How to use the pyparsing.oneOf 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 scVENUS / PeekabooAV / peekaboo / ruleset / expressions.py View on Github external
result.setParseAction(EvalResult)
        rvallist.setParseAction(EvalList)
        rvalset.setParseAction(EvalSet)

        identity_test = Keyword('is') + ~Keyword('not') | Combine(
            Keyword('is') + Keyword('not'), adjacent=False, joinString=' ')
        membership_test = Keyword('in') | Combine(
            Keyword('not') + Keyword('in'), adjacent=False, joinString=' ')
        comparison_op = oneOf('< <= > >= != == isdisjoint')
        comparison = identity_test | membership_test | comparison_op

        self.parser = infixNotation(operand, [
            (Literal('**'), 2, opAssoc.LEFT, EvalPower),
            (oneOf('+ - ~'), 1, opAssoc.RIGHT, EvalModifier),
            (oneOf('* / // %'), 2, opAssoc.LEFT, EvalArith),
            (oneOf('+ -'), 2, opAssoc.LEFT, EvalArith),
            (oneOf('<< >>'), 2, opAssoc.LEFT, EvalArith),
            (Literal('&'), 2, opAssoc.LEFT, EvalArith),
            (Literal('^'), 2, opAssoc.LEFT, EvalArith),
            (Literal('|'), 2, opAssoc.LEFT, EvalArith),
            (comparison, 2, opAssoc.LEFT, EvalLogic),
            (Keyword('not'), 1, opAssoc.RIGHT, EvalModifier),
            (Keyword('and'), 2, opAssoc.LEFT, EvalLogic),
            (Keyword('or'), 2, opAssoc.LEFT, EvalLogic),
            (Keyword('->'), 2, opAssoc.LEFT, EvalArith),
        ])
github pyparsing / pyparsing / examples / verilogParse.py View on Github external
else_ = Keyword("else")
        edge = Keyword("edge")
        posedge = Keyword("posedge")
        negedge = Keyword("negedge")
        specify = Keyword("specify")
        endspecify = Keyword("endspecify")
        fork = Keyword("fork")
        join = Keyword("join")
        begin = Keyword("begin")
        end = Keyword("end")
        default = Keyword("default")
        forever = Keyword("forever")
        repeat = Keyword("repeat")
        while_ = Keyword("while")
        for_ = Keyword("for")
        case = oneOf("case casez casex")
        endcase = Keyword("endcase")
        wait = Keyword("wait")
        disable = Keyword("disable")
        deassign = Keyword("deassign")
        force = Keyword("force")
        release = Keyword("release")
        assign = Keyword("assign")

        eventExpr = Forward()
        eventTerm = (
            (posedge + expr) | (negedge + expr) | expr | (LPAR + eventExpr + RPAR)
        )
        eventExpr << (Group(delimitedList(eventTerm, Keyword("or"))))
        eventControl = Group(
            "@" + ((LPAR + eventExpr + RPAR) | identifier | "*")
        ).setName("eventCtrl")
github pyparsing / pyparsing / examples / lua_parser.py View on Github external
exp_atom = (
    NIL
    | FALSE
    | TRUE
    | number
    | string
    | ELLIPSIS
    | functioncall
    | var  # prefixexp
    | tableconstructor
)

exp <<= pp.infixNotation(
    exp_atom,
    [
        (pp.oneOf("+ -"), 2, pp.opAssoc.LEFT),
        (AND, 2, pp.opAssoc.LEFT),
        (OR, 2, pp.opAssoc.LEFT),
    ],
)

assignment_stat = pp.Optional(LOCAL) + varlist1 + EQ + explist1
func_call_stat = pp.Optional(LOCAL) + functioncall
do_stat = DO + block + END
while_stat = WHILE + exp + block + END
repeat_stat = REPEAT + block + UNTIL + exp
for_loop_stat = (
    FOR + name + EQ + exp + COMMA + exp + pp.Optional(COMMA + exp) + DO + block + END
)
for_seq_stat = FOR + namelist + IN + explist1 + DO + block + END
if_stat = (
    IF
github pyparsing / pyparsing / examples / booleansearchparser.py View on Github external
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 pyparsing / pyparsing / examples / verilogParse.py View on Github external
+ Optional(expandRange)
            + Optional(delay)
            + Group(delimitedList(~inputOutput + identifier))
        )
        netDecl3Arg = (
            nettype
            + Optional(driveStrength)
            + Optional(expandRange)
            + Optional(delay)
            + Group(delimitedList(assgnmt))
        )
        netDecl1 = Group(netDecl1Arg + SEMI).setName("netDecl1")
        netDecl2 = Group(netDecl2Arg + SEMI).setName("netDecl2")
        netDecl3 = Group(netDecl3Arg + SEMI).setName("netDecl3")

        gateType = oneOf(
            "and  nand  or  nor xor  xnor buf  bufif0 bufif1 "
            "not  notif0 notif1  pulldown pullup nmos  rnmos "
            "pmos rpmos cmos rcmos   tran rtran  tranif0  "
            "rtranif0  tranif1 rtranif1"
        )
        gateInstance = (
            Optional(Group(identifier + Optional(range)))
            + LPAR
            + Group(delimitedList(expr))
            + RPAR
        )
        gateDecl = Group(
            gateType
            + Optional(driveStrength)
            + Optional(delay)
            + delimitedList(gateInstance)
github ColdGrub1384 / Pyto / site-packages / _stash / system / shparsers.py View on Github external
uq_word = (pp.Literal('&3') | pp.Word(_WORD_CHARS)).setParseAction(self.uq_word_action)
        bq_word = pp.QuotedString('`', escChar='\\', unquoteResults=False).setParseAction(self.bq_word_action)
        dq_word = pp.QuotedString('"', escChar='\\', unquoteResults=False).setParseAction(self.dq_word_action)
        sq_word = pp.QuotedString("'", escChar='\\', unquoteResults=False).setParseAction(self.sq_word_action)
        # The ^ operator means longest match (as opposed to | which means first match)
        word = pp.Combine(pp.OneOrMore(escaped ^ escaped_oct ^ escaped_hex
                                       ^ uq_word ^ bq_word ^ dq_word ^ sq_word))\
            .setParseAction(self.word_action)

        identifier = pp.Word(pp.alphas + '_', pp.alphas + pp.nums + '_').setParseAction(self.identifier_action)
        assign_op = pp.Literal('=').setParseAction(self.assign_op_action)
        assignment_word = pp.Combine(identifier + assign_op + word).setParseAction(self.assignment_word_action)

        punctuator = pp.oneOf('; &').setParseAction(self.punctuator_action)
        pipe_op = pp.Literal('|').setParseAction(self.pipe_op_action)
        io_redirect_op = pp.oneOf('>> >').setParseAction(self.io_redirect_op_action)
        io_redirect = (io_redirect_op + word)('io_redirect')

        # The optional ' ' is a workaround to a possible bug in pyparsing.
        # The position of cmd_word after cmd_prefix is always reported 1 character ahead
        # of the correct value.
        cmd_prefix = (pp.OneOrMore(assignment_word) + pp.Optional(' '))('cmd_prefix')
        cmd_suffix = (pp.OneOrMore(word)('args') + pp.Optional(io_redirect)) ^ io_redirect

        modifier = pp.oneOf('! \\')
        cmd_word = (pp.Combine(pp.Optional(modifier) + word) ^ word)('cmd_word').setParseAction(self.cmd_word_action)

        simple_command = \
            (cmd_prefix + pp.Optional(cmd_word) + pp.Optional(cmd_suffix)) \
            | (cmd_word + pp.Optional(cmd_suffix))
        simple_command = pp.Group(simple_command)
github uwescience / raco / raco / datalog / grammar.py View on Github external
# a list of string literals representing opcodes
opcodes = sum([oc.literals for oc in binopclasses], [])

binopstr = " ".join(opcodes)


def parsebinop(opexpr):
    "parse action for binary operators"
    left, opstr, right = opexpr

    for opclass in binopclasses:
        if opstr in opclass.literals:
            return opclass(left, right)

binop = oneOf(binopstr)
arithSign = Word("+-", exact=1)

realNum = Combine(Optional(arithSign) +
                  (Word(nums) + "." + Optional(Word(nums)) | ("." + Word(nums)))  # noqa
                  + Optional(E + Optional(arithSign) + Word(nums)))
realNum.setParseAction(lambda x: expression.NumericLiteral(float(x[0])))

intNum = Combine(Optional(arithSign) + Word(nums) +
                 Optional(E + Optional("+") + Word(nums)))
intNum.setParseAction(lambda x: expression.NumericLiteral(int(x[0])))

number = realNum | intNum

variable = ident.copy()
variable.setParseAction(lambda x: model.Var(x[0]))
github OpenMDAO / OpenMDAO-Framework / openmdao.util / src / openmdao / util / filewrap.py View on Github external
dot = "."
        sign = oneOf("+ -")
        ee = CaselessLiteral('E') | CaselessLiteral('D')
        
        num_int = ToInteger(Combine( Optional(sign) + digits ))
        
        num_float = ToFloat(Combine( Optional(sign) + 
                            ((digits + dot + Optional(digits)) |
                             (dot + digits)) +
                             Optional(ee + Optional(sign) + digits)
                            ))
        
        # special case for a float written like "3e5"
        mixed_exp = ToFloat(Combine( digits + ee + Optional(sign) + digits ))
        
        nan = ToInf(oneOf("Inf -Inf")) | \
              ToNan(oneOf("NaN nan NaN%  NaNQ NaNS qNaN sNaN " + \
                            "1.#SNAN 1.#QNAN -1.#IND"))
    
        string_text = Word(textchars)
            
        self.line_parse_token = ( OneOrMore( (nan | num_float | mixed_exp | num_int |
                                              string_text) ) )
github pybel / pybel / src / pybel / parser / modifiers / constants.py View on Github external
# -*- coding: utf-8 -*-

"""Contains constants"""

from pyparsing import Keyword, MatchFirst, oneOf

from ..exc import PlaceholderAminoAcidWarning
from ... import language

aa_single = oneOf(list(language.amino_acid_dict.keys()))
aa_single.setParseAction(lambda s, l, t: [language.amino_acid_dict[t[0]]])

aa_triple = oneOf(list(language.amino_acid_dict.values()))

#: In biological literature, the X is used to denote a truncation. Text mining efforts often encode X as an amino
#: acid, for which we will throw an error using :func:`handle_aa_placeholder`
aa_placeholder = Keyword('X')


def handle_aa_placeholder(line, position, tokens):
    """Raises an exception when encountering a placeholder amino acid, ``X``"""
    raise PlaceholderAminoAcidWarning(-1, line, position, tokens[0])


aa_placeholder.setParseAction(handle_aa_placeholder)
github abesto / python_ircd / include / abnf.py View on Github external
# Used as part of params
middle = Group(nospcrlfcl + ZeroOrMore(':' ^ nospcrlfcl))

# Used as part of params
trailing = Group(ZeroOrMore(oneOf([':', ' ']) ^ nospcrlfcl))

params = (((0, 14) * (space + middle)) +
             Optional(space + Suppress(':') + trailing)) ^ \
         (14 * (space + middle) +
          Optional(space + Optional(Suppress(':')) + trailing))
params.leaveWhitespace()

servername = hostname

ip4addr = 3 * ((1, 3) * digit + '.') + ((1, 3) * digit)
ip6addr = ('0:0:0:0:0:' + oneOf('0 FFFF') + ':' + ip4addr) ^ \
          (OneOrMore(hexdigit) + 7 * (':' + OneOrMore(hexdigit)))
hostaddr = ip4addr ^ ip6addr

host = hostname ^ hostaddr

user = OneOrMore(charclass(
    (0x01, 0x09),
    (0x0B, 0x0C),
    (0x0E, 0x1F),
    (0x21, 0x3F),
    (0x41, 0xFF)
)).leaveWhitespace()


nickname = (letter ^ special) + \
           (0, 8) * (letter ^ digit ^ special ^ '-')