Part 3: Model instantiation

The model represents a wff for propositional logic. This wff is in part defined by the input string passed to the meta-model. In this section, we implement the meta-model and show how to generate a model.

Meta-model

The meta-model is generated from the language grammar and the custom classes. The language grammar allows the parser to recognize a string of the language and construct the AST. The custom classes allow us to customize the behavior of the objects making the model (i.e., the AST).

Creating a meta-model is made simple with textX. First, we import textX library. Then we create a list composed of the concrete classes that we defined; for now they do not contain any methods, but we will add it later. And lastly, generate the meta-model with the textX.metamodel_from_str method. The method takes the grammar and list of classes as arguments.

import textX

grammar = """
Model: wff=WFF;
WFF: Atom | Negation | Conjunction | Disjunction | Implication | Equivalence;
Atom: id=ID;
Negation: '~' wff=WFF;
Conjunction: '(' lhs=WFF '&' rhs=WFF ')';
Disjunction: '(' lhs=WFF '|' rhs=WFF ')';
Implication: '(' lhs=WFF '=>' rhs=WFF ')';
Equivalence: '(' lhs=WFF '<=>' rhs=WFF ')';
"""
classes = [Atom, Negation, Conjunction, Disjunction, Implication, Equivalence]
metamodel = textX.metamodel_from_str(grammar, classes)

Model

The model is an AST representation of the wff, which is initially represented as a string (the program’s input). Make sure that the wff string is valid as per the grammar. In particular, the binary connectives must always be enclosed by parentheses.

Creating the model from an input string is quite straightforward. Just pass a string representing the wff to the metamodel.mode_from_str method.

wff_example = "(~(A&B)=>C)"
model = metamodel.model_from_str(wff_example)

However, model is not of type WFF, it is of type Model. This is because the first rule to match is the “root rule” defined earlier, which generates a Model object. Therefore, to get the top-most WFF in the AST, we need to access the wff parameter of model.

wff = model.wff

In the next part, we will visualize the meta-model and model as an AST image.