How to use the pyparsing.Forward function in pyparsing

To help you get started, we’ve selected a few pyparsing examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eerimoq / asn1tools / asn1tools / parser.py View on Github external
real_number = Regex(r'[+-]?\d+\.?\d*([eE][+-]?\d+)?')
    bstring = Regex(r"'[01\s]*'B")
    hstring = Regex(r"'[0-9A-F\s]*'H")
    cstring = QuotedString('"')
    number = (Word(nums).setName('number') + ~dot)
    ampersand = Literal('&')
    less_than = Literal('<')

    reserved_words = Regex(r'(END|SEQUENCE|ENUMERATED|WITH)(\s|$)')

    # Forward declarations.
    value = Forward()
    type_ = Forward()
    object_ = Forward()
    object_set = Forward()
    primitive_field_name = Forward()
    constraint = Forward()
    element_set_spec = Forward()
    token_or_group_spec = Forward()
    value_reference = Forward().setName('valuereference')
    type_reference = Forward().setName('typereference')
    value_set = Forward().setName('"valueSet" not implemented')
    named_type = Forward()
    root_element_set_spec = Forward()
    defined_object_set = Forward()
    syntax_list = Forward()
    object_from_object = Forward()
    object_set_from_objects = Forward()
    defined_value = Forward().setName('DefinedValue')
    component_type_lists = Forward()
    extension_and_exception = Forward()
    optional_extension_marker = Forward()
github bwesterb / pol / src / editfile.py View on Github external
note = quotedString | originalTextFor(OneOrMore(word))
    containerKeyword = Suppress('CONTAINER')
    entry = (~containerKeyword + Group(key - secret - Optional(note))
                - Suppress(lineEnd))
    comment = Suppress(lineEnd | '#' + SkipTo(lineEnd))
    line = comment | entry
    containerLine = containerKeyword + containerId + comment
    # Instead of the following recursive grammar, we could have simply used
    #
    #     containerBlock = ZeroOrMore(comment) + Group(containerLine
    #                                                + Group(OneOrMore(line)))
    #     multipleContainers = OneOrMore(containerBlock)
    #
    # but then any parsing error in line will result in a "expected stringEnd"
    # or "expected CONTAINER".
    _multipleContainers_head = Forward()
    _multipleContainers_body = Forward()
    _multipleContainers_head << (stringEnd | comment + _multipleContainers_head
                    | containerLine + _multipleContainers_body)
    _multipleContainers_body << (stringEnd
                    | (containerLine | line) + _multipleContainers_body)
    _multipleContainers_entry = And([entry])
    multipleContainers = And([_multipleContainers_head]) # TODO ibidem below
    containerLine.setParseAction(lambda s,l,t: [[None, t[0]]])
    def multipleContainersParseAction(s, loc, tokens):
        curEntries = []
        curId = None
        ret = []
        for t in tuple(tokens) + ((None, None),):
            if t[0] is not None:
                assert curId is not None
                curEntries.append(t)
github eerimoq / asn1tools / asn1tools / parser.py View on Github external
defined_value = Forward().setName('DefinedValue')
    component_type_lists = Forward()
    extension_and_exception = Forward()
    optional_extension_marker = Forward()
    additional_element_set_spec = Forward()
    reference = Forward()
    defined_object_class = Forward()
    defined_type = Forward()
    module_reference = Forward()
    external_type_reference = Forward()
    external_value_reference = Forward()
    simple_defined_type = Forward()
    defined_object = Forward()
    referenced_value = Forward()
    builtin_value = Forward()
    named_value = Forward()
    sequence_value = Forward()
    signed_number = Forward()
    name_and_number_form = Forward()
    number_form = Forward().setName('numberForm')
    definitive_number_form = Forward().setName('definitiveNumberForm')
    version_number = Forward()
    union_mark = Forward()
    named_number = Forward()
    size_constraint = Forward()

    value_field_reference = Combine(ampersand + value_reference)
    type_field_reference = Combine(ampersand + type_reference)

    # ToDo: Remove size_paren as they are a workaround for
    #       SEQUENCE/SET OF.
    size_paren = (Suppress(Optional(left_parenthesis))
github eerimoq / asn1tools / asn1tools / parser.py View on Github external
module_reference = Forward()
    external_type_reference = Forward()
    external_value_reference = Forward()
    simple_defined_type = Forward()
    defined_object = Forward()
    referenced_value = Forward()
    builtin_value = Forward()
    named_value = Forward()
    sequence_value = Forward()
    signed_number = Forward()
    name_and_number_form = Forward()
    number_form = Forward().setName('numberForm')
    definitive_number_form = Forward().setName('definitiveNumberForm')
    version_number = Forward()
    union_mark = Forward()
    named_number = Forward()
    size_constraint = Forward()

    value_field_reference = Combine(ampersand + value_reference)
    type_field_reference = Combine(ampersand + type_reference)

    # ToDo: Remove size_paren as they are a workaround for
    #       SEQUENCE/SET OF.
    size_paren = (Suppress(Optional(left_parenthesis))
                  + size_constraint
                  + Suppress(Optional(right_parenthesis)))

    class_number = (number | defined_value).setName('ClassNumber')
    tag = Group(Optional(Suppress(left_bracket)
                         - Group(Optional(UNIVERSAL
                                          | APPLICATION
                                          | PRIVATE)
github openstack / monasca-analytics / monasca_analytics / banana / grammar / config.py View on Github external
comp_ctor.setParseAction(action_parse_comp_ctor)\
        .setName(const.COMP_CTOR)\
        .setDebug(debug_grammar)

    # Assignments
    assignment = dot_path + equals - (comp_ctor | expr | json_obj)
    assignment.setParseAction(action_assignment)

    # Connections
    connection = p.Forward()
    array_of_connection = p.Group(
        lbra + p.Optional(p.delimitedList(connection)) + rbra
    )
    array_of_connection.setParseAction(action_merge_connections)
    last_expr = ident | array_of_connection
    this_expr = p.Forward()
    match_expr = p.FollowedBy(last_expr + arrow - last_expr) + \
        (last_expr + p.OneOrMore(arrow - last_expr))
    this_expr <<= match_expr | last_expr
    connection <<= this_expr

    match_expr.setDebug(debug_grammar)\
        .setName(const.CONNECTION) \
        .setParseAction(action_create_connections)

    # Definitions
    definition = ing - less - string_lit - greater - ident - lbrace - rbrace
    definition.setDebug(debug_grammar)\
        .setName(const.DEFINITION)\
        .setParseAction(action_unimplemented)

    # Import directive
github timvieira / arsenal / pyparsing / examples / searchparser.py View on Github external
)
        
        operatorQuotes = Group(
            Suppress('"') + operatorQuotesContent + Suppress('"')
        ).setResultsName("quotes") | operatorWord
        
        operatorParenthesis = Group(
            (Suppress("(") + operatorOr + Suppress(")"))
        ).setResultsName("parenthesis") | operatorQuotes

        operatorNot = Forward()
        operatorNot << (Group(
            Suppress(Keyword("not", caseless=True)) + operatorNot
        ).setResultsName("not") | operatorParenthesis)

        operatorAnd = Forward()
        operatorAnd << (Group(
            operatorNot + Suppress(Keyword("and", caseless=True)) + operatorAnd
        ).setResultsName("and") | Group(
            operatorNot + OneOrMore(~oneOf("and or") + operatorAnd)
        ).setResultsName("and") | operatorNot)
        
        operatorOr << (Group(
            operatorAnd + Suppress(Keyword("or", caseless=True)) + operatorOr
        ).setResultsName("or") | operatorAnd)

        return operatorOr.parseString
github cascremers / scyther / scripts / if2spdl / Ifparser.py View on Github external
# Basic constructors
	Alfabet= alphas+nums+"_$"
	Number = Word(nums)

	# Typeinfo/Constant
	TypeInfo = oneOf ("mr nonce pk sk fu table")
	Constant = Word(alphas,Alfabet)

	# Time
	nTime = Number
	xTime = Literal("xTime")
	sTime = Literal("s") + lbrX + Number + rbrX
	Time = Or([nTime,xTime,sTime])

	# Const
	Const = Forward()
	ConstC = Literal("c") + lbrX + Constant + commaX + Time + rbrX
	ConstF = Literal("c(ni,ni)")
	Const << Or ([ Constant, ConstC, ConstF ])

	def stringize(s,l,t):
		return [ "".join(t) ]

	Const.setParseAction(stringize)

	# Optional prime
	def optprimeaction(s,l,t):
		if len(t) == 0:
			return [ "" ]
		else:
			return t
	optprime = Optional(Literal("'"))
github paradox-bot / paradox / NumericStringParser.py View on Github external
e     = pyp.CaselessLiteral( "E" )
        fnumber = pyp.Combine( pyp.Word( "+-"+pyp.nums, pyp.nums ) + 
                           pyp.Optional( point + pyp.Optional( pyp.Word( pyp.nums ) ) ) +
                           pyp.Optional( e + pyp.Word( "+-"+pyp.nums, pyp.nums ) ) )
        ident = pyp.Word(pyp.alphas, pyp.alphas+pyp.nums+"_$")       
        plus  = pyp.Literal( "+" )
        minus = pyp.Literal( "-" )
        mult  = pyp.Literal( "*" )
        div   = pyp.Literal( "/" )
        lpar  = pyp.Literal( "(" ).suppress()
        rpar  = pyp.Literal( ")" ).suppress()
        addop  = plus | minus
        multop = mult | div
        expop = pyp.Literal( "^" )
        pi    = pyp.CaselessLiteral( "PI" )
        expr = pyp.Forward()
        atom = ((pyp.Optional(pyp.oneOf("- +")) +
                 (pi|e|fnumber|ident+lpar+expr+rpar).setParseAction(self.pushFirst))
                | pyp.Optional(pyp.oneOf("- +")) + pyp.Group(lpar+expr+rpar)
                ).setParseAction(self.pushUMinus)       
        # by defining exponentiation as "atom [ ^ factor ]..." instead of 
        # "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-right
        # that is, 2^3^2 = 2^(3^2), not (2^3)^2.
        factor = pyp.Forward()
        factor << atom + pyp.ZeroOrMore( ( expop + factor ).setParseAction(
            self.pushFirst ) )
        term = factor + pyp.ZeroOrMore( ( multop + factor ).setParseAction(
            self.pushFirst ) )
        expr << term + pyp.ZeroOrMore( ( addop + term ).setParseAction( self.pushFirst ) )
        self.bnf = expr
        # map operator symbols to corresponding arithmetic operations
        epsilon = 1e-12
github stevearc / dql / dql / grammar / query.py View on Github external
def create_where():
    """ Create a grammar for the 'where' clause used by 'select' """
    conjunction = Forward().setResultsName("conjunction")
    nested = Group(Suppress("(") + conjunction + Suppress(")")).setResultsName(
        "conjunction"
    )

    maybe_nested = nested | constraint
    inverted = Group(not_ + maybe_nested).setResultsName("not")
    full_constraint = maybe_nested | inverted
    conjunction <<= full_constraint + OneOrMore(and_or + full_constraint)
    return upkey("where") + Group(conjunction | full_constraint).setResultsName("where")