class GenTestCase(unittest.TestCase): def compile(self, tokenize, grammar, **kwargs): """Compile a grammar. Use this when you expect compilation to
succeed."""
self.tokenize = tokenize
self.parser_class = gen.compile(grammar, **kwargs)
# Issue #3: This also has an abiguity; empty string matches either # `goal ::= [empty]` or `goal ::= phrase, phrase ::= [empty]`.
check({ 'goal': [[Optional('phrase')]], 'phrase': [[Optional('X')]],
})
# Input "X" is ambiguous, could be ('goal', ('a', None), ('a', 'X')) # or the other 'a' could be the one that's missing.
check({ 'goal': [['a', 'a']], 'a': [[Optional('X')]],
})
def testLeftFactorMulti(self): """Test left-factoring with common prefix of length >1."""
tokenize = lexer.LexicalGrammar("A B C D E")
grammar = Grammar({ 'goal': [
['A', 'B', 'C', 'D'],
['A', 'B', 'C', 'E'],
],
})
self.compile(tokenize, grammar)
self.assertParse( "A B C D",
('goal_0', 'A', 'B', 'C', 'D'))
self.assertParse( "A B C E",
('goal_1', 'A', 'B', 'C', 'E'))
def testLeftFactorMultiLevel(self): """Test left-factoring again on a nonterminal introduced by
left-factoring."""
tokenize = lexer.LexicalGrammar("FOR IN TO BY ( ) = ;",
VAR=r'[A-Za-z]+')
# The first left-factoring pass on `stmt` will left-factor `FOR ( VAR`. # A second pass is needed to left-factor `= expr TO expr`.
grammar = Grammar({ 'stmt': [
['expr', ';'],
['FOR', '(', 'VAR', 'IN', 'expr', ')', 'stmt'],
['FOR', '(', 'VAR', '=', 'expr', 'TO', 'expr', ')', 'stmt'],
['FOR', '(', 'VAR', '=', 'expr', 'TO', 'expr', 'BY', 'expr', ')', 'stmt'],
['IF', '(', 'expr', ')', 'stmt'],
], 'expr': [
['VAR'],
],
})
self.compile(tokenize, grammar)
self.assertParse( "FOR (x IN y) z;",
('stmt_1', 'FOR', '(', 'x', 'IN', 'y', ')',
('stmt_0', 'z', ';')))
self.assertParse( "FOR (x = y TO z) x;",
('stmt_2', 'FOR', '(', 'x', '=', 'y', 'TO', 'z', ')',
('stmt_0', 'x', ';')))
self.assertParse( "FOR (x = y TO z BY w) x;",
('stmt_3', 'FOR', '(', 'x', '=', 'y', 'TO', 'z', 'BY', 'w', ')',
('stmt_0', 'x', ';')))
def testFirstFirstConflict(self): """This grammar is unambiguous, but is not LL(1) due to a first/first conflict.
def testLeftHandSideExpression(self): """Example of a grammar that's in SLR(1) but hard to smoosh into an LL(1) form.
This is taken from the ECMAScript grammar.
...Of course, it's not really possible to enforce the desired syntactic
restrictions in LR(k) either; the ES grammar matches `(x + y) = z` and
an additional attribute grammar (IsValidSimpleAssignmentTarget) is
necessary to rule it out. """
self.compile(
lexer.LexicalGrammar("= +", VAR=r'[a-z]+\b'),
Grammar({ 'AssignmentExpression': [
['AdditiveExpression'],
['LeftHandSideExpression', '=', 'AssignmentExpression'],
], 'AdditiveExpression': [
['LeftHandSideExpression'],
['AdditiveExpression', '+', 'LeftHandSideExpression'],
], 'LeftHandSideExpression': [
['VAR'],
]
})
)
self.assertParse("z = x + y")
self.assertNoParse( "x + y = z",
message="expected one of ['+', 'end of input'], got '='")
N = 3000
s = "x"
t = ('expr_0', 'x') for i in range(N):
s = "(" + s + ")"
t = ('expr_2', '(', t, ')')
result = self.parse(s)
# Python can't check that result == t; it causes a RecursionError. # Testing that repr(result) == repr(t), same deal. So: for i in range(N):
self.assertIsInstance(result, tuple)
self.assertEqual(len(result), 4)
self.assertEqual(result[0], 'expr_2')
self.assertEqual(result[1], '(')
self.assertEqual(result[3], ')')
result = result[2]
# In simple cases like this, the lookahead restriction can even # disambiguate a grammar that would otherwise be ambiguous.
rules['goal'].append(prod(['a'], 'goal_a'))
self.compile(tokenize, Grammar(rules))
self.assertParse('a', ('goal_a', 'a'))
# Test that without the lookahead restriction, we reject this grammar # (it's ambiguous): del grammar['stmt'][0][0]
self.assertRaisesRegex(ValueError, 'banana', lambda: gen.compile(grammar))
def testTrailingLookahead(self): """Lookahead at the end of a production is banned."""
tokenize = lexer.LexicalGrammar('IF ( X ) ELSE OTHER ;')
grammar = gen.Grammar({ 'goal': [['stmt']], 'stmt': [
['OTHER', ';'],
['IF', '(', 'X', ')', 'stmt',
LookaheadRule(frozenset({'ELSE'}), False)],
['IF', '(', 'X', ')', 'stmt', 'ELSE', 'stmt'],
],
})
self.compile(lexer.LexicalGrammar("function x ( ) { } ++ ;"), grammar)
self.assertParse("function x() {}")
self.assertParse("++function x() {};")
self.assertNoParse("++function x() {}", message="unexpected end") # TODO: The parser generator fails to handle this case because it does # not forward the restriction from producting a Function to the # Primitive rule. Therefore, `Function [lookahead: ;]` is incorrectly # reduced to a `Primitive [lookahead: ;]` # self.assertNoParse("function x() {}++;", message="got ';'")
self.assertParse("function x() {} ++x;")
# XXX to test: combination of lookaheads, ++, +-, -+, -- # XXX todo: find an example where lookahead canonicalization matters
# Note: This lexical grammar is not suitable for use with incremental # parsing.
emu_grammar_lexer = lexer.LexicalGrammar( # the operators and keywords: "[ ] { } , ~ + ? "but empty here lookahead no not of one or through",
NL="\n", # any number of colons together
EQ=r':+', # terminals of the ES grammar, quoted with backticks
T=r'`[^` \n]+`|```', # also terminals, denoting control characters
CHR=r'<[A-Z]+>|U\+[0-9A-f]{4}', # nonterminals that will be followed by boolean parameters
NTCALL=r'(?:uri|[A-Z])\w*(?=\[)', # nonterminals (also, boolean parameters)
NT=r'(?:uri|[A-Z])\w*', # nonterminals wrapped in vertical bars for no apparent reason
NTALT=r'\|[A-Z]\w+\|', # the spec also gives a few productions names
PRODID=r'#[A-Za-z]\w*', # prose to the end of the line
PROSE=r'>.*', # prose wrapped in square brackets
WPROSE=r'\[>[^]]*\]',
)
self.compile(tokenize, grammar)
self.assertParse("{};")
self.assertParse("async x => {};")
self.assertParse("async x => async y => {};")
def testMultiGoal(self):
tokenize = lexer.LexicalGrammar("WHILE DEF FN { } ( ) -> ;", ID=r'\w+')
grammar = Grammar({ "stmt": [
["expr", ";"],
["{", "stmts", "}"],
["WHILE", "(", "expr", ")", "stmt"],
["DEF", "ID", "(", "ID", ")", "{", Optional("stmts"), "}"],
], "stmts": [
["stmt"],
["stmts", "stmt"],
], "expr": [
["FN", "ID", "->", "expr"],
["call_expr"],
], "call_expr": [
["ID"],
["call_expr", "(", "expr", ")"],
["(", "expr", ")"],
],
}, goal_nts=["stmts", "expr"])
self.compile(tokenize, grammar)
self.assertParse("WHILE ( x ) { decx ( x ) ; }", goal="stmts")
self.assertNoParse( "WHILE ( x ) { decx ( x ) ; }", goal="expr",
message="expected one of ['(', 'FN', 'ID'], got 'WHILE'")
self.assertParse("f(x);", goal="stmts")
self.assertNoParse("f(x);", goal="expr",
message="expected 'end of input', got ';'")
self.assertParse("(FN x -> f ( x ))(x)", goal="expr")
self.assertNoParse("(FN x -> f ( x ))(x)", goal="stmts",
message="unexpected end of input")
def testStaggeredItems(self): """Items in a state can have different amounts of leading context.""" # In this example grammar, after "A" "B", we're in a state that # contains these two items (ignoring lookahead): # goal ::= "A" "B" · y # x ::= "B" · stars "X" # # Likewise, after `"A" "B" stars`, we have: # x ::= "B" stars · "X" # y ::= stars · "Y" # stars ::= stars · "*"
tokenize = lexer.LexicalGrammar("A B * X Y")
grammar = Grammar({ "goal": [
["A", "x"],
["A", "B", "y"],
], "x": [
["B", "stars", "X"],
], "y": [
["stars", "Y"],
], "stars": [
["*"],
["stars", "*"],
],
})
self.compile(tokenize, grammar)
self.assertParse("A B * * * X")
self.assertParse("A B * * * Y")
def testConvenienceMethodTypeInference(self): """A method can be called only in an intermediate reduce expression."""
# The reduce expression `f(g($0))`.
reducer = CallMethod("f", [CallMethod("g", [0])])
# The grammar `goal ::= NAME => f(g($1))`.
grammar = Grammar(
{ 'goal': [Production(['NAME'], reducer)],
},
variable_terminals=['NAME'])
# Since the return value of f() is used as the value of a `goal`, # we infer that f() returns a goal.
self.assertEqual(
grammar.methods['f'].return_type,
jsparagus.types.Type('goal'))
# Since the return value of g() isn't used except as an argument, we # just give it the type `g`.
self.assertEqual(
grammar.methods['g'].return_type,
jsparagus.types.Type('g'))
# Since g() is passed to f(), we infer this:
self.assertEqual(
grammar.methods['f'].argument_types,
[jsparagus.types.Type('g')])
def compile_as_js(
self,
grammar_source: str,
goals: typing.Optional[typing.Iterable[str]] = None,
verbose: bool = False,
) -> None: """Like self.compile(), but generate a parser from ESGrammar, with ASI support, using the JS lexer. """ from js_parser.lexer import JSLexer from js_parser import load_es_grammar from js_parser import generate_js_parser_tables
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.