markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Here is another record from that CSV file: | mystring = '''\
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00
'''
print(mystring)
tree = parse_csv(mystring)
bad_nodes = {5, 6, 7, 8, 9, 10}
display_tree(tree, node_attr=highlight_err_node, graph_attr=lr_graph) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Fixing this would require modifying both inner `parse_quote()` and the outer `parse_csv()` procedures. We note that each of these features actually documented in the CSV [RFC 4180](https://tools.ietf.org/html/rfc4180) Indeed, each additional improvement falls apart even with a little extra complexity. The problem becom... | A1_GRAMMAR: Grammar = {
"<start>": ["<expr>"],
"<expr>": ["<expr>+<expr>", "<expr>-<expr>", "<integer>"],
"<integer>": ["<digit><integer>", "<digit>"],
"<digit>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
}
syntax_diagram(A1_GRAMMAR) | start
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
In the above expression, the rule ` : [+,-,]` corresponds to how the nonterminal `` might be expanded. The expression `+` corresponds to one of the alternative choices. We call this an _alternative_ expansion for the nonterminal ``. Finally, in an expression `+`, each of ``, `+`, and `` are _symbols_ in that expansion... | mystring = '1+2' | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The _derivation tree_ for our expression from this grammar is given by: | tree = ('<start>', [('<expr>',
[('<expr>', [('<integer>', [('<digit>', [('1', [])])])]),
('+', []),
('<expr>', [('<integer>', [('<digit>', [('2',
[])])])])])])
assert mystring == tree_to_strin... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
While a grammar can be used to specify a given language, there could be multiplegrammars that correspond to the same language. For example, here is another grammar to describe the same addition expression. | A2_GRAMMAR: Grammar = {
"<start>": ["<expr>"],
"<expr>": ["<integer><expr_>"],
"<expr_>": ["+<expr>", "-<expr>", ""],
"<integer>": ["<digit><integer_>"],
"<integer_>": ["<integer>", ""],
"<digit>": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
}
syntax_diagram(A2_GRAMMAR) | start
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The corresponding derivation tree is given by: | tree = ('<start>', [('<expr>', [('<integer>', [('<digit>', [('1', [])]),
('<integer_>', [])]),
('<expr_>', [('+', []),
('<expr>',
[('<integer>',
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Indeed, there could be different classes of grammars thatdescribe the same language. For example, the first grammar `A1_GRAMMAR`is a grammar that sports both _right_ and _left_ recursion, while thesecond grammar `A2_GRAMMAR` does not have left recursion in thenonterminals in any of its productions, but contains _epsilo... | LR_GRAMMAR: Grammar = {
'<start>': ['<A>'],
'<A>': ['<A>a', ''],
}
syntax_diagram(LR_GRAMMAR)
mystring = 'aaaaaa'
display_tree(
('<start>', [('<A>', [('<A>', [('<A>', []), ('a', [])]), ('a', [])]),
('a', [])])) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
A grammar is indirectly left-recursive if anyof the left-most symbols can be expanded using their definitions toproduce the nonterminal as the left-most symbol of the expansion. The leftrecursion is called a _hidden-left-recursion_ if during the series ofexpansions of a nonterminal, one reaches a rule where the rule c... | RR_GRAMMAR: Grammar = {
'<start>': ['<A>'],
'<A>': ['a<A>', ''],
}
syntax_diagram(RR_GRAMMAR)
display_tree(('<start>', [('<A>', [
('a', []), ('<A>', [('a', []), ('<A>', [('a', []), ('<A>', [])])])])]
)) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
AmbiguityTo complicate matters further, there could bemultiple derivation trees – also called _parses_ – corresponding to thesame string from the same grammar. For example, a string `1+2+3` can be parsedin two ways as we see below using the `A1_GRAMMAR` | mystring = '1+2+3'
tree = ('<start>',
[('<expr>',
[('<expr>', [('<expr>', [('<integer>', [('<digit>', [('1', [])])])]),
('+', []),
('<expr>', [('<integer>',
[('<digit>', [('2', [])])])])]), ('+', []),
('<expr>... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
There are many ways to resolve ambiguities. One approach taken by *Parsing Expression Grammars* explained in the next section is to specify a particular order of resolution, and choose the first one. Another approach is to simply return all possible derivation trees, which is the approach taken by *Earley parser* we de... | class Parser:
"""Base class for parsing."""
def __init__(self, grammar: Grammar, *,
start_symbol: str = START_SYMBOL,
log: bool = False,
coalesce: bool = True,
tokens: Set[str] = set()) -> None:
"""Constructor.
`grammar` is ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Excursion: Canonical Grammars The `EXPR_GRAMMAR` we import from the [chapter on grammars](Grammars.ipynb) is oriented towards generation. In particular, the production rules are stored as strings. We need to massage this representation a little to conform to a _canonical representation_ where each token in a rule is ... | CanonicalGrammar = Dict[str, List[List[str]]]
import re
def single_char_tokens(grammar: Grammar) -> Dict[str, List[List[Collection[str]]]]:
g_ = {}
for key in grammar:
rules_ = []
for rule in grammar[key]:
rule_ = []
for token in rule:
if token in grammar:... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We also provide a convenience method for easier display of canonical grammars. | def recurse_grammar(grammar, key, order):
rules = sorted(grammar[key])
old_len = len(order)
for rule in rules:
for token in rule:
if token not in grammar: continue
if token not in order:
order.append(token)
new = order[old_len:]
for ckey in new:
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We provide a way to revert a canonical expression. | def non_canonical(grammar):
new_grammar = {}
for k in grammar:
rules = grammar[k]
new_rules = []
for rule in rules:
new_rules.append(''.join(rule))
new_grammar[k] = new_rules
return new_grammar
non_canonical(CE_GRAMMAR) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
It is easier to work with the `canonical` representation during parsing. Hence, we update our parser class to store the `canonical` representation also. | class Parser(Parser):
def __init__(self, grammar, **kwargs):
self._start_symbol = kwargs.get('start_symbol', START_SYMBOL)
self.log = kwargs.get('log', False)
self.tokens = kwargs.get('tokens', set())
self.coalesce_tokens = kwargs.get('coalesce', True)
canonical_grammar = kwa... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We update the `prune_tree()` to account for the phony start symbol if it was insserted. | class Parser(Parser):
def prune_tree(self, tree):
name, children = tree
if name == '<>':
assert len(children) == 1
return self.prune_tree(children[0])
if self.coalesce_tokens:
children = self.coalesce(children)
if name in self.tokens:
r... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
End of Excursion Parsing Expression GrammarsA _[Parsing Expression Grammar](http://bford.info/pub/lang/peg)_ (*PEG*) \cite{Ford2004} is a type of _recognition based formal grammar_ that specifies the sequence of steps to take to parse a given string.A _parsing expression grammar_ is very similar to a _context-free gr... | PEG1 = {
'<start>': ['a', 'b']
} | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
However, unlike the _CFG_, the alternatives represent *ordered choice*. That is, rather than choosing all rules that can potentially match, we stop at the first match that succeed. For example, the below _PEG_ can match `ab` but not `abc` unlike a _CFG_ which will match both. (We call the sequence of ordered choice exp... | PEG2 = {
'<start>': ['ab', 'abc']
} | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Each choice in a _choice expression_ represents a rule on how to satisfy that particular choice. The choice is a sequence of symbols (terminals and nonterminals) that are matched against a given text as in a _CFG_. Beyond the syntax of grammar definitions we have seen so far, a _PEG_ can also contain a few additional e... | class PEGParser(Parser):
def parse_prefix(self, text):
cursor, tree = self.unify_key(self.start_symbol(), text, 0)
return cursor, [tree] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Excursion: Implementing `PEGParser` Unify KeyThe `unify_key()` algorithm is simple. If given a terminal symbol, it tries to match the symbol with the current position in the text. If the symbol and text match, it returns successfully with the new parse index `at`.If on the other hand, it was given a nonterminal, it r... | class PEGParser(PEGParser):
"""Packrat parser for Parsing Expression Grammars (PEGs)."""
def unify_key(self, key, text, at=0):
if self.log:
print("unify_key: %s with %s" % (repr(key), repr(text[at:])))
if key not in self.cgrammar:
if text[at:].startswith(key):
... | unify_key: '1' with '2'
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Unify RuleThe `unify_rule()` method is similar. It retrieves the tokens corresponding to the rule that it needs to unify with the text, and calls `unify_key()` on them in sequence. If **all** tokens are successfully unified with the text, the parse is a success. | class PEGParser(PEGParser):
def unify_rule(self, rule, text, at):
if self.log:
print('unify_rule: %s with %s' % (repr(rule), repr(text[at:])))
results = []
for token in rule:
at, res = self.unify_key(token, text, at)
if res is None:
return ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The two methods are mutually recursive, and given that `unify_key()` tries each alternative until it succeeds, `unify_key` can be called multiple times with the same arguments. Hence, it is important to memoize the results of `unify_key`. Python provides a simple decorator `lru_cache` for memoizing any function call th... | from functools import lru_cache
class PEGParser(PEGParser):
@lru_cache(maxsize=None)
def unify_key(self, key, text, at=0):
if key not in self.cgrammar:
if text[at:].startswith(key):
return at + len(key), (key, [])
else:
return at, None
for ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We wrap initialization and calling of `PEGParser` in a method `parse()` already implemented in the `Parser` base class that accepts the text to be parsed along with the grammar. End of Excursion Here are a few examples of our parser in action. | mystring = "1 + (2 * 3)"
peg = PEGParser(EXPR_GRAMMAR)
for tree in peg.parse(mystring):
assert tree_to_string(tree) == mystring
display(display_tree(tree))
mystring = "1 * (2 + 3.35)"
for tree in peg.parse(mystring):
assert tree_to_string(tree) == mystring
display(display_tree(tree)) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
One should be aware that while the grammar looks like a *CFG*, the language described by a *PEG* may be different. Indeed, only *LL(1)* grammars are guaranteed to represent the same language for both PEGs and other parsers. Behavior of PEGs for other classes of grammars could be surprising \cite{redziejowski2008}. Pa... | PEG_SURPRISE: Grammar = {
"<A>": ["a<A>a", "aa"]
} | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
When interpreted as a *CFG* and used as a string generator, it will produce strings of the form `aa, aaaa, aaaaaa` that is, it produces strings where the number of `a` is $ 2*n $ where $ n > 0 $. | strings = []
for nn in range(4):
f = GrammarFuzzer(PEG_SURPRISE, start_symbol='<A>')
tree = ('<A>', None)
for _ in range(nn):
tree = f.expand_tree_once(tree)
tree = f.expand_tree_with_strategy(tree, f.expand_node_min_cost)
strings.append(tree_to_string(tree))
display_tree(tree)
strings | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
However, the _PEG_ parser can only recognize strings of the form $2^n$ | peg = PEGParser(PEG_SURPRISE, start_symbol='<A>')
for s in strings:
with ExpectError():
for tree in peg.parse(s):
display_tree(tree)
print(s) | aa
aaaa
aaaaaaaa
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
This is not the only problem with _Parsing Expression Grammars_. While *PEGs* are expressive and the *packrat* parser for parsing them is simple and intuitive, *PEGs* suffer from a major deficiency for our purposes. *PEGs* are oriented towards language recognition, and it is not clear how to translate an arbitrary *PE... | SAMPLE_GRAMMAR: Grammar = {
'<start>': ['<A><B>'],
'<A>': ['a<B>c', 'a<A>'],
'<B>': ['b<C>', '<D>'],
'<C>': ['c'],
'<D>': ['d']
}
C_SAMPLE_GRAMMAR = canonical(SAMPLE_GRAMMAR)
syntax_diagram(SAMPLE_GRAMMAR) | start
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The basic idea of Earley parsing is the following:* Start with the alternative expressions corresponding to the START_SYMBOL. These represent the possible ways to parse the string from a high level. Essentially each expression represents a parsing path. Queue each expression in our set of possible parses of the string.... | class Column:
def __init__(self, index, letter):
self.index, self.letter = index, letter
self.states, self._unique = [], {}
def __str__(self):
return "%s chart[%d]\n%s" % (self.letter, self.index, "\n".join(
str(state) for state in self.states if state.finished())) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The `Column` only stores unique `states`. Hence, when a new `state` is `added` to our `Column`, we check whether it is already known. | class Column(Column):
def add(self, state):
if state in self._unique:
return self._unique[state]
self._unique[state] = state
self.states.append(state)
state.e_col = self
return self._unique[state] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
ItemsAn item represents a _parse in progress for a specific rule._ Hence the item contains the name of the nonterminal, and the corresponding alternative expression (`expr`) which together form the rule, and the current position of parsing in this expression -- `dot`.**Note.** If you are familiar with [LR parsing](htt... | class Item:
def __init__(self, name, expr, dot):
self.name, self.expr, self.dot = name, expr, dot | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We also provide a few convenience methods. The method `finished()` checks if the `dot` has moved beyond the last element in `expr`. The method `advance()` produces a new `Item` with the `dot` advanced one token, and represents an advance of the parsing. The method `at_dot()` returns the current symbol being parsed. | class Item(Item):
def finished(self):
return self.dot >= len(self.expr)
def advance(self):
return Item(self.name, self.expr, self.dot + 1)
def at_dot(self):
return self.expr[self.dot] if self.dot < len(self.expr) else None | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Here is how an item could be used. We first define our item | item_name = '<B>'
item_expr = C_SAMPLE_GRAMMAR[item_name][1]
an_item = Item(item_name, tuple(item_expr), 0) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
To determine where the status of parsing, we use `at_dot()` | an_item.at_dot() | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
That is, the next symbol to be parsed is `` If we advance the item, we get another item that represents the finished parsing rule ``. | another_item = an_item.advance()
another_item.finished() | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
StatesFor `Earley` parsing, the state of the parsing is simply one `Item` along with some meta information such as the starting `s_col` and ending column `e_col` for each state. Hence we inherit from `Item` to create a `State`.Since we are interested in comparing states, we define `hash()` and `eq()` with the corresp... | class State(Item):
def __init__(self, name, expr, dot, s_col, e_col=None):
super().__init__(name, expr, dot)
self.s_col, self.e_col = s_col, e_col
def __str__(self):
def idx(var):
return var.index if var else -1
return self.name + ':= ' + ' '.join([
str(... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The usage of `State` is similar to that of `Item`. The only difference is that it is used along with the `Column` to track the parsing state. For example, we initialize the first column as follows: | col_0 = Column(0, None)
item_tuple = tuple(*C_SAMPLE_GRAMMAR[START_SYMBOL])
start_state = State(START_SYMBOL, item_tuple, 0, col_0)
col_0.add(start_state)
start_state.at_dot() | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The first column is then updated by using `add()` method of `Column` | sym = start_state.at_dot()
for alt in C_SAMPLE_GRAMMAR[sym]:
col_0.add(State(sym, tuple(alt), 0, col_0))
for s in col_0.states:
print(s) | <start>:= | <A> <B>(0,0)
<A>:= | a <B> c(0,0)
<A>:= | a <A>(0,0)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The Parsing Algorithm The _Earley_ algorithm starts by initializing the chart with columns (as many as there are letters in the input). We also seed the first column with a state representing the expression corresponding to the start symbol. In our case, the state corresponds to the start symbol with the `dot` at `0` ... | class EarleyParser(Parser):
"""Earley Parser. This parser can parse any context-free grammar."""
def __init__(self, grammar: Grammar, **kwargs) -> None:
super().__init__(grammar, **kwargs)
self.chart: List = [] # for type checking
def chart_parse(self, words, start):
alt = tuple(*... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The main parsing loop in `fill_chart()` has three fundamental operations. `predict()`, `scan()`, and `complete()`. We discuss `predict` next. Predicting StatesWe have already seeded `chart[0]` with a state `[,]` with `dot` at `0`. Next, given that `` is a nonterminal, we `predict` the possible parse continuations of t... | class EarleyParser(EarleyParser):
def predict(self, col, sym, state):
for alt in self.cgrammar[sym]:
col.add(State(sym, tuple(alt), 0, col)) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
To see how to use `predict`, we first construct the 0th column as before, and we assign the constructed column to an instance of the EarleyParser. | col_0 = Column(0, None)
col_0.add(start_state)
ep = EarleyParser(SAMPLE_GRAMMAR)
ep.chart = [col_0] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
It should contain a single state -- ` at 0` | for s in ep.chart[0].states:
print(s) | <start>:= | <A> <B>(0,0)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We apply predict to fill out the 0th column, and the column should contain the possible parse paths. | ep.predict(col_0, '<A>', s)
for s in ep.chart[0].states:
print(s) | <start>:= | <A> <B>(0,0)
<A>:= | a <B> c(0,0)
<A>:= | a <A>(0,0)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Scanning TokensWhat if rather than a nonterminal, the state contained a terminal symbol such as a letter? In that case, we are ready to make some progress. For example, consider the second state:```: ● b c```We `scan` the next column's letter. Say the next token is `b`.If the letter matches what we have, then create a... | class EarleyParser(EarleyParser):
def scan(self, col, state, letter):
if letter == col.letter:
col.add(state.advance()) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
As before, we construct the partial parse first, this time adding a new column so that we can observe the effects of `scan()` | ep = EarleyParser(SAMPLE_GRAMMAR)
col_1 = Column(1, 'a')
ep.chart = [col_0, col_1]
new_state = ep.chart[0].states[1]
print(new_state)
ep.scan(col_1, new_state, 'a')
for s in ep.chart[1].states:
print(s) | <A>:= a | <B> c(0,1)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Completing ProcessingWhen we advance, what if we actually `complete()` the processing of the current rule? If so, we want to update not just this state, but also all the _parent_ states from which this state was derived.For example, say we have states as below.```: a ● c: b c ● ```The state `: b c ●` is now complete.... | class EarleyParser(EarleyParser):
def complete(self, col, state):
return self.earley_complete(col, state)
def earley_complete(self, col, state):
parent_states = [
st for st in state.s_col.states if st.at_dot() == state.name
]
for st in parent_states:
col.... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Here is an example of completed processing. First we complete the Column 0 | ep = EarleyParser(SAMPLE_GRAMMAR)
col_1 = Column(1, 'a')
col_2 = Column(2, 'd')
ep.chart = [col_0, col_1, col_2]
ep.predict(col_0, '<A>', s)
for s in ep.chart[0].states:
print(s) | <start>:= | <A> <B>(0,0)
<A>:= | a <B> c(0,0)
<A>:= | a <A>(0,0)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Then we use `scan()` to populate Column 1 | for state in ep.chart[0].states:
if state.at_dot() not in SAMPLE_GRAMMAR:
ep.scan(col_1, state, 'a')
for s in ep.chart[1].states:
print(s)
for state in ep.chart[1].states:
if state.at_dot() in SAMPLE_GRAMMAR:
ep.predict(col_1, state.at_dot(), state)
for s in ep.chart[1].states:
print(s) | <A>:= a | <B> c(0,1)
<A>:= a | <A>(0,1)
<B>:= | b <C>(1,1)
<B>:= | <D>(1,1)
<A>:= | a <B> c(1,1)
<A>:= | a <A>(1,1)
<D>:= | d(1,1)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Then we use `scan()` again to populate Column 2 | for state in ep.chart[1].states:
if state.at_dot() not in SAMPLE_GRAMMAR:
ep.scan(col_2, state, state.at_dot())
for s in ep.chart[2].states:
print(s) | <D>:= d |(1,2)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Now, we can use `complete()`: | for state in ep.chart[2].states:
if state.finished():
ep.complete(col_2, state)
for s in ep.chart[2].states:
print(s) | <D>:= d |(1,2)
<B>:= <D> |(1,2)
<A>:= a <B> | c(0,2)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Filling the ChartThe main driving loop in `fill_chart()` essentially calls these operations in order. We loop over each column in order.* For each column, fetch one state in the column at a time, and check if the state is `finished`. * If it is, then we `complete()` all the parent states depending on this state. *... | class EarleyParser(EarleyParser):
def fill_chart(self, chart):
for i, col in enumerate(chart):
for state in col.states:
if state.finished():
self.complete(col, state)
else:
sym = state.at_dot()
if sym in ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We now can recognize a given string as belonging to a language represented by a grammar. | ep = EarleyParser(SAMPLE_GRAMMAR, log=True)
columns = ep.chart_parse('adcd', START_SYMBOL) | None chart[0]
a chart[1]
d chart[2]
<D>:= d |(1,2)
<B>:= <D> |(1,2)
c chart[3]
<A>:= a <B> c |(0,3)
d chart[4]
<D>:= d |(3,4)
<B>:= <D> |(3,4)
<start>:= <A> <B> |(0,4)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The chart we printed above only shows completed entries at each index. The parenthesized expression indicates the column just before the first character was recognized, and the ending column.Notice how the `` nonterminal shows fully parsed status. | last_col = columns[-1]
for state in last_col.states:
if state.name == '<start>':
print(state) | <start>:= <A> <B> |(0,4)
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Since `chart_parse()` returns the completed table, we now need to extract the derivation trees. The Parse MethodFor determining how far we have managed to parse, we simply look for the last index from `chart_parse()` where the `start_symbol` was found. | class EarleyParser(EarleyParser):
def parse_prefix(self, text):
self.table = self.chart_parse(text, self.start_symbol())
for col in reversed(self.table):
states = [
st for st in col.states if st.name == self.start_symbol()
]
if states:
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Here is the `parse_prefix()` in action. | ep = EarleyParser(SAMPLE_GRAMMAR)
cursor, last_states = ep.parse_prefix('adcd')
print(cursor, [str(s) for s in last_states]) | 4 ['<start>:= <A> <B> |(0,4)']
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The following is adapted from the excellent reference on Earley parsing by [Loup Vaillant](http://loup-vaillant.fr/tutorials/earley-parsing/). Our `parse()` method is as follows. It depends on two methods `parse_forest()` and `extract_trees()` that will be defined next. | class EarleyParser(EarleyParser):
def parse(self, text):
cursor, states = self.parse_prefix(text)
start = next((s for s in states if s.finished()), None)
if cursor < len(text) or not start:
raise SyntaxError("at " + repr(text[cursor:]))
forest = self.parse_forest(self.t... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Parsing PathsThe `parse_paths()` method tries to unify the given expression in `named_expr` with the parsed string. For that, it extracts the last symbol in `named_expr` and checks if it is a terminal symbol. If it is, then it checks the chart at `til` to see if the letter corresponding to the position matches the ter... | class EarleyParser(EarleyParser):
def parse_paths(self, named_expr, chart, frm, til):
def paths(state, start, k, e):
if not e:
return [[(state, k)]] if start == frm else []
else:
return [[(state, k)] + r
for r in self.parse_path... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Here is the `parse_paths()` in action | print(SAMPLE_GRAMMAR['<start>'])
ep = EarleyParser(SAMPLE_GRAMMAR)
completed_start = last_states[0]
paths = ep.parse_paths(completed_start.expr, columns, 0, 4)
for path in paths:
print([list(str(s_) for s_ in s) for s in path]) | ['<A><B>']
[['<B>:= <D> |(3,4)', 'n'], ['<A>:= a <B> c |(0,3)', 'n']]
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
That is, the parse path for `` given the input `adcd` included recognizing the expression ``. This was recognized by the two states: `` from input(0) to input(2) which further involved recognizing the rule `ac`, and the next state `` from input(3) which involved recognizing the rule ``. Parsing ForestsThe `parse_fores... | class EarleyParser(EarleyParser):
def forest(self, s, kind, chart):
return self.parse_forest(chart, s) if kind == 'n' else (s, [])
def parse_forest(self, chart, state):
pathexprs = self.parse_paths(state.expr, chart, state.s_col.index,
state.e_col.index) if ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Extracting Trees What we have from `parse_forest()` is a forest of trees. We need to extract a single tree from that forest. That is accomplished as follows. (For now, we return the first available derivation tree. To do that, we need to extract the parse forest from the state corresponding to `start`.) | class EarleyParser(EarleyParser):
def extract_a_tree(self, forest_node):
name, paths = forest_node
if not paths:
return (name, [])
return (name, [self.extract_a_tree(self.forest(*p)) for p in paths[0]])
def extract_trees(self, forest):
yield self.extract_a_tree(fores... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We now verify that our parser can parse a given expression. | A3_GRAMMAR: Grammar = {
"<start>": ["<bexpr>"],
"<bexpr>": [
"<aexpr><gt><aexpr>", "<aexpr><lt><aexpr>", "<aexpr>=<aexpr>",
"<bexpr>=<bexpr>", "<bexpr>&<bexpr>", "<bexpr>|<bexpr>", "(<bexrp>)"
],
"<aexpr>":
["<aexpr>+<aexpr>", "<aexpr>-<aexpr>", "(<aexpr>)", "<integer>"],
"<integ... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We now have a complete parser that can parse almost arbitrary *CFG*. There remains a small corner to fix -- the case of epsilon rules as we will see later. Ambiguous Parsing Ambiguous grammars are grammars that can produce multiple derivation trees for some given string. For example, the `A3_GRAMMAR` can parse `1+2+3`... | import itertools as I
class EarleyParser(EarleyParser):
def extract_trees(self, forest_node):
name, paths = forest_node
if not paths:
yield (name, [])
for path in paths:
ptrees = [self.extract_trees(self.forest(*p)) for p in path]
for p in I.product(*ptre... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
As before, we verify that everything works. | mystring = '1+2'
parser = EarleyParser(A1_GRAMMAR)
for tree in parser.parse(mystring):
assert mystring == tree_to_string(tree)
display_tree(tree) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
One can also use a `GrammarFuzzer` to verify that everything works. | gf = GrammarFuzzer(A1_GRAMMAR)
for i in range(5):
s = gf.fuzz()
print(i, s)
for tree in parser.parse(s):
assert tree_to_string(tree) == s | 0 045+3+2-9+7-7-5-1-449
1 0+9+5-2+1-8+4-3+7+2
2 76413
3 9339
4 62
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The Aycock Epsilon FixWhile parsing, one often requires to know whether a given nonterminal can derive an empty string. For example, in the following grammar A can derive an empty string, while B can't. The nonterminals that can derive an empty string are called _nullable_ nonterminals. For example, in the below gramm... | E_GRAMMAR_1: Grammar = {
'<start>': ['<A>', '<B>'],
'<A>': ['a', ''],
'<B>': ['b']
} | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
One of the problems with the original Earley implementation is that it does not handle rules that can derive empty strings very well. For example, the given grammar should match `a` | EPSILON = ''
E_GRAMMAR: Grammar = {
'<start>': ['<S>'],
'<S>': ['<A><A><A><A>'],
'<A>': ['a', '<E>'],
'<E>': [EPSILON]
}
syntax_diagram(E_GRAMMAR)
mystring = 'a'
parser = EarleyParser(E_GRAMMAR)
with ExpectError():
trees = parser.parse(mystring) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Aycock et al.\cite{Aycock2002} suggests a simple fix. Their idea is to pre-compute the `nullable` set and use it to advance the `nullable` states. However, before we do that, we need to compute the `nullable` set. The `nullable` set consists of all nonterminals that can derive an empty string. Computing the `nullable` ... | def fixpoint(f):
def helper(arg):
while True:
sarg = str(arg)
arg_ = f(arg)
if str(arg_) == sarg:
return arg
arg = arg_
return helper | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Remember `my_sqrt()` from [the first chapter](Intro_Testing.ipynb)? We can define `my_sqrt()` using fixpoint. | def my_sqrt(x):
@fixpoint
def _my_sqrt(approx):
return (approx + x / approx) / 2
return _my_sqrt(1)
my_sqrt(2) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
NullableSimilarly, we can define `nullable` using `fixpoint`. We essentially provide the definition of a single intermediate step. That is, assuming that `nullables` contain the current `nullable` nonterminals, we iterate over the grammar looking for productions which are `nullable` -- that is, productions where the e... | def rules(grammar):
return [(key, choice)
for key, choices in grammar.items()
for choice in choices] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The `terminals()` method extracts all terminal symbols from a `canonical` grammar representation. | def terminals(grammar):
return set(token
for key, choice in rules(grammar)
for token in choice if token not in grammar)
def nullable_expr(expr, nullables):
return all(token in nullables for token in expr)
def nullable(grammar):
productions = rules(grammar)
@fixpoint
de... | E_GRAMMAR {'', '<E>', '<start>', '<A>', '<S>'}
E_GRAMMAR_1 {'', '<A>', '<start>'}
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
So, once we have the `nullable` set, all that we need to do is, after we have called `predict` on a state corresponding to a nonterminal, check if it is `nullable` and if it is, advance and add the state to the current column. | class EarleyParser(EarleyParser):
def __init__(self, grammar, **kwargs):
super().__init__(grammar, **kwargs)
self.epsilon = nullable(self.cgrammar)
def predict(self, col, sym, state):
for alt in self.cgrammar[sym]:
col.add(State(sym, tuple(alt), 0, col))
if sym in se... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
To ensure that our parser does parse all kinds of grammars, let us try two more test cases. | DIRECTLY_SELF_REFERRING: Grammar = {
'<start>': ['<query>'],
'<query>': ['select <expr> from a'],
"<expr>": ["<expr>", "a"],
}
INDIRECTLY_SELF_REFERRING: Grammar = {
'<start>': ['<query>'],
'<query>': ['select <expr> from a'],
"<expr>": ["<aexpr>", "a"],
"<aexpr>": ["<expr>"],
}
mystring = '... | recognized select a from a
Recursion error maximum recursion depth exceeded
recognized select a from a
Recursion error maximum recursion depth exceeded
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Why do we get recursion error here? The reason is that, our implementation of `extract_trees()` is eager. That is, it attempts to extract _all_ inner parse trees before it can construct the outer parse tree. When there is a self reference, this results in recursion. Here is a simple extractor that avoids this problem. ... | class SimpleExtractor:
def __init__(self, parser, text):
self.parser = parser
cursor, states = parser.parse_prefix(text)
start = next((s for s in states if s.finished()), None)
if cursor < len(text) or not start:
raise SyntaxError("at " + repr(cursor))
self.my_for... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Using it is as folows: | de = SimpleExtractor(EarleyParser(DIRECTLY_SELF_REFERRING), mystring)
for i in range(5):
tree = de.extract_a_tree()
print(tree_to_string(tree)) | select a from a
select a from a
select a from a
select a from a
select a from a
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
On the indirect reference: | ie = SimpleExtractor(EarleyParser(INDIRECTLY_SELF_REFERRING), mystring)
for i in range(5):
tree = ie.extract_a_tree()
print(tree_to_string(tree)) | select a from a
select a from a
select a from a
select a from a
select a from a
| MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Note that the `SimpleExtractor` gives no guarantee of the uniqueness of the returned trees. This can however be fixed by keeping track of the particular nodes that were expanded from `pos_tree` variable, and hence, avoiding exploration of the same paths.For implementing this, we extract the random stream passing into t... | class ChoiceNode:
def __init__(self, parent, total):
self._p, self._chosen = parent, 0
self._total, self.next = total, None
def chosen(self):
assert not self.finished()
return self._chosen
def __str__(self):
return '%d(%s/%s %s)' % (self._i, str(self._chosen),
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Now we come to the enhanced `EnhancedExtractor()`. | class EnhancedExtractor(SimpleExtractor):
def __init__(self, parser, text):
super().__init__(parser, text)
self.choices = ChoiceNode(None, 1) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
First we define `choose_path()` that given an array and a choice node, returns the element in array corresponding to the next choice node if it exists, or produces a new choice nodes, and returns that element. | class EnhancedExtractor(EnhancedExtractor):
def choose_path(self, arr, choices):
arr_len = len(arr)
if choices.next is not None:
if choices.next.finished():
return None, None, None, choices.next
else:
choices.next = ChoiceNode(choices, arr_len)
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We define `extract_a_node()` here. While extracting, we have a choice. Should we allow infinite forests, or should we have a finite number of trees with no direct recursion? A direct recursion is when there exists a parent node with the same nonterminal that parsed the same span. We choose here not to extract such tree... | class EnhancedExtractor(EnhancedExtractor):
def extract_a_node(self, forest_node, seen, choices):
name, paths = forest_node
if not paths:
return (name, []), choices
cur_path, _i, _l, new_choices = self.choose_path(paths, choices)
if cur_path is None:
return N... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
The `extract_a_tree()` is a depth first extractor of a single tree. It tries to extract a tree, and if the extraction returns `None`, it means that a particular choice was exhausted, or we hit on a recursion. In that case, we increment the choice, and explore a new path. | class EnhancedExtractor(EnhancedExtractor):
def extract_a_tree(self):
while not self.choices.finished():
parse_tree, choices = self.extract_a_node(self.my_forest, set(), self.choices)
choices.increment()
if parse_tree is not None:
return self.parser.prune_... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Note that the `EnhancedExtractor` only extracts nodes that are not directly recursive. That is, if it finds a node with a nonterminal that covers the same span as that of a parent node with the same nonterminal, it skips the node. | ee = EnhancedExtractor(EarleyParser(INDIRECTLY_SELF_REFERRING), mystring)
i = 0
while True:
i += 1
t = ee.extract_a_tree()
if t is None: break
print(i, t)
s = tree_to_string(t)
assert s == mystring
istring = '1+2+3+4'
ee = EnhancedExtractor(EarleyParser(A1_GRAMMAR), istring)
i = 0
while True:
... | 1 ('<start>', [('<expr>', [('<expr>', [('<expr>', [('<expr>', [('<integer>', [('<digit>', [('1', [])])])]), ('+', []), ('<expr>', [('<integer>', [('<digit>', [('2', [])])])])]), ('+', []), ('<expr>', [('<integer>', [('<digit>', [('3', [])])])])]), ('+', []), ('<expr>', [('<integer>', [('<digit>', [('4', [])])])])])])
2... | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
More Earley ParsingA number of other optimizations exist for Earley parsers. A fast industrial strength Earley parser implementation is the [Marpa parser](https://jeffreykegler.github.io/Marpa-web-site/). Further, Earley parsing need not be restricted to character data. One may also parse streams (audio and video stre... | mystring = "1 + (2 * 3)"
earley = EarleyParser(EXPR_GRAMMAR)
for tree in earley.parse(mystring):
assert tree_to_string(tree) == mystring
display(display_tree(tree))
mystring = "1 * (2 + 3.35)"
for tree in earley.parse(mystring):
assert tree_to_string(tree) == mystring
display(display_tree(tree)) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
In contrast to the `PEGParser`, above, the `EarleyParser` can handle arbitrary context-free grammars. Excursion: Testing the ParsersWhile we have defined two parser variants, it would be nice to have some confirmation that our parses work well. While it is possible to formally prove that they work, it is much more sat... | def prod_line_grammar(nonterminals, terminals):
g = {
'<start>': ['<symbols>'],
'<symbols>': ['<symbol><symbols>', '<symbol>'],
'<symbol>': ['<nonterminals>', '<terminals>'],
'<nonterminals>': ['<lt><alpha><gt>'],
'<lt>': ['<'],
'<gt>': ['>'],
'<alpha>': nonte... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Now we verify if our arbitrary grammars can be used by the Earley parser. | for i in range(5):
my_grammar = make_grammar()
print(my_grammar)
parser = EarleyParser(my_grammar)
mygf = GrammarFuzzer(my_grammar)
s = mygf.fuzz()
print(s)
for tree in parser.parse(s):
assert tree_to_string(tree) == s
display_tree(tree) | {'<SCS>': ['ts', 'f', 'ng'], '<BQN>': ['wm<SCS>', '<SCS>wi', '<SCS>hw'], '<UZC>': ['gyk<BQN>br', '<SCS>iqp', '<BQN>vb'], '<start>': ['<UZC>']}
fhwvb
{'<CRN>': ['meze', 'de', 'cpcv'], '<AIS>': ['<CRN>hb', 'dc<CRN>', 'pa<CRN>x'], '<MAO>': ['<CRN>su', '<CRN>hj', '<CRN><AIS>g'], '<start>': ['<MAO>']}
dehj
{'<MFY>': ['y', '... | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
With this, we have completed both implementation and testing of *arbitrary* CFG, which can now be used along with `LangFuzzer` to generate better fuzzing inputs. End of Excursion BackgroundNumerous parsing techniques exist that can parse a given string using agiven grammar, and produce corresponding derivation tree o... | from Grammars import US_PHONE_GRAMMAR
us_phone_parser = EarleyParser(US_PHONE_GRAMMAR) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Then, use the `parse()` method to retrieve a list of possible derivation trees: | trees = us_phone_parser.parse("(555)987-6543")
tree = list(trees)[0]
display_tree(tree) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
These derivation trees can then be used for test generation, notably for mutating and recombining existing inputs. | # ignore
from ClassDiagram import display_class_hierarchy
# ignore
display_class_hierarchy([PEGParser, EarleyParser],
public_methods=[
Parser.parse,
Parser.__init__,
Parser.grammar,
Pa... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Lessons Learned* Grammars can be used to generate derivation trees for a given string.* Parsing Expression Grammars are intuitive, and easy to implement, but require care to write.* Earley Parsers can parse arbitrary Context Free Grammars. Next Steps* Use parsed inputs to [recombine existing inputs](LangFuzzer.ipynb)... | class PackratParser(Parser):
def parse_prefix(self, text):
txt, res = self.unify_key(self.start_symbol(), text)
return len(txt), [res]
def parse(self, text):
remain, res = self.parse_prefix(text)
if remain:
raise SyntaxError("at " + res)
return res
def u... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Exercise 2: More PEG SyntaxThe _PEG_ syntax provides a few notational conveniences reminiscent of regular expressions. For example, it supports the following operators (letters `T` and `A` represents tokens that can be either terminal or nonterminal. `ε` is an empty string, and `/` is the ordered choice operator simil... | mystring = 'aaaaaa' | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
To see the problem, we need to enable logging. Here is the logged version of parsing with the `LR_GRAMMAR` | result = EarleyParser(LR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass # consume the generator so that we can see the logs | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= <A> a |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= <A> a |(0,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= <A> a |(0,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= <A> a |(0,4)
<start>:= <A> |(0,4)
a chart[5]
<A>:= <A> a |(0,5)
<start>:= <A> |(0,5)
a cha... | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Compare that to the parsing of `RR_GRAMMAR` as seen below: | result = EarleyParser(RR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= |(1,1)
<A>:= a <A> |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= |(2,2)
<A>:= a <A> |(1,2)
<A>:= a <A> |(0,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= |(3,3)
<A>:= a <A> |(2,3)
<A>:= a <A> |(1,3)
<A>:= a <A> |(0,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:... | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
As can be seen from the parsing log for each letter, the number of states with representation `: a ● (i, j)` increases at each stage, and these are simply a left over from the previous letter. They do not contribute anything more to the parse other than to simply complete these entries. However, they take up space, an... | class LeoParser(EarleyParser):
def complete(self, col, state):
return self.leo_complete(col, state)
def leo_complete(self, col, state):
detred = self.deterministic_reduction(state)
if detred:
col.add(detred.copy())
else:
self.earley_complete(col, state)
... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Can you implement the `deterministic_reduction()` method to obtain the topmost element? **Solution.** Here is a possible solution: First, we update our `Column` class with the ability to add transitive items. Note that, while Leo asks the transitive to be added to the set $ I_k $ there is no actual requirement for the... | class Column(Column):
def __init__(self, index, letter):
self.index, self.letter = index, letter
self.states, self._unique, self.transitives = [], {}, {}
def add_transitive(self, key, state):
assert key not in self.transitives
self.transitives[key] = state
return self.tr... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Remember the picture we drew of the deterministic path?``` : seq_3 ● (s_3, e) | constraints satisfied by : seq_3 ● (s_3, s_2) : seq_2 ● (s_2, e) | constraints satisfied by : seq_2 ● (s_2, s_1) : seq_1 ● (s_1, e)``` We... | class LeoParser(LeoParser):
def uniq_postdot(self, st_A):
col_s1 = st_A.s_col
parent_states = [
s for s in col_s1.states if s.expr and s.at_dot() == st_A.name
]
if len(parent_states) > 1:
return None
matching_st_B = [s for s in parent_states if s.dot =... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We next define the function `get_top()` that is the core of deterministic reduction which gets the topmost state above the current state (`A`). | class LeoParser(LeoParser):
def get_top(self, state_A):
st_B_inc = self.uniq_postdot(state_A)
if not st_B_inc:
return None
t_name = st_B_inc.name
if t_name in st_B_inc.e_col.transitives:
return st_B_inc.e_col.transitives[t_name]
st_B = st_B_i... | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Once we have the machinery in place, `deterministic_reduction()` itself is simply a wrapper to call `get_top()` | class LeoParser(LeoParser):
def deterministic_reduction(self, state):
return self.get_top(state)
lp = LeoParser(RR_GRAMMAR)
columns = lp.chart_parse(mystring, lp.start_symbol())
[(str(s), str(lp.get_top(s))) for s in columns[-1].states] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Now, both LR and RR grammars should work within $O(n)$ bounds. | result = LeoParser(RR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= |(1,1)
<A>:= a <A> |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= |(2,2)
<A>:= a <A> |(1,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= |(3,3)
<A>:= a <A> |(2,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= |(4,4)
<A>:= a <A> |(3,4)
<start>:= <A> |(0,4)
a char... | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We verify the Leo parser with a few more right recursive grammars. | RR_GRAMMAR2 = {
'<start>': ['<A>'],
'<A>': ['ab<A>', ''],
}
mystring2 = 'ababababab'
result = LeoParser(RR_GRAMMAR2, log=True).parse(mystring2)
for _ in result: pass
RR_GRAMMAR3 = {
'<start>': ['c<A>'],
'<A>': ['ab<A>', ''],
}
mystring3 = 'cababababab'
result = LeoParser(RR_GRAMMAR3, log=True).parse(mys... | None chart[0]
a chart[1]
<A>:= a |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= a |(1,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= a |(2,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= a |(3,4)
<start>:= <A> |(0,4)
a chart[5]
<A>:= a |(4,5)
<start>:= <A> |(0,5)
a chart[6]
<A>:= a |(5,6)
<start>:= <A> |(0,6)
a chart[7... | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We verify that our parser works correctly on `LR_GRAMMAR` too. | result = LeoParser(LR_GRAMMAR, log=True).parse(mystring)
for _ in result: pass | None chart[0]
<A>:= |(0,0)
<start>:= <A> |(0,0)
a chart[1]
<A>:= <A> a |(0,1)
<start>:= <A> |(0,1)
a chart[2]
<A>:= <A> a |(0,2)
<start>:= <A> |(0,2)
a chart[3]
<A>:= <A> a |(0,3)
<start>:= <A> |(0,3)
a chart[4]
<A>:= <A> a |(0,4)
<start>:= <A> |(0,4)
a chart[5]
<A>:= <A> a |(0,5)
<start>:= <A> |(0,5)
a cha... | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
__Advanced:__ We have fixed the complexity bounds. However, because we are saving only the topmost item of a right recursion, we need to fix our parser to be aware of our fix while extracting parse trees. Can you fix it?__Hint:__ Leo suggests simply transforming the Leo item sets to normal Earley sets, with the results... | class Column(Column):
def add_transitive(self, key, state):
assert key not in self.transitives
self.transitives[key] = TState(state.name, state.expr, state.dot,
state.s_col, state.e_col)
return self.transitives[key] | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We also need a `back()` method to create the constraints. | class State(State):
def back(self):
return TState(self.name, self.expr, self.dot - 1, self.s_col, self.e_col) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
We update `copy()` to make `TState` items instead. | class TState(State):
def copy(self):
return TState(self.name, self.expr, self.dot, self.s_col, self.e_col) | _____no_output_____ | MIT | docs/notebooks/Parser.ipynb | cn-fairy/fuzzingbook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.