コード例 #1
0
ファイル: parser.py プロジェクト: Bamba4/disquaire
class Arguments(List):
    grammar = optional(
        csl([
            ArgumentWithoutQuotes, ArgumentWithSingleQuotes,
            ArgumentWithDoubleQuotes
        ],
            separator=','))
コード例 #2
0
class Arguments(List):
    grammar = optional(csl(
        [
            ArgumentWithoutQuotes,
            ArgumentWithQuotes,
        ],
        separator=[',', '']
    ))
コード例 #3
0
ファイル: grammar_key_desc.py プロジェクト: svenlr/xkbparse
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
コード例 #4
0
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
コード例 #5
0
ファイル: peg.py プロジェクト: wujm2007/thrift2pyi
class Modules(List):
    grammar = optional(csl(re.compile(r"[\w_*]+")))
コード例 #6
0
def action(name_aliases: list, arguments: list):
    return name_aliases, "(", peg.csl(arguments, separator=","), ")"
コード例 #7
0
class Parameters(List):
    grammar = optional(csl(Parameter))
コード例 #8
0
class Arguments(List):
    grammar = optional(csl([Argument], separator=','))
コード例 #9
0
class Block(List):
    """A curly brace delimited block."""
    grammar = '{', csl([Call, Field], separator=','), '}'
コード例 #10
0
class Arguments(List):
    """Arguments to a call."""
    grammar = csl(number, separator=',')
コード例 #11
0
class ComposeTuple(pypeg2.List):
    grammar = pypeg2.csl(pypeg2.word)
コード例 #12
0
ファイル: xmlast.py プロジェクト: EBlatter/MusicMaker
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
コード例 #13
0
    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))),
コード例 #14
0
            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:]
コード例 #15
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
コード例 #16
0
 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")))
コード例 #17
0
class Parms(pypeg2.Namespace):
    grammar = (pypeg2.csl(Parm), pypeg2.flag("fullstop", "."),
            pypeg2.flag("semicolon", ";"))
コード例 #18
0
ファイル: parser.py プロジェクト: VuThiHoa0904/github-cmsw
    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), '}'

コード例 #19
0
class Parameters(pypeg2.Namespace):
    grammar = pypeg2.optional(pypeg2.csl(Parameter))
コード例 #20
0
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="+")
コード例 #21
0
class CallList(List):
    grammar = csl(Field, separator='.')
コード例 #22
0
class Parameters(Namespace):
    grammar = optional(csl(Parameter))
コード例 #23
0
class Events(Namespace):
    grammar = optional(csl(Event))
コード例 #24
0
    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)
コード例 #25
0
class BlockBody(List):
    grammar = optional(
        csl([ParentField, IncludedField, ExcludedField, AllFields],
            separator=','))
コード例 #26
0
class List(MExpression):
    head = MSymbol("List")

    grammar = (
        Literal("{"), optional(attr("body", csl(MExpression))), Literal("}")
    )
コード例 #27
0
class Modules(List):
    grammar = optional(csl(Module))
コード例 #28
0
class Parameters(peg.Namespace):
    grammar = peg.optional(peg.csl(Parameter))
コード例 #29
0
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(
コード例 #30
0
class Block(List):
    grammar = '{', optional(csl([Call, Field], separator=',')), '}'