Runtime API: package grammarinator.runtime¶
- class grammarinator.runtime.Annotations(root)[source]¶
Bases:
objectClass for calculating and managing additional metadata needed by the mutators, particularly to enforce size constraints and facilitate node filtering by rule types.
- Parameters:
root (
Rule) – Root of the tree to be annotated.
- property quants: list[UnparserRuleQuantifier]¶
Get nodes created from quantified expressions.
- Returns:
List of quantifier nodes.
- property rules: list[UnlexerRule | UnparserRule]¶
Get nodes created from rule nodes.
- Returns:
List of rule nodes.
- class grammarinator.runtime.DefaultModel[source]¶
Bases:
ModelDefault decision model implementation.
- charset(node, idx, chars)[source]¶
A single character is chosen randomly from the set of possible options (
chars).Parameters
nodeandidxare unused.- Return type:
- choice(node, idx, weights)[source]¶
The decision is solely based upon the provided
weights.Parameters
nodeandidxare unused.- Return type:
- quantify(node, idx, cnt, start, stop, prob=0.5)[source]¶
After generating the minimum expected items (
start) and before reaching the maximum expected items (stop), quantify decides about the expansion of the optional items based on a random binary decision.Parameters
node,idx,cnt,start, andstopare unused.- Return type:
- class grammarinator.runtime.DispatchingListener[source]¶
Bases:
ListenerBase class of custom listeners that aim to override the enter and exit actions for specific rules. Subclassing
DispatchingListenerenables to define the enter and exit methods of a rule in the form of[enter|exit]_{rule_name}.
- class grammarinator.runtime.DispatchingModel[source]¶
Bases:
DefaultModelBase class of custom models that aim to override the decisions in specific rules. To override a decision point, the subclass must define methods in the form of
choice_{rule_name},quantify_{rule_name}orcharset_{rule_name}- with the same signature as their counterparts inDefaultModel- in case of overriding an alternation, quantifier or charset decision, respectively.- charset(node, idx, chars)[source]¶
Trampoline to the
charset_{node.name}method of the subclassed model, if it exists. Otherwise, it calls the default implementation (DefaultModel.charset()).- Return type:
- choice(node, idx, weights)[source]¶
Trampoline to the
choice_{node.name}method of the subclassed model, if it exists. Otherwise, it calls the default implementation (DefaultModel.choice()).- Return type:
- quantify(node, idx, cnt, start, stop, prob=0.5)[source]¶
Trampoline to the
quantify_{node.name}method of the subclassed model, if it exists. Otherwise, it calls the default implementation (DefaultModel.quantify()).- Return type:
- class grammarinator.runtime.Generator(*, model=None, listeners=None, limit=None)[source]¶
Bases:
objectBase class of the generated Generators. Stores the decision model, the listeners, and additional internal state used during generation.
- Parameters:
model (
Model|None) – Model object responsible for every decision during the generation. (default:DefaultModel).listeners (
list[Listener] |None) – Listeners that get notified whenever a rule is entered or exited.limit (
RuleSize|None) – The limit on the depth of the trees and on the number of tokens (number of unlexer rule calls), i.e., it must be possible to finish generation from the selected node so that the overall depth and token count of the tree does not exceed these limits (default:RuleSize.max).
- class grammarinator.runtime.Individual(root=None)[source]¶
Bases:
objectAbstract base class of population individuals.
- property annotations: Annotations¶
Return the associated annotations if available, otherwise compute them immediately.
- Returns:
The annotations associated with the tree.
- class grammarinator.runtime.Listener[source]¶
Bases:
objectBase class of listeners that get notified by generators whenever a rule is entered or exited. which needs to be subclassed.
- class grammarinator.runtime.Model[source]¶
Bases:
objectAbstract base class of models that make decisions for generators at alternations, quantifiers, and charsets.
- charset(node, idx, chars)[source]¶
Choose a character from a charset.
Raises
NotImplementedErrorby default.- Parameters:
- Return type:
- Returns:
The chosen character.
- choice(node, idx, weights)[source]¶
Choose an alternative from an alternation.
Raises
NotImplementedErrorby default.- Parameters:
- Return type:
- Returns:
The index of the chosen alternative.
- quantify(node, idx, cnt, start, stop, prob=0.5)[source]¶
Guide the loop of subtree quantification. This has to make a binary decision to tell whether to enable the next iteration or stop the loop.
Raises
NotImplementedErrorby default.- Parameters:
node (
Rule) – The current node. Itsnamefield identifies the corresponding grammar rule, which contains the quantified subtree.idx (
int) – Index of the quantified subtree inside the current rule.cnt (
int) – Number of the already generated subtrees, guaranteed to be betweenstart(inclusive) andstop(exclusive).start (
int) – Lower bound of the quantification range.stop (
int|float) – Upper bound of the quantification range.prob (
float) – Predefined probability of enabling the next iteration (between 0 and 1).
- Return type:
- Returns:
Boolean value enabling the next iteration or stopping it.
- class grammarinator.runtime.ParentRule(*, name, children=None)[source]¶
Bases:
RuleAbstract base class of tree nodes that can have children.
- Parameters:
- __iadd__(item)[source]¶
Support for
+=operation to add one or more children to the current node. An alias toadd_child()oradd_children()depending on the type ofchild.
- equals(other)[source]¶
Compare two nodes (potentially including any children) for equality. The comparison is not implemented within
__eq__to ensure that nodes can be added to collections based on identity.
- class grammarinator.runtime.Population[source]¶
Bases:
objectAbstract base class of populations that store test cases in tree form (i.e., individuals) and can select trees for mutation or recombination based on some strategy.
- add_individual(root, path=None)[source]¶
Add a tree to the population.
Raises
NotImplementedErrorby default.
- empty()[source]¶
Return whether the population is empty.
Raises
NotImplementedErrorby default.- Return type:
- Returns:
Trueif the population is empty andFalseotherwise.
- select_individual(recipient=None)[source]¶
Select an individual of the population.
Raises
NotImplementedErrorby default.- Parameters:
recipient (
Individual|None) – If None, the caller looks for an individual that could be mutated or recombined (i.e., a recipient). If not None, the caller looks for an individual (i.e., a donor) that could be recombined with the given individual (i.e., with the recipient).- Return type:
- Returns:
A single individual of the population.
- class grammarinator.runtime.Rule(*, name)[source]¶
Bases:
objectAbstract base class of tree nodes.
Tree nodes support deep copying via
copy.deepcopy()(but no shallow copying viacopy.copy()). A deep copy of a node is the copy of the whole subtree rooted at that node. However, the parent of a copy node is always None, even if the original node had a parent.Tree nodes support various string representations:
The “informal” representation of a node consists of the concatenation of the string contents of all tokens found in the tree rooted at the node in depth-first order. No extra whitespace is inserted for separation.
The “official” representation of a node is an (almost) valid Python expression to recreate the tree rooted at the node. If the node has any children, the representation consists of multiple lines.
The “debug” representation of a node is a multi-line string with the most important attributes of the tree rooted at the node, using vertical bars for visual guidance.
The builtins
strandrepr()can be used to compute the “informal” and “official” representations, respectively, whileformat()can produce all of the above. When string formatting is used, the following format specifiers are recognized:Specifier
Meaning
''or's'“Informal” representation.
'r'“Official” representation.
'|'“Debug” representation.
Thus, if
nis a node, the following expressions give equivalent results:str(n),f'{n}',f'{n!s}',f'{n:s}','{}'.format(n),'{!s}'.format(n), and'{:s}'.format(n)repr(n),f'{n!r}',f'{n:r}','{!r}'.format(n), and'{:r}'.format(n)f'{n:|}'and'{:|}'.format(n)
- Parameters:
name (
str) – Name of the node, i.e., name of the corresponding parser or lexer rule in the grammar.
- equals(other)[source]¶
Compare two nodes (potentially including any children) for equality. The comparison is not implemented within
__eq__to ensure that nodes can be added to collections based on identity.
- property left_sibling: Rule | None¶
Get the left sibling of the node if any. Return
Noneif the node has no parent or is the leftmost child of its parent.- Returns:
The left sibling of the current node or
None.
- parent: ParentRule | None¶
Parent node object.
- property right_sibling: Rule | None¶
Get the right sibling of the node if any. Return
Noneif the node has no parent or is the rightmost child of its parent.- Returns:
The right sibling of the current node or
None.
- class grammarinator.runtime.RuleSize(depth=0, tokens=0)[source]¶
Bases:
objectSize information about a grammar rule or a (sub)tree (generated based on a grammar rule), expressed using different metrics (both vertical and horizontal).
This class can be used to describe various size-related concepts, e.g.:
The minimum depth of derivation of a grammar rule and the minimum number of tokens generated by a grammar rule.
The actual depth of derivation of a grammar rule and the actual number of tokens generated by a grammar rule.
The maximum allowed depth of derivation in a tree and the maximum number of tokens allowed in a tree.
The depth of derivation reaching a node from the root of the tree and the number of tokens in the tree outside the subtree of the node.
The class supports additive arithmetics (
+,+=,-,-=) and comparisons (==,<=,<). Note, however, that the type is not totally but partially ordered, i.e., a size object is less than another size object iff all its metrics compare less than the corresponding metrics of the other size object.- Parameters:
- class grammarinator.runtime.UnlexerRule(*, name, src='', size=None, immutable=False)[source]¶
Bases:
RuleTree node representing a lexer rule or token. It has a string constant set in its
srcfield.- Parameters:
- equals(other)[source]¶
Compare two nodes (potentially including any children) for equality. The comparison is not implemented within
__eq__to ensure that nodes can be added to collections based on identity.
- class grammarinator.runtime.UnparserRule(*, name, children=None)[source]¶
Bases:
ParentRuleTree node representing a parser rule. It can have zero or more
UnparserRule,UnlexerRule,UnparserRuleQuantifierorUnparserRuleAlternativechildren.- Parameters:
- class grammarinator.runtime.UnparserRuleAlternative(*, alt_idx, idx, children=None)[source]¶
Bases:
ParentRuleTree node representing a sub-tree of an alternative. It can have zero or more
UnparserRule,UnlexerRule,UnparserRuleQuantifierorUnparserRuleAlternativechildren.- Parameters:
- class grammarinator.runtime.UnparserRuleQuantified(*, children=None)[source]¶
Bases:
ParentRuleTree node representing a single instance of quantified sub-tree. It can have one or more
UnparserRule,UnlexerRule,UnparserRuleQuantifierorUnparserRuleAlternativechildren.
- class grammarinator.runtime.UnparserRuleQuantifier(*, idx, start, stop, children=None)[source]¶
Bases:
ParentRuleTree node representing the root of a quantified sub-tree. It can have one or more
UnparserRuleQuantifiedchildren.- Parameters:
- class grammarinator.runtime.WeightedModel(model, *, weights=None, probs=None)[source]¶
Bases:
ModelCustom model (or model wrapper) that pre-multiplies the weights of alternatives before calling the underlying model.
- Parameters:
model (
Model) – The underlying model.weights (
dict[tuple[str,int,int],float] |None) – Multipliers of alternatives. The keys of the dictionary are tuples in the form of(str, int, int), each denoting an alternative: the first element specifies the name of the rule that contains the alternative, the second element specifies the index of the alternation containing the alternative within the rule, and the third element specifies the index of the alternative within the alternation (both indices start counting from 0). The first and second elements correspond to thenodeandidxparameters ofchoice(), while the third element corresponds to the indices of theweightsparameter.probs (
dict[tuple[str,int],float] |None) – Custom probabilities for quantifiers. The keys of the dictionary are tuples in the form of(str, int), each denoting a quantifier: the first element specifies the name of the rule that contains the quantifier, and the second element specifies the index of the quantifier within the rule (index starts counting from 0). The first and second elements correspond to thenodeandidxparameters ofquantify().
- charset(node, idx, chars)[source]¶
Trampoline to the
charsetmethod of the underlying model.- Return type:
- grammarinator.runtime.simple_space_serializer(root)[source]¶
Simple serializer concatenating the children of
UnparserRules with a single space.