Exemplo n.º 1
0
 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)
             ]
         )
     )
Exemplo n.º 2
0
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)
Exemplo n.º 3
0
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]
Exemplo n.º 4
0
class IncludedField(List):
    grammar = optional(Alias), name()

    @property
    def alias(self):
        if len(self) > 0:
            return self[0].name
        return None
Exemplo n.º 5
0
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))
Exemplo n.º 6
0
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))
Exemplo n.º 7
0
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)
Exemplo n.º 8
0
class Method(object):
    grammar = blank, "def ", name(), "(self, ", attr("params", Parameters), ") ->", attr("response", Type), \
              ":", endl, "  ...", endl
Exemplo n.º 9
0
class Union(object):
    grammar = cls, name(), "(object):", endl, attr("annotations",
                                                   Annotations), attr(
                                                       "init", Init), endl
Exemplo n.º 10
0
class Enum(object):
    grammar = cls, name(), "(Enum):", endl, attr("kvs", KeyValues)
Exemplo n.º 11
0
class KeyValue(object):
    grammar = blank, name(), "=", attr("value", Value), endl
Exemplo n.º 12
0
class IncludedField(List):
    grammar = name()
Exemplo n.º 13
0
class ArgumentWithDoubleQuotes(BaseArgument):
    grammar = name(), ':', '"', re.compile(r'[^"]+'), '"'
Exemplo n.º 14
0
class ArgumentWithoutQuotes(BaseArgument):
    grammar = name(), ':', re.compile(r'[^,:"\'\)]+')
Exemplo n.º 15
0
class ComposeAttribute(object):
    grammar = pypeg2.name()
Exemplo n.º 16
0
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
Exemplo n.º 17
0
class Field():
    """A field name in a query."""
    grammar = name()
Exemplo n.º 18
0
class Argument(List):
    grammar = name(), ':', re.compile(r'[^,:\)]+')

    @property
    def value(self):
        return self[0]
Exemplo n.º 19
0
class ArgumentWithSingleQuotes(BaseArgument):
    grammar = name(), ':', "'", re.compile(r'[^\']+'), "'"
Exemplo n.º 20
0
class Another(object):
    grammar = pypeg2.name(), "=", pypeg2.attr("value")
Exemplo n.º 21
0
class Argument(List):
    grammar = name(), ':', word

    @property
    def value(self):
        return self[0]
Exemplo n.º 22
0
class Parameter(object):
    grammar = pypeg2.attr("typing", str), pypeg2.name()
Exemplo n.º 23
0
class ExcludedField(List):
    grammar = contiguous('-', name())
Exemplo n.º 24
0
class Function(pypeg2.List):
    grammar = pypeg2.name(), pypeg2.attr(
        "parms", Parameters), "{", pypeg2.maybe_some(Instruction), "}"
Exemplo n.º 25
0
class Const(object):
    grammar = name(), "=", attr("value", Value), endl
Exemplo n.º 26
0
class Something(pypeg2.List):
    grammar = pypeg2.name(), pypeg2.some(Another), str
Exemplo n.º 27
0
class Annotation(object):
    grammar = blank, name(), ":", attr("type", Type)
Exemplo n.º 28
0
class SomethingElse(pypeg2.Namespace):
    grammar = pypeg2.name(), pypeg2.some(Another)
Exemplo n.º 29
0
class Exc(object):
    grammar = cls, name(), "(TException):", endl, attr("annotations",
                                                       Annotations), attr(
                                                           "init", Init), endl
Exemplo n.º 30
0
class Key(str):
    grammar = pypeg2.name(), "=", pypeg2.restline
Exemplo n.º 31
0
class Service(object):
    grammar = cls, name(), "(object):", endl, attr("methods", Methods), endl
Exemplo n.º 32
0
# -*- 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)