def runTest(self): parser = pypeg2.Parser() r = parser.parse("hello, world", (pypeg2.name(), ",", pypeg2.name())) self.assertEqual( r, ( '', [ pypeg2.attr.Class(name='name', thing=pypeg2.Symbol('hello'), subtype=None), pypeg2.attr.Class(name='name', thing=pypeg2.Symbol('world'), subtype=None) ] ) )
class SelfClosingTag(object): grammar = '<', name(), attr('attributes', Attributes), ignore(whitespace), '/>' def get_name(self): return "'%s'" % self.name def compose(self, parser, indent=0, first=False): text = [] indent = int(indent) indent_str = indent * int(not first) * " " end_indent_str = indent * " " indent_plus_str = (indent + 1) * " " has_contents = bool(self.attributes) paren_sep = '\n' if has_contents else '' contents_sep = ',\n' if has_contents else '' text.append( "{indent}h({paren_sep}{indent_plus}{name}{contents_sep}".format( indent=indent_str, indent_plus=indent_plus_str if has_contents else '', name=self.get_name(), paren_sep=paren_sep, contents_sep=contents_sep, )) text.append( self.attributes.compose(parser, followed_by_children=False, indent=indent + 1)) text.append("{indent})".format( indent=end_indent_str if has_contents else '', )) return ''.join(text)
class ArgumentWithQuotes(List): grammar = name(), ':', re.compile(r'"([^"\\]|\\.|\\\n)*"|\'([^\'\\]|\\.|\\\n)*\'') @property def value(self): # Slicing is for removing quotes # at the begining and end of a string return self[0][1:-1]
class IncludedField(List): grammar = optional(Alias), name() @property def alias(self): if len(self) > 0: return self[0].name return None
class Attribute(object): grammar = name(), '=', attr('value', [String, InlineCode]) def compose(self, parser, indent=0): indent_str = indent * " " return "{indent}'{name}': {value},".format( indent=indent_str, name=self.name, value=self.value.compose(parser))
class Attribute(object): """Matches an attribute formatted as either: key="value" or key={value} to handle strings and inline code in a similar style to JSX. """ grammar = name(), '=', attr('value', [String, InlineCode]) def compose(self, parser, indent=0): indent_str = indent * " " return "{indent}'{name}': {value},".format( indent=indent_str, name=self.name, value=self.value.compose(parser))
class ArgumentWithoutQuotes(List): grammar = name(), ':', re.compile(r'true|false|null|[-+]?[0-9]*\.?[0-9]+') def number(self, val): try: return int(val) except ValueError: return float(val) @property def value(self): raw_val = self[0] FIXED_DATA_TYPES = { 'true': True, 'false': False, 'null': None } if raw_val in FIXED_DATA_TYPES: return FIXED_DATA_TYPES[raw_val] return self.number(raw_val)
class Method(object): grammar = blank, "def ", name(), "(self, ", attr("params", Parameters), ") ->", attr("response", Type), \ ":", endl, " ...", endl
class Union(object): grammar = cls, name(), "(object):", endl, attr("annotations", Annotations), attr( "init", Init), endl
class Enum(object): grammar = cls, name(), "(Enum):", endl, attr("kvs", KeyValues)
class KeyValue(object): grammar = blank, name(), "=", attr("value", Value), endl
class IncludedField(List): grammar = name()
class ArgumentWithDoubleQuotes(BaseArgument): grammar = name(), ':', '"', re.compile(r'[^"]+'), '"'
class ArgumentWithoutQuotes(BaseArgument): grammar = name(), ':', re.compile(r'[^,:"\'\)]+')
class ComposeAttribute(object): grammar = pypeg2.name()
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
class Field(): """A field name in a query.""" grammar = name()
class Argument(List): grammar = name(), ':', re.compile(r'[^,:\)]+') @property def value(self): return self[0]
class ArgumentWithSingleQuotes(BaseArgument): grammar = name(), ':', "'", re.compile(r'[^\']+'), "'"
class Another(object): grammar = pypeg2.name(), "=", pypeg2.attr("value")
class Argument(List): grammar = name(), ':', word @property def value(self): return self[0]
class Parameter(object): grammar = pypeg2.attr("typing", str), pypeg2.name()
class ExcludedField(List): grammar = contiguous('-', name())
class Function(pypeg2.List): grammar = pypeg2.name(), pypeg2.attr( "parms", Parameters), "{", pypeg2.maybe_some(Instruction), "}"
class Const(object): grammar = name(), "=", attr("value", Value), endl
class Something(pypeg2.List): grammar = pypeg2.name(), pypeg2.some(Another), str
class Annotation(object): grammar = blank, name(), ":", attr("type", Type)
class SomethingElse(pypeg2.Namespace): grammar = pypeg2.name(), pypeg2.some(Another)
class Exc(object): grammar = cls, name(), "(TException):", endl, attr("annotations", Annotations), attr( "init", Init), endl
class Key(str): grammar = pypeg2.name(), "=", pypeg2.restline
class Service(object): grammar = cls, name(), "(object):", endl, attr("methods", Methods), endl
# -*- coding: utf-8 -*- # May you recognize your weaknesses and share your strengths. # May you share freely, never taking more than you give. # May you find love and love everyone you find. import re import pypeg2 class Dialog(str): grammar = '"', pypeg2.maybe_some(pypeg2.word), '"', pypeg2.endl class Label(pypeg2.List): pass instruction = [Dialog, Label] # We have to delay this definition because it's circular. Label.grammar = 'label', pypeg2.name(), ':', pypeg2.endl, pypeg2.some(instruction) def parse(inFile): text = open(inFile).read() return pypeg2.parse(text, instruction)