class Arguments(List): grammar = optional( csl([ ArgumentWithoutQuotes, ArgumentWithSingleQuotes, ArgumentWithDoubleQuotes ], separator=','))
class Arguments(List): grammar = optional(csl( [ ArgumentWithoutQuotes, ArgumentWithQuotes, ], separator=[',', ''] ))
class KeySymList(peg.List): """ A list of key symbols in brackets """ grammar = "[", peg.optional(peg.csl(KeySym)), "]" @staticmethod def from_strings(strings: list): levels = KeySymList() for s in strings: k = KeySym() k.name = s levels.append(k) return levels
class Enumerators(_List, Node): grammar = pypeg2.csl(Enumerator), pypeg2.optional(',') def __init__(self, items): super().__init__([i.value for i in items]) def __str__(self): s = '<enumerators>' for e in self: s += str(e) s += '</enumerators>' return s
class Modules(List): grammar = optional(csl(re.compile(r"[\w_*]+")))
def action(name_aliases: list, arguments: list): return name_aliases, "(", peg.csl(arguments, separator=","), ")"
class Parameters(List): grammar = optional(csl(Parameter))
class Arguments(List): grammar = optional(csl([Argument], separator=','))
class Block(List): """A curly brace delimited block.""" grammar = '{', csl([Call, Field], separator=','), '}'
class Arguments(List): """Arguments to a call.""" grammar = csl(number, separator=',')
class ComposeTuple(pypeg2.List): grammar = pypeg2.csl(pypeg2.word)
def create_tree(thing, parent=None, object_names=False): """Create an XML etree from a thing. Arguments: thing thing to interpret parent etree.Element to put subtree into default: create a new Element tree object_names experimental feature: if True tag names are object names instead of types Returns: etree.Element instance created """ try: grammar = type(thing).grammar except AttributeError: if isinstance(thing, list): grammar = pypeg2.csl(pypeg2.name()) else: grammar = pypeg2.word name = type(thing).__name__ if object_names: try: name = str(thing.name) name = name.replace(" ", "_") except AttributeError: pass if parent is None: me = etree.Element(name) else: me = etree.SubElement(parent, name) for e in pypeg2.attributes(grammar): if object_names and e.name == "name": if name != type(thing).__name__: continue key, value = e.name, getattr(thing, e.name, None) if value is not None: if pypeg2._issubclass(e.thing, (str, int, pypeg2.Literal)) \ or type(e.thing) == pypeg2._RegEx: me.set(key, str(value)) else: create_tree(value, me, object_names) if isinstance(thing, list): things = thing elif isinstance(thing, pypeg2.Namespace): things = thing.values() else: things = [] last = None for t in things: if type(t) == str: if last is not None: last.tail = str(t) else: me.text = str(t) else: last = create_tree(t, me, object_names) if isinstance(thing, str): me.text = str(thing) return me
single_quote_string_literal, double_quote_string_literal, float_literal, int_literal, bool_literal, token ]), ':', attr('value', ternary_expression_or_less)) AssociativeListExpression.grammar = ('{', endl, attr( 'content', pypeg2.indent( optional( AttributeDeclaration, maybe_some( ',', endl, AttributeDeclaration)), endl)), '}') OrderedListExpression.grammar = ('[', attr('content'), pypeg2.indent( pypeg2.csl(ternary_expression_or_less)), ']') BracketedExpression.grammar = '[', attr('content', ternary_expression_or_less), ']' InvocationExpression.grammar = '(', attr( 'content', optional(pypeg2.csl((blank, ternary_expression_or_less)))), ')' ParensExpression.grammar = '(', attr('content', ternary_expression_or_less), ')' AssignmentExpression.grammar = ( attr('operand1', [PostfixExpression, token]), blank, attr('operator', re.compile('[*/+-]?=')), blank, attr('operand2', [AssignmentExpression, *ternary_expression_or_less])) VariableDeclaration.grammar = (attr( 'qualifiers', maybe_some((re.compile('const|var|let'), blank))),
print() print(' private:') print(' const std::shared_ptr<arpc::Channel> channel_;') print('};') print() print( 'static std::unique_ptr<Stub> NewStub(const std::shared_ptr<arpc::Channel>& channel) {' ) print(' return std::make_unique<Stub>(channel);') print('}') print() print('};') ProtoFile = ('syntax', '=', ['"proto3"', '\'proto3\''], ';', 'package', pypeg2.csl(pypeg2.word, separator='.'), ';', pypeg2.ignore((pypeg2.maybe_some(['import', 'option'], pypeg2.restline), )), pypeg2.maybe_some([ EnumDeclaration, MessageDeclaration, ServiceDeclaration, ])) input_str = sys.stdin.read() input_sha256 = hashlib.sha256(input_str.encode('UTF-8')).hexdigest() declarations = pypeg2.parse(input_str, ProtoFile, comment=pypeg2.comment_cpp) package = [] while isinstance(declarations[0], str): package.append(declarations[0]) declarations = declarations[1:]
def runTest(self): L1 = pypeg2.csl("thing") L2 = pypeg2.csl("hello", "world") self.assertEqual(L1, ("thing", -1, (",", pypeg2.blank, "thing"))) self.assertEqual(L2, ("hello", "world", -1, (",", pypeg2.blank, "hello", "world")))
class Parms(pypeg2.Namespace): grammar = (pypeg2.csl(Parm), pypeg2.flag("fullstop", "."), pypeg2.flag("semicolon", ";"))
According to ParentField grammar: self[0] returns IncludedField instance, self[1] returns Block instance """ @property def name(self): return self[0].name @property def block(self): return self[1] # A block which contains included fields(No excluded fields here) include_block = csl( [ParentField, IncludedField, optional(AllFields)], separator=',' ) # A block which contains excluded fields(No included fields here) exclude_block = csl( [ParentField, ExcludedField, optional(AllFields)], separator=',' ) class Block(List): # A block with either `include_block` or `exclude_block` # features but not both grammar = '{', optional(include_block, exclude_block), '}'
class Parameters(pypeg2.Namespace): grammar = pypeg2.optional(pypeg2.csl(Parameter))
class ModifiersArgument(peg.List): """ modifiers= or mods= argument in action command. Takes a list of '+'-separated modifiers """ grammar = ["modifiers", "mods"], "=", peg.csl(peg.word, separator="+")
class CallList(List): grammar = csl(Field, separator='.')
class Parameters(Namespace): grammar = optional(csl(Parameter))
class Events(Namespace): grammar = optional(csl(Event))
body = None class List(MExpression): head = MSymbol("List") grammar = ( Literal("{"), optional(attr("body", csl(MExpression))), Literal("}") ) # Since MExpression is recursive, we need to define the class, # then the grammar. Moreover, since it depends on List and other # such things, we need to put it last. MExpression.grammar = [ ( attr("head", MSymbol), Literal("["), optional(attr("body", csl(MExpression))), Literal("]") ), attr("head", MSymbol), List, atom ] ## TESTING ########################################################### if __name__ == "__main__": print parse("ab`c", MExpression) print parse('12', MExpression) print parse('"a"', MExpression) print parse("List", MExpression) print parse("List[]", MExpression)
class BlockBody(List): grammar = optional( csl([ParentField, IncludedField, ExcludedField, AllFields], separator=','))
class List(MExpression): head = MSymbol("List") grammar = ( Literal("{"), optional(attr("body", csl(MExpression))), Literal("}") )
class Modules(List): grammar = optional(csl(Module))
class Parameters(peg.Namespace): grammar = peg.optional(peg.csl(Parameter))
ternary_expression_or_less = [TernaryExpression, *binary_expression_or_less] TernaryExpression.grammar = (attr('operand1', binary_expression_or_less), '?', blank, attr('operand2', ternary_expression_or_less), blank, ':', blank, attr('operand3', ternary_expression_or_less)) BracketedExpression.grammar = '[', attr('content', ternary_expression_or_less), ']' ParensExpression.grammar = '(', attr('content', ternary_expression_or_less), ')' InvocationExpression.grammar = (attr('reference', token), '(', attr('arguments', pypeg2.csl(ternary_expression_or_less)), ')') AttributeExpression.grammar = (attr( 'reference', [InvocationExpression, token, ParensExpression ]), attr('attributes', pypeg2.some([BracketedExpression, ('.', token)]))) AssignmentExpression.grammar = ( attr('operand1', [AttributeExpression, token]), blank, attr('operator', re.compile('[*/+-]?=')), blank, attr('operand2', [AssignmentExpression, *ternary_expression_or_less])) VariableDeclaration.grammar = ( attr( 'qualifiers', maybe_some(
class Block(List): grammar = '{', optional(csl([Call, Field], separator=',')), '}'