def number(self, text): """number = ["-"] . ("0" | digit - "0" . {digit}) . ["." . digit +] ;""" self._attempting(text) return concatenation([ option( "-" ), alternation([ "0", concatenation([ exclusion( self.digit, "0" ), zero_or_more( self.digit, ignore_whitespace=False ), ], ignore_whitespace=False), ]), option( concatenation([ ".", one_or_more( self.digit, ignore_whitespace=False ), ], ignore_whitespace=False) ), ], ignore_whitespace=False)(text).compressed(TokenType.number)
def return_statement(self, text): """return_statement = ["return"] , expression , [";"] ;""" self._attempting(text) return concatenation([ option( "return" ), self.expression, option( ";" ), ], ignore_whitespace=True)(text).retyped(TokenType.return_statement)
def test_optional_repetition(self): # Makes sure nested repetitions will terminate. c0 = P.zero_or_more(P.option(P.alternation(["a", "b"]))) t0 = "ababaabbaaab" n0 = c0(t0) self.assertEqual(n0.consumed, len(t0))
def expression(self, text): """expression = number , op_mult , expression | expression_terminal , op_mult , number , [operator , expression] | expression_terminal , op_add , [operator , expression] | expression_terminal , [operator , expression] ;""" self._attempting(text) return alternation([ concatenation([ self.number, self.op_mult, self.expression, ], ignore_whitespace=True), concatenation([ self.expression_terminal, self.op_mult, self.number, option( concatenation([ self.operator, self.expression, ], ignore_whitespace=True) ), ], ignore_whitespace=True), concatenation([ self.expression_terminal, self.op_add, option( concatenation([ self.operator, self.expression, ], ignore_whitespace=True) ), ], ignore_whitespace=True), concatenation([ self.expression_terminal, option( concatenation([ self.operator, self.expression, ], ignore_whitespace=True) ), ], ignore_whitespace=True), ])(text).retyped(TokenType.expression)
def test_option(self): c0 = P.option("a") n0 = c0("a") self.assertEqual(n0.node_type, P.ParseNodeType.repetition) self.assertEqual(len(n0.children), 1) self.assertEqual(n0.children[0].value, "a") self.assertFalse(n0.is_empty) n1 = c0("b") self.assertEqual(n1.node_type, P.ParseNodeType.repetition) self.assertTrue(n1.is_empty)
def function_call(self, text): """function_call = function_name . "(" , [function_args] , ")" ;""" self._attempting(text) return concatenation([ self.function_name, concatenation([ "(", option( self.function_args ), ")", ], ignore_whitespace=True), ], ignore_whitespace=False)(text).retyped(TokenType.function_call)
def switch(self, text): """switch = switch_subject , switch_case + , [switch_default] ; s""" self._attempting(text) return concatenation([ self.switch_subject, one_or_more( self.switch_case, ignore_whitespace=True ), option( self.switch_default ), ], ignore_whitespace=True)(text).retyped(TokenType.switch)