本文整理汇总了Python中pyparsing.ZeroOrMore.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python ZeroOrMore.setParseAction方法的具体用法?Python ZeroOrMore.setParseAction怎么用?Python ZeroOrMore.setParseAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.ZeroOrMore
的用法示例。
在下文中一共展示了ZeroOrMore.setParseAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _logicals_
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def _logicals_(atomic):
"""
Return a new parser parsing logical expressions on atomics.
This parser recognizes the following grammar, with precedences
parser := atomic | '~' parser | parser '&' parser | parser '|' parser |
parser '->' parser | parser '<->' parser
Returned AST uses .ast package's classes.
"""
parser = Forward()
atom = (atomic | Suppress("(") + parser + Suppress(")"))
notstrict = "~" + atom
notstrict.setParseAction(lambda tokens: Not(tokens[1]))
not_ = notstrict | atom
and_ = not_ + ZeroOrMore("&" + not_)
and_.setParseAction(lambda tokens: _left_(And, tokens))
or_ = and_ + ZeroOrMore("|" + and_)
or_.setParseAction(lambda tokens: _left_(Or, tokens))
implies = ZeroOrMore(or_ + "->") + or_
implies.setParseAction(lambda tokens: _right_(Implies, tokens))
iff = implies + ZeroOrMore("<->" + implies)
iff.setParseAction(lambda tokens: _left_(Iff, tokens))
parser <<= iff
return parser
示例2: _logical_parser
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def _logical_parser(expression):
"""
Return a new parser parsing logical expressions.
This parser recognizes the following grammar, with precedence:
<logical> ::= expression | '~' <logical> | <logical> '&' <logical>
| <logical> '|' <logical> | <logical> '->' <logical>
| <logical> '<->' <logical>
.. note:: The parser uses :mod:`pytlq.ast` module's classes to build ASTs.
.. credit:: Adapted from Simon Busard's parser parsing logical expressions
on atomics.
"""
parser = Forward()
not_strict = Literal('~') + expression
not_strict.setParseAction(lambda tokens: Not(tokens[1]))
not_ = (not_strict | expression)
and_ = not_ + ZeroOrMore(Literal('&') + not_)
and_.setParseAction(lambda tokens: _left(And, tokens))
or_ = and_ + ZeroOrMore(Literal('|') + and_)
or_.setParseAction(lambda tokens: _left(Or, tokens))
imply = ZeroOrMore(or_ + Literal('->')) + or_
imply.setParseAction(lambda tokens: _right(Imply, tokens))
iff = imply + ZeroOrMore(Literal('<->') + imply)
iff.setParseAction(lambda tokens: _left(Iff, tokens))
parser <<= iff
return parser
示例3: cleanAnnotation
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def cleanAnnotation(filepath):
"""Clean out the obsolete or superflous annotations."""
with open(filepath, 'r') as mo_file:
string = mo_file.read()
# remove 'Window(),' and 'Coordsys()' annotations:
WindowRef = ZeroOrMore(White(' \t')) + (Keyword('Window')|Keyword('Coordsys')) + nestedExpr() + ',' + ZeroOrMore(White(' \t') + lineEnd)
out = Suppress(WindowRef).transformString(string)
# special care needs to be taken if the annotation is the last one
WindowLastRef = Optional(',') + ZeroOrMore(White(' \t')) + (Keyword('Window')|Keyword('Coordsys')) + nestedExpr() + ZeroOrMore(White(' \t') + lineEnd)
out = Suppress(WindowLastRef).transformString(out)
# remove empty '[__Dymola_]experimentSetupOutput(),' annotation:
expRef = Optional(',') + ZeroOrMore(White(' \t')) + Optional('__Dymola_') + (Keyword('experimentSetupOutput')|Keyword('experiment')|Keyword('DymolaStoredErrors')|Keyword('Diagram')|Keyword('Icon')) + ~nestedExpr() + ~CharsNotIn(',)')
out = Suppress(expRef).transformString(out)
# Remove Icon and Diagram annotations that do not contain any graphics
emptyRef = ZeroOrMore(White(' \t')) + (Keyword('Icon')|Keyword('Diagram')) + nestedExpr()('args') + ',' + ZeroOrMore(White(' \t') + lineEnd)
emptyRef.setParseAction(skipNonEmptyGraphics)
out = Suppress(emptyRef).transformString(out)
# special care for the last annotation again
emptyRef = Optional(',') + ZeroOrMore(White(' \t')) + (Keyword('Icon')|Keyword('Diagram')) + nestedExpr()('args') + ZeroOrMore(White(' \t') + lineEnd)
emptyRef.setParseAction(skipNonEmptyGraphics)
out = Suppress(emptyRef).transformString(out)
# in case we end up with empty annotations remove them too
AnnotationRef = ZeroOrMore(White(' \t')) + Keyword('annotation') + nestedExpr('(',');',content=' ') + ZeroOrMore(White(' \t') + lineEnd)
out = Suppress(AnnotationRef).transformString(out)
with open(filepath,'w') as mo_file:
mo_file.write(out)
示例4: _extract_keyword_values_termination
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def _extract_keyword_values_termination(self, line):
"""
Extracts the keyword, the values and the termination of an input line.
The values are returned as a list.
:arg line: input line
:return: keyword, values, comment
"""
keywordletters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-="
keyword = Word(keywordletters, max=8)("keyword")
value = Word(alphanums + ".-+")
values = Group(Optional(delimitedList(value)))("vals")
termination = ZeroOrMore(Word(printables))("termination")
termination.setParseAction(lambda tokens: " ".join(tokens))
expr = keyword + Suppress("(") + values + Suppress(")") + termination + stringEnd
try:
result = expr.parseString(line)
except ParseException:
return None, None, None
return result.keyword, result.vals, result.termination
示例5: parser
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def parser(cls, width, height):
"""Parse a BZW file.
For now, we're only supporting a subset of BZW's allobjects.
"""
comment = '#' + SkipTo(LineEnd())
bzw = ZeroOrMore(Box.parser() | Base.parser()).ignore(comment)
bzw.setParseAction(lambda toks: cls(width, height, toks))
return bzw
示例6: __init__
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def __init__(self, max_=60):
# define the grammar structure
digits = "0123456789"
star = Literal('*')
number = Word(digits) | Word(alphas)
steps = number
range_ = number + Optional(Literal('-') + number)
numspec = star | range_
expr = Group(numspec) + Optional(Literal('/') + steps)
extra_groups = ZeroOrMore(Literal(',') + expr)
groups = expr + extra_groups + StringEnd()
# define parse actions
star.setParseAction(self._expand_star)
number.setParseAction(self._expand_number)
range_.setParseAction(self._expand_range)
expr.setParseAction(self._filter_steps)
extra_groups.setParseAction(self._ignore_comma)
groups.setParseAction(self._join_to_set)
self.max_ = max_
self.parser = groups
示例7: gth_out
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def gth_out():
"""
A grammar to parse the responses which can come out of the GTH.
This was written with reference to gth_out.dtd
More information about the GTH API at https://www.corelatus.com/gth/api/
"""
global gth_out_grammar
if not gth_out_grammar:
# Literals
open = Suppress("<")
close = Suppress(">")
emclose = Suppress("/>")
tagattr = Word(alphas) + Suppress("=") + quotedString
ok = _empty_tag("ok", 0)
job = _empty_tag("job")
error = _empty_tag("error") | _tag("error", Word(alphas + " "))
event_child = open \
+ Word(alphas + "_0123456789").setResultsName("type") \
+ _attlist() + emclose
event = _tag("event", event_child, 0)
attributes = ZeroOrMore(_empty_tag("attribute"))
attributes.setParseAction(_collapse_attributes)
resource = _empty_tag("resource") ^ _tag("resource", attributes)
resources = ZeroOrMore(resource) ^ error
# REVISIT: state grammar below is incomplete
state = _tag("state", resources, 0)
gth_out_grammar = ok ^ job ^ event ^ state ^ resource ^ error
return gth_out_grammar
示例8: cleanAnnotation
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def cleanAnnotation(filepath, eol):
"""Clean out the obsolete or superfluous annotations."""
with io.open(filepath, 'r') as mo_file:
string = mo_file.read()
# remove old Modelica 1 'Window(),' and 'Coordsys()' annotations:
WindowRef = ZeroOrMore(White(' \t')) + (Keyword('Window')|Keyword('Coordsys')) + nestedExpr() + ',' + ZeroOrMore(White(' \t') + lineEnd)
out = Suppress(WindowRef).transformString(string)
# special care needs to be taken if the annotation is the last one
WindowLastRef = Optional(',') + ZeroOrMore(White(' \t')) + (Keyword('Window')|Keyword('Coordsys')) + nestedExpr() + ZeroOrMore(White(' \t') + lineEnd)
out = Suppress(WindowLastRef).transformString(out)
# remove empty and superfluous Dymola specific annotations:
dymolaRef = (ZeroOrMore(White(' \t'))
+ ((Optional('__Dymola_') + 'experimentSetupOutput')|
Keyword('DymolaStoredErrors'))
+ ~nestedExpr() + ',' + ZeroOrMore(White(' \t')))
out = Suppress(dymolaRef).transformString(out)
# special care of the last one again
lastDymolaRef = (Optional(',') + ZeroOrMore(White(' \t'))
+ ((Optional('__Dymola_') + 'experimentSetupOutput')|
Keyword('DymolaStoredErrors'))
+ ~nestedExpr() + ZeroOrMore(White(' \t')))
out = Suppress(lastDymolaRef).transformString(out)
# remove superfluous annotations with defaults
defaultRef = ((Keyword('rotation')|Keyword('visible')|Keyword('origin'))
+ ZeroOrMore(White(' \t')) + '=' + ZeroOrMore(White(' \t'))
+ (Keyword('0')|Keyword('true')|Keyword('{0,0}'))
+ ',' + ZeroOrMore(White(' \t')))
out = Suppress(defaultRef).transformString(out)
# special rule for initial scale in order to avoid false positives
iniSRef = (Keyword('initialScale')
+ ZeroOrMore(White(' \t')) + '=' + ZeroOrMore(White(' \t'))
+ Keyword('0.1')
+ ',' + ZeroOrMore(White(' \t')))
out = Suppress(iniSRef).transformString(out)
# special care for the last ones again
lastDefaultRef = (Optional(',')
+ (Keyword('rotation')|Keyword('visible')|Keyword('origin'))
+ ZeroOrMore(White(' \t')) + '=' + ZeroOrMore(White(' \t'))
+ (Keyword('0')|Keyword('true')|Keyword('{0,0}'))
+ ZeroOrMore(White(' \t')))
out = Suppress(lastDefaultRef).transformString(out)
lastIniSRef = (Optional(',') + Keyword('initialScale')
+ ZeroOrMore(White(' \t')) + '=' + ZeroOrMore(White(' \t'))
+ Keyword('0.1')
+ ZeroOrMore(White(' \t')))
out = Suppress(lastIniSRef).transformString(out)
# remove empty and superfluous Documentation annotation:
docRef = (ZeroOrMore(White(' \t'))
+ (Keyword('Documentation'))
+ ~nestedExpr() + ',' + ZeroOrMore(White(' \t')))
out = Suppress(docRef).transformString(out)
# special care of the last one again
lastDocRef = (Optional(',') + ZeroOrMore(White(' \t'))
+ (Keyword('Documentation'))
+ ~nestedExpr() + ZeroOrMore(White(' \t')))
out = Suppress(lastDocRef).transformString(out)
# remove Icon and Diagram annotations that do not contain any graphics
emptyRef = ZeroOrMore(White(' \t')) + (Keyword('Icon')|Keyword('Diagram')) + nestedExpr()('args') + ',' + ZeroOrMore(White(' \t') + lineEnd)
emptyRef.setParseAction(skipNonEmptyGraphics)
out = Suppress(emptyRef).transformString(out)
# special care for the last annotation again
lastEmptyRef = Optional(',') + ZeroOrMore(White(' \t')) + (Keyword('Icon')|Keyword('Diagram')) + nestedExpr()('args') + ZeroOrMore(White(' \t') + lineEnd)
lastEmptyRef.setParseAction(skipNonEmptyGraphics)
out = Suppress(lastEmptyRef).transformString(out)
# in case we end up with empty annotations remove them too
AnnotationRef = ZeroOrMore(White(' \t')) + Keyword('annotation') + nestedExpr('(',');',content=' ') + ZeroOrMore(White(' \t') + lineEnd)
out = Suppress(AnnotationRef).transformString(out)
with io.open(filepath,'w', newline= eol) as mo_file:
mo_file.write(out)
示例9: _define_grammar
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def _define_grammar():
"""
Creates and returns a copy of the selector grammar.
Wrapped in a function to avoid polluting the module namespace.
"""
expr = Forward()
label_name = Word(LABEL_CHARS)
label_name.setParseAction(LabelNode)
string_literal = QuotedString('"') | QuotedString("'")
string_literal.setParseAction(LiteralNode)
set_literal = (Suppress("{") +
delimitedList(QuotedString('"') | QuotedString("'"), ",") +
Suppress("}"))
set_literal.setParseAction(SetLiteralNode)
eq_comparison = label_name + Suppress("==") + string_literal
eq_comparison.setParseAction(LabelToLiteralEqualityNode)
not_eq_comparison = label_name + Suppress("!=") + string_literal
not_eq_comparison.setParseAction(InequalityNode)
in_comparison = label_name + Suppress(Keyword("in")) + set_literal
in_comparison.setParseAction(LabelInSetLiteralNode)
not_in = Suppress(Keyword("not") + Keyword("in"))
not_in_comparison = label_name + not_in + set_literal
not_in_comparison.setParseAction(NotInNode)
has_check = (Suppress("has(") +
Word(LABEL_CHARS) +
Suppress(")"))
has_check.setParseAction(HasNode)
# For completeness, we allow an all() to occur in an expression like
# "! all()". Note: we special-case the trivial selectors "" and
# "all()" below for efficiency.
all_op = (Suppress("all()"))
all_op.setParseAction(AllNode)
comparison = (eq_comparison |
not_eq_comparison |
in_comparison |
not_in_comparison |
has_check |
all_op)
paren_expr = (Suppress("(") + expr + Suppress(")"))
value = ZeroOrMore("!") + (comparison | paren_expr)
value.setParseAction(simplify_negation_node)
and_expr = value + ZeroOrMore(Suppress("&&") + value)
and_expr.setParseAction(simplify_and_node)
or_expr = and_expr + ZeroOrMore(Suppress("||") + and_expr)
or_expr.setParseAction(simplify_or_node)
expr << or_expr
grammar = expr + StringEnd()
return grammar
示例10: len
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
Create an array from the given list of `tokens`.
:param tokens: a non-empty list of tokens
"""
if len(tokens) <= 1:
return tokens[0]
elif len(tokens[1]) == 1:
return _handle_array([Subscript(tokens[0], tokens[1][0])] + tokens[2:])
else: # len(tokens[1]) == 2
return _handle_array([BitSelection(tokens[0], tokens[1][0], tokens[1][1])] + tokens[2:])
_array.setParseAction(lambda s, l, t: _handle_array(t))
_not = ZeroOrMore("!") + _array
_not.setParseAction(lambda s, l, t: reduce(lambda e, n: Not(e), t[:-1], t[-1]))
_concat = _not + ZeroOrMore(Suppress("::") + _not)
_concat.setParseAction(lambda s, l, t: reduce(lambda e, n: Concat(e, n), t[0:1] + t[2::2]))
_minus = ZeroOrMore("-") + _concat
_minus.setParseAction(lambda s, l, t: reduce(lambda e, n: Minus(e), t[:-1], t[-1]))
_mult = _minus + ZeroOrMore(oneOf("* / mod") + _minus)
_mult.setParseAction(lambda s, l, t: _reduce_list_to_expr(t))
_add = _mult + ZeroOrMore(oneOf("+ -") + _mult)
_add.setParseAction(lambda s, l, t: _reduce_list_to_expr(t))
_shift = _add + ZeroOrMore(oneOf("<< >>") + _add)
_shift.setParseAction(lambda s, l, t: _reduce_list_to_expr(t))
示例11: make_grammar
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def make_grammar():
from pyparsing import (ParserElement, Literal, Word, Forward,
Optional, QuotedString, Combine,
ZeroOrMore, Keyword, alphas, alphanums,
nums)
ParserElement.enablePackrat()
plus = Literal("+")
minus = Literal("-")
mul = Literal("*")
div = Literal("/")
floordiv = Literal("//")
mod = Literal("%")
lt = Literal("<")
le = Literal("<=")
gt = Literal(">")
ge = Literal(">=")
lshift = Literal("<<")
rshift = Literal(">>")
equal = Literal("==") | Literal("=") | Literal("!=")
bitwise_not = Literal("~")
bitwise_and = Literal("&")
bitwise_or = Literal("|")
bitwise_xor = Literal("^")
logical_not = Literal("!") | Keyword("not")
logical_and = Literal("&&") | Literal("and") | Keyword("AND")
logical_or = Literal("||") | Keyword("or") | Keyword("OR")
ident = Word(alphas + "_", alphanums + "_")
functionname = Word(alphas + "_", alphanums + "_")
unit = Word(alphas)
int_number = Word(nums)
float_number = Combine(Word(nums) + Optional(Literal(".") + Word(nums)))
number = (float_number | int_number) + Optional(unit)
lparent = Literal("(").suppress()
rparent = Literal(")").suppress()
relational_op = (lt | le | gt | ge)
shift = (lshift | rshift)
add_op = (plus | minus)
mul_op = (mul | floordiv | div | mod)
expr = Forward()
string = (QuotedString('"') | QuotedString("'"))
primary_expr = ident | number | string | (lparent + expr + rparent)
def make_op(s, loc, toks):
if len(toks) == 1:
return toks[0]
else:
def loop(lhs, rest):
if len(rest) == 0:
return lhs
else:
return loop(Operator(rest[0], lhs, rest[1]), rest[2:])
return loop(Operator(toks[1], toks[0], toks[2]), toks[3:])
def make_unary(s, loc, toks):
if len(toks) == 1:
return toks[0]
else:
return UnaryOperator(toks[0], make_unary(s, loc, toks[1:]))
argument_expression_list = expr + ZeroOrMore(Literal(",").suppress() + expr)
function_expression = (functionname + lparent + argument_expression_list + rparent)
postfix_expression = function_expression | primary_expr
unary_expr = ZeroOrMore(bitwise_not | logical_not | minus | plus) + postfix_expression
cast_expresion = unary_expr | postfix_expression
mult_expr = cast_expresion + ZeroOrMore(mul_op + cast_expresion) # noqa: E221
add_expr = mult_expr + ZeroOrMore(add_op + mult_expr) # noqa: E221
shift_expr = add_expr + ZeroOrMore(shift + add_expr) # noqa: E221
relational_expr = shift_expr + ZeroOrMore(relational_op + shift_expr) # noqa: E221
equality_expr = relational_expr + ZeroOrMore(equal + relational_expr) # noqa: E221
bitwise_and_expr = equality_expr + ZeroOrMore(bitwise_and + equality_expr) # noqa: E221
bitwise_xor_expr = bitwise_and_expr + ZeroOrMore(bitwise_xor + bitwise_and_expr) # noqa: E221
bitwise_or_expr = bitwise_xor_expr + ZeroOrMore(bitwise_or + bitwise_xor_expr) # noqa: E221
logical_and_expr = bitwise_or_expr + ZeroOrMore(logical_and + bitwise_or_expr) # noqa: E221
logical_or_expr = logical_and_expr + ZeroOrMore(logical_or + logical_and_expr) # noqa: E221
expr <<= logical_or_expr
function_expression.setParseAction(Function)
int_number.setParseAction(lambda s, loc, toks: int(toks[0]))
float_number.setParseAction(lambda s, loc, toks: float(toks[0]))
number.setParseAction(Number)
string.setParseAction(String)
ident.setParseAction(Variable)
unary_expr.setParseAction(make_unary)
mult_expr.setParseAction(make_op)
#.........这里部分代码省略.........
示例12: Group
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
gArgList = Group(LPAR + delimitedList(exp) + RPAR)
gCall = gIdent + gArgList
gCall.setParseAction(lambda t: GCall(t[0], list(t[1])))
exp << (constructor | fCall | gCall | variable)
patternArgList = Group(Optional(LPAR + Optional(delimitedList(lIdent)) + RPAR))
pattern = uIdent + patternArgList
fParamList = Group(Optional(delimitedList(lIdent)))
fRule = fIdent + LPAR + fParamList + RPAR + EQ + exp + SC
fRule.setParseAction(lambda t: FRule(t[0], list(t[1]), t[2]))
gParamList = Group(Optional(Suppress(",") + delimitedList(lIdent)))
gRule = gIdent + LPAR + pattern + gParamList + RPAR + EQ + exp + SC
gRule.setParseAction(lambda t: GRule(t[0], t[1], list(t[2]), list(t[3]), t[4]))
program = ZeroOrMore(fRule | gRule)
program.setParseAction(lambda t: Program(list(t)))
def pExp(input):
return exp.parseString(input, True)[0]
def pProg(input):
return program.parseString(input, True)[0]
示例13: Literal
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
comment = Literal("//") + Regex("[^\\n]*") + LineEnd()
field_type = Regex("[A-Za-z0-9_]+")
field_name = Regex("[A-Za-z0-9_]+")
field_number = Regex("[0-9]+")
message_field = ((Keyword("required") | Keyword("optional") | Keyword("repeated"))
+ field_type + field_name + Suppress("=") + field_number + Suppress(";"))
message_field.setParseAction(Field)
message_name = Regex("[A-Za-z_]+")
message_spec = (Suppress(Keyword("message")) + message_name + Suppress("{") +
Group(ZeroOrMore(message_field)) + Suppress("}"))
message_spec.setParseAction(Message)
option_spec = (Suppress(Keyword("option")) + Regex("[a-z_]+") + Suppress("=") +
Regex('"[^"]*"') + Suppress(";"))
option_spec.setParseAction(lambda tokens: (tokens[0], tokens[1][1:-1]))
option_list = ZeroOrMore(option_spec)
option_list.setParseAction(lambda tokens: dict(tokens.asList()))
message_list = Group(ZeroOrMore(message_spec))
proto_file = (option_list + message_list).ignore(comment)
if len(sys.argv) < 3:
print "usage: simpleproto some_file.proto outputfolder"
print "The output will be placed in a folder within outputfolder"
print "appropriate for the package specified in the file's java_package"
print "option, in the file specified by java_outer_classname."
options, messages = proto_file.parseFile(sys.argv[1], parseAll=True).asList()
output_class = options["java_outer_classname"]
output_package = options["java_package"]
output_file_path = os.path.join(sys.argv[2], output_package.replace(
".", os.path.sep), output_class + ".java")
output_file = open(output_file_path, "w")
示例14: parse
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
def parse (input):
# parse a string into an element of the abstract representation
# Grammar:
#
# <expr> ::= <integer>
# true
# false
# <identifier>
# ( if <expr> <expr> <expr> )
# ( let ( ( <name> <expr> ) ... ) <expr )
# ( function ( <name> ... ) <expr> )
# ( <expr> <expr> ... )
# ( call/cc <expr>)
#
idChars = alphas+"_+*-?!=<>"
pIDENTIFIER = Word(idChars, idChars+"0123456789")
pIDENTIFIER.setParseAction(lambda result: EId(result[0]))
# A name is like an identifier but it does not return an EId...
pNAME = Word(idChars,idChars+"0123456789")
pNAMES = ZeroOrMore(pNAME)
pNAMES.setParseAction(lambda result: [result])
pINTEGER = Word("0123456789")
pINTEGER.setParseAction(lambda result: EValue(VInteger(int(result[0]))))
pBOOLEAN = Keyword("true") | Keyword("false")
pBOOLEAN.setParseAction(lambda result: EValue(VBoolean(result[0]=="true")))
pEXPR = Forward()
pEXPRS = ZeroOrMore(pEXPR)
pEXPRS.setParseAction(lambda result: [result])
pIF = "(" + Keyword("if") + pEXPR + pEXPR + pEXPR + ")"
pIF.setParseAction(lambda result: EIf(result[2],result[3],result[4]))
pBINDING = "(" + pNAME + pEXPR + ")"
pBINDING.setParseAction(lambda result: (result[1],result[2]))
pBINDINGS = ZeroOrMore(pBINDING)
pBINDINGS.setParseAction(lambda result: [ result ])
def makeLet (bindings,body):
params = [ param for (param,exp) in bindings ]
args = [ exp for (param,exp) in bindings ]
return ECall(EFunction(params,body),args)
pLET = "(" + Keyword("let") + "(" + pBINDINGS + ")" + pEXPR + ")"
pLET.setParseAction(lambda result: makeLet(result[3],result[5]))
pCALL = "(" + pEXPR + pEXPRS + ")"
pCALL.setParseAction(lambda result: ECall(result[1],result[2]))
pFUN = "(" + Keyword("function") + "(" + pNAMES + ")" + pEXPR + ")"
pFUN.setParseAction(lambda result: EFunction(result[3],result[5]))
pFUNrec = "(" + Keyword("function") + pNAME + "(" + pNAMES + ")" + pEXPR + ")"
pFUNrec.setParseAction(lambda result: EFunction(result[4],result[6],name=result[2]))
def makeDo (exprs):
result = exprs[-1]
for e in reversed(exprs[:-1]):
# space is not an allowed identifier in the syntax!
result = makeLet([(" ",e)],result)
return result
pDO = "(" + Keyword("do") + pEXPRS + ")"
pDO.setParseAction(lambda result: makeDo(result[2]))
def makeWhile (cond,body):
return makeLet([(" while",
EFunction([],EIf(cond,makeLet([(" ",body)],ECall(EId(" while"),[])),EValue(VNone())),name=" while"))],
ECall(EId(" while"),[]))
pWHILE = "(" + Keyword("while") + pEXPR + pEXPR + ")"
pWHILE.setParseAction(lambda result: makeWhile(result[2],result[3]))
pCALLCC = "(" + Keyword("call/cc") + pEXPR + ")"
pCALLCC.setParseAction(lambda result: ECallCC(result[2]))
pEXPR << (pINTEGER | pBOOLEAN | pIDENTIFIER | pIF | pLET | pFUN | pFUNrec| pDO | pWHILE | pCALLCC | pCALL)
# can't attach a parse action to pEXPR because of recursion, so let's duplicate the parser
pTOPEXPR = pEXPR.copy()
pTOPEXPR.setParseAction(lambda result: {"result":"expression","expr":result[0]})
pDEFINE = "(" + Keyword("define") + pNAME + pEXPR + ")"
pDEFINE.setParseAction(lambda result: {"result":"value",
"name":result[2],
"expr":result[3]})
pDEFUN = "(" + Keyword("defun") + pNAME + "(" + pNAMES + ")" + pEXPR + ")"
pDEFUN.setParseAction(lambda result: {"result":"function",
"name":result[2],
#.........这里部分代码省略.........
示例15: _build_asn1_grammar
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import setParseAction [as 别名]
#.........这里部分代码省略.........
boolean_type = BOOLEAN
real_type = REAL
null_type = NULL
object_identifier_type = OBJECT_IDENTIFIER
octetstring_type = OCTET_STRING + Optional(size_constraint)
unrestricted_characterstring_type = CHARACTER_STRING
restricted_characterstring_type = BMPString | GeneralString | \
GraphicString | IA5String | \
ISO646String | NumericString | \
PrintableString | TeletexString | \
T61String | UniversalString | \
UTF8String | VideotexString | VisibleString
characterstring_type = restricted_characterstring_type | unrestricted_characterstring_type
useful_type = GeneralizedTime | UTCTime | ObjectDescriptor
# todo: consider other builtins from 16.2
simple_type = (boolean_type | null_type | octetstring_type | characterstring_type | real_type | plain_integer_type | object_identifier_type | useful_type) + Optional(constraint)
constructed_type = choice_type | sequence_type | set_type
value_list_type = restricted_integer_type | enumerated_type
builtin_type = value_list_type | tagged_type | simple_type | constructed_type | sequenceof_type | setof_type | bitstring_type
type_ << (builtin_type | referenced_type)
# EXT: identifier should not be Optional here, but
# our other ASN.1 code generator supports unnamed members,
# and we use them.
named_type << (Optional(identifier) + type_)
type_assignment = typereference + '::=' + type_
value_assignment = valuereference + type_ + '::=' + value
assignment = type_assignment | value_assignment
assignment_list = ZeroOrMore(assignment)
assigned_identifier = Optional(object_identifier_value | defined_value)
global_module_reference = module_reference + assigned_identifier
symbol = Unique(reference) # TODO: parameterized reference?
symbol_list = Group(delimitedList(symbol))
symbols_from_module = symbol_list + Suppress(FROM) + global_module_reference
symbols_from_module_list = OneOrMore(symbols_from_module)
symbols_imported = Optional(symbols_from_module_list)
exports = Optional(Suppress(EXPORTS) + symbol_list + Suppress(';'))
imports = Optional(Suppress(IMPORTS) + symbols_imported + Suppress(';'))
module_body = (exports + imports + assignment_list)
module_defaults = Suppress(tag_default + extension_default) # we don't want these in the AST
module_identifier = module_reference + definitive_identifier
module_definition = module_identifier + DEFINITIONS + module_defaults + '::=' + BEGIN + module_body + END
module_definition.ignore(comment)
# Mark up the parse results with token tags
identifier.setParseAction(annotate('Identifier'))
named_number_value.setParseAction(annotate('Value'))
tag.setParseAction(annotate('Tag'))
class_.setParseAction(annotate('TagClass'))
class_number.setParseAction(annotate('TagClassNumber'))
type_.setParseAction(annotate('Type'))
simple_type.setParseAction(annotate('SimpleType'))
choice_type.setParseAction(annotate('ChoiceType'))
sequence_type.setParseAction(annotate('SequenceType'))
set_type.setParseAction(annotate('SetType'))
value_list_type.setParseAction(annotate('ValueListType'))
bitstring_type.setParseAction(annotate('BitStringType'))
referenced_type.setParseAction(annotate('ReferencedType'))
sequenceof_type.setParseAction(annotate('SequenceOfType'))
setof_type.setParseAction(annotate('SetOfType'))
named_number.setParseAction(annotate('NamedValue'))
constraint.setParseAction(annotate('Constraint'))
size_constraint.setParseAction(annotate('SizeConstraint'))
component_type.setParseAction(annotate('ComponentType'))
component_type_optional.setParseAction(annotate('ComponentTypeOptional'))
component_type_default.setParseAction(annotate('ComponentTypeDefault'))
component_type_components_of.setParseAction(annotate('ComponentTypeComponentsOf'))
tagged_type.setParseAction(annotate('TaggedType'))
named_type.setParseAction(annotate('NamedType'))
type_assignment.setParseAction(annotate('TypeAssignment'))
value_assignment.setParseAction(annotate('ValueAssignment'))
valuereference.setParseAction(annotate('ValueReference'))
module_reference.setParseAction(annotate('ModuleReference'))
module_body.setParseAction(annotate('ModuleBody'))
module_definition.setParseAction(annotate('ModuleDefinition'))
extension_marker.setParseAction(annotate('ExtensionMarker'))
name_form.setParseAction(annotate('NameForm'))
number_form.setParseAction(annotate('NumberForm'))
name_and_number_form.setParseAction(annotate('NameAndNumberForm'))
object_identifier_value.setParseAction(annotate('ObjectIdentifierValue'))
definitive_identifier.setParseAction(annotate('DefinitiveIdentifier'))
definitive_number_form.setParseAction(annotate('DefinitiveNumberForm'))
definitive_name_and_number_form.setParseAction(annotate('DefinitiveNameAndNumberForm'))
imports.setParseAction(annotate('Imports'))
exports.setParseAction(annotate('Exports'))
assignment_list.setParseAction(annotate('AssignmentList'))
bstring.setParseAction(annotate('BinaryStringValue'))
hstring.setParseAction(annotate('HexStringValue'))
start = OneOrMore(module_definition)
return start