本文整理汇总了Python中pyparsing.ZeroOrMore.ignore方法的典型用法代码示例。如果您正苦于以下问题:Python ZeroOrMore.ignore方法的具体用法?Python ZeroOrMore.ignore怎么用?Python ZeroOrMore.ignore使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.ZeroOrMore
的用法示例。
在下文中一共展示了ZeroOrMore.ignore方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: defineParsers
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def defineParsers():
#Enable a fast parsing mode with caching.
ParserElement.enablePackrat()
#end of line terminates statements, so it is not regular whitespace
ParserElement.setDefaultWhitespaceChars('\t ')
func_call = Forward() #forward declaration because this is a recursive rule
#The "terminal" rules
symbol = Word(alphas+'_-', alphanums+'_-') .setParseAction(action_symbol)
q_symbol = quotedString .setParseAction(action_q_symbol)
bracket_term = Literal("(").suppress() - func_call \
+ Literal(")").suppress()
word = symbol | q_symbol | bracket_term
#The function call
#Parse: "foo | bar | baz" or "foo"
pipeline = (word + ZeroOrMore("|" - word)) .setParseAction(action_pipeline)
#Parse "foo|bar op1 op2 op3"
func_call << (pipeline - ZeroOrMore(word)) .setParseAction(action_func_call)
#High level structure of program
line = LineEnd() | func_call - LineEnd() #empty line or function call
program = ZeroOrMore(line) + StringEnd() #multiple lines are a program
#define the comments
program.ignore('%' + restOfLine)
#no tab expansion
program.parseWithTabs()
#return additional func_call parser to make testing more easy
return program, func_call
示例2: _parse_items
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def _parse_items(self, source):
ParserElement.setDefaultWhitespaceChars(' \t\r')
EOL = LineEnd().suppress()
comment = Literal('#') + Optional( restOfLine ) + EOL
string = CharsNotIn("\n")
line = Group(
Word(alphanums + '-')('key') + Literal(':').suppress() + Optional(Combine(string + ZeroOrMore(EOL + Literal(' ') + string)))("value") + EOL
)
group = ZeroOrMore(line)
group.ignore(comment)
return group.parseString(source, True)
示例3: parser
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def parser():
rule = Forward()
body = OneOrMore(CharsNotIn('{};') + ';')
sel = CharsNotIn('{};')
rule <<= sel + Group( '{' + ZeroOrMore( rule | body ) + '}' )
rule.setParseAction( make_action(Rule) )
stylesheet = ZeroOrMore( rule )
stylesheet.ignore( cStyleComment )
return stylesheet
示例4: build_parser
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def build_parser():
key = Word(alphanums).setResultsName('key')
value = restOfLine.setParseAction(
lambda string, location, tokens: tokens[0].strip()
).setResultsName('value')
property_ = Group(key + Suppress(Literal('=')) + value)
properties = Group(OneOrMore(property_)).setResultsName('properties')
section_name = (Suppress('[') + OneOrMore(CharsNotIn(']')) +
Suppress(']')).setResultsName('section')
section = Group(section_name + properties)
ini_file = ZeroOrMore(section).setResultsName('sections')
ini_file.ignore(pythonStyleComment)
return ini_file
示例5: create_grammar
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def create_grammar():
global arrows
global stereotypes
assert len(arrows) > 0
assert len(stereotypes) > 0
linechars = ''.join((c for c in printables if c not in '}\n')) + ' \t'
norbracket = ''.join((c for c in printables if c != ']')) + ' \t'
nogt = ''.join((c for c in printables if c != '>')) + ' \t'
norparen = ''.join((c for c in printables if c != ')')) + ' \t'
line = Word(linechars)
cls_body = Group(ZeroOrMore(line))
classkeyword = Keyword('class').setResultsName('type')
st_names = stereotypes.keys()
st = Literal(st_names[0])
for s in st_names[1:]:
st = st | Literal(s)
stereotype = Group(Optional(Literal('<<').suppress() + st + Literal('>>').suppress()))
identifier_list = Word(alphas) + ZeroOrMore(Literal(',').suppress() + Word(alphas))
baseclasses = Group(Optional(Literal(':').suppress() + identifier_list))
cls = Group(stereotype + classkeyword + Word(alphas) + baseclasses + \
Literal('{').suppress() + cls_body + Literal('}').suppress())
arrow_names = arrows.keys()
arrow_names.sort(lambda x,y: -cmp(len(x), len(y)))
arrow = Keyword(arrow_names[0])
for ar in arrow_names[1:]:
arrow = arrow | Keyword(ar)
relation_caption = Literal('(').suppress() + Word(norparen) + \
Literal(')').suppress()
quantifier = Literal('[').suppress() + Word(norbracket) + Literal(']').suppress()
relation = Group(
Word(alphas) + Group(Optional(quantifier)) + \
arrow.setResultsName('type') + \
Word(alphas) + Group(Optional(quantifier)) + \
Group(Optional(relation_caption))
)
grammar = ZeroOrMore(cls | relation)
grammar.ignore(cStyleComment)
grammar.ignore("//" + restOfLine)
return grammar
示例6: getkw_bnf
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def getkw_bnf(self):
sect_begin = Literal("{").suppress()
sect_end = Literal("}").suppress()
array_begin = Literal("[").suppress()
array_end = Literal("]").suppress()
tag_begin = Literal("<").suppress()
tag_end = Literal(">").suppress()
eql = Literal("=").suppress()
dmark = Literal('$').suppress()
end_data=Literal('$end').suppress()
prtable = alphanums+r'!$%&*+-./<>[email protected]^_|~'
ival=Regex('[-]?\d+')
dval=Regex('-?\d+\.\d*([eE]?[+-]?\d+)?')
lval=Regex('([Yy]es|[Nn]o|[Tt]rue|[Ff]alse|[Oo]n|[Oo]ff)')
# Helper definitions
kstr= quotedString.setParseAction(removeQuotes) ^ \
dval ^ ival ^ lval ^ Word(prtable)
name = Word(alphas+"_",alphanums+"_")
vec=array_begin+delimitedList(dval ^ ival ^ lval ^ Word(prtable) ^ \
Literal("\n").suppress() ^ \
quotedString.setParseAction(removeQuotes))+array_end
sect=name+sect_begin
tag_sect=name+Group(tag_begin+name+tag_end)+sect_begin
# Grammar
keyword = name + eql + kstr
vector = name + eql + vec
data=Combine(dmark+name)+SkipTo(end_data)+end_data
section=Forward()
sect_def=(sect | tag_sect ) #| vec_sect)
input=section | data | vector | keyword
section << sect_def+ZeroOrMore(input) + sect_end
# Parsing actions
ival.setParseAction(self.conv_ival)
dval.setParseAction(self.conv_dval)
lval.setParseAction(self.conv_lval)
keyword.setParseAction(self.store_key)
vector.setParseAction(self.store_vector)
data.setParseAction(self.store_data)
sect.setParseAction(self.add_sect)
tag_sect.setParseAction(self.add_sect)
sect_end.setParseAction(self.pop_sect)
bnf=ZeroOrMore(input) + StringEnd().setFailAction(parse_error)
bnf.ignore(pythonStyleComment)
return bnf
示例7: gramma
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def gramma():
## Tokens
point = Literal('.')
prefix_op = Literal('.')
choice_op = Literal('+')
parallel = Literal("||") | Literal("<>")
#ident = Word(alphas, alphanums+'_')
ratename = Word(alphas.lower(),alphanums+"_")
lpar = Literal('(').suppress()
rpar = Literal(')').suppress()
lsqpar = Literal('[').suppress()
rsqpar = Literal(']').suppress()
define = Literal('=')
semicol = Literal(';').suppress()
col = Literal(',').suppress()
number = Word(nums)
integer = number
floatnumber = Combine( integer + Optional( point + Optional(number)))
passiverate = Word('infty') | Word('T')
internalrate = Word('tau')
pound = Literal('#').suppress()
percent = Literal('%').suppress()
peparate = (ratename | floatnumber | internalrate | passiverate).setParseAction(_check_var)
peparate_indef = floatnumber | internalrate | passiverate
sync = Word('<').suppress() + ratename + ZeroOrMore(col + ratename) + Word('>').suppress()
coop_op = (parallel | sync).setParseAction(_create_sync_set)
activity = (ratename + col + peparate).setParseAction(_create_activity)
procdef = (Word(alphas.upper(), alphanums+"_") + Optional(lsqpar + peparate_indef + rsqpar)).setParseAction(_create_procdef)
## RATES Definitions
ratedef = (Optional(percent)+ratename + define + peparate_indef).setParseAction(assign_var) + semicol
prefix = Forward()
choice = Forward()
coop = Forward()
process = ( activity
| procdef
| lpar + coop + rpar
).setParseAction(_create_process)
prefix << (process + ZeroOrMore(prefix_op + prefix)).setParseAction( _create_prefix)
choice << (prefix + ZeroOrMore(choice_op + choice)).setParseAction(_create_choice)
coop << (choice + ZeroOrMore(coop_op + coop)).setParseAction(_create_coop)
rmdef = (Optional(pound) + procdef + define + coop + semicol).setParseAction(_create_definition)
system_eq = Optional(pound) + coop
pepa = ZeroOrMore(ratedef) + ZeroOrMore(rmdef) + system_eq.setParseAction(_create_system_equation)
pepacomment = '//' + restOfLine
pepa.ignore(pepacomment)
return pepa
示例8: getkw_bnf
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def getkw_bnf(self):
sect_begin = Literal("{").suppress()
sect_end = Literal("}").suppress()
array_begin = Literal("[").suppress()
array_end = Literal("]").suppress()
arg_begin = Literal("(").suppress()
arg_end = Literal(")").suppress()
eql = Literal("=").suppress()
dmark = Literal('$').suppress()
end_data=Literal('$end').suppress()
prtable = alphanums+r'!$%&*+-./<>[email protected]^_|~'
# Helper definitions
kstr=Word(prtable) ^ quotedString.setParseAction(removeQuotes)
name = Word(alphas+"_",alphanums+"_")
vec=array_begin+delimitedList(Word(prtable) ^ \
Literal("\n").suppress() ^ \
quotedString.setParseAction(removeQuotes))+array_end
sect=name+sect_begin
key_sect=name+Group(arg_begin+kstr+arg_end)+sect_begin
vec_sect=name+Group(arg_begin+vec+ arg_end)+sect_begin
# Grammar
keyword = name + eql + kstr
vector = name + eql + vec
data=Combine(dmark+name)+SkipTo(end_data)+end_data
section=Forward()
sect_def=(sect | key_sect | vec_sect)
input=section | data | vector | keyword
section << sect_def+ZeroOrMore(input) + sect_end
# Parsing actions
keyword.setParseAction(self.store_key)
vector.setParseAction(self.store_vector)
data.setParseAction(self.store_data)
sect.setParseAction(self.add_sect)
key_sect.setParseAction(self.add_sect)
vec_sect.setParseAction(self.add_vecsect)
sect_end.setParseAction(self.pop_sect)
bnf=ZeroOrMore(input) + StringEnd().setFailAction(parse_error)
bnf.ignore(pythonStyleComment)
return bnf
示例9: _grammar
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def _grammar(self):
ident = Word(alphanums + ".")
semi = Literal(";").suppress()
# lrb = Literal("(").suppress()
# rrb = Literal(")").suppress()
lcb = Literal("{").suppress()
rcb = Literal("}").suppress()
Value = SkipTo(semi)
KeyValue = Dict(Group(ident + Value + semi))
Dictionary = Forward()
Block = lcb + ZeroOrMore(Dictionary | KeyValue) + rcb
Dictionary << Dict(Group(ident + Block))
ParameterFile = ZeroOrMore(Dictionary | KeyValue)
ParameterFile.ignore(cStyleComment)
ParameterFile.ignore(cppStyleComment)
return ParameterFile
示例10: find_procedures_headers
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def find_procedures_headers(self):
CREATE = CaselessKeyword("CREATE")
OR = CaselessKeyword("OR")
REPLACE = CaselessKeyword("REPLACE")
FUNCTION = CaselessKeyword("FUNCTION")
IN = CaselessKeyword("IN")
OUT = CaselessKeyword("OUT")
INOUT = CaselessKeyword("INOUT")
VARIADIC = CaselessKeyword("VARIADIC")
NAME = (Word(alphas, alphanums + "_."))("name")
ALIAS = Word(alphas, alphanums + "_")
TYPE = (
Word(alphas, alphanums + "[]_. ", ) + Suppress(Optional(Literal("(") + Word(nums) + Literal(")")))
)
PRM = (
(Optional(IN | OUT | INOUT | VARIADIC | (OUT + VARIADIC)) +
Optional(ALIAS) +
TYPE) | TYPE
).setParseAction(lambda res: " ".join([w.strip() for w in res]))
COMMENT = "--" + restOfLine
COMMA = Suppress(",")
PARAMS = ZeroOrMore(
PRM +
Optional(COMMA)
)("input")
PARAMS.ignore(COMMENT)
HEADER = (
CREATE + Optional(OR) + Optional(REPLACE) + FUNCTION + NAME +
Suppress("(") + PARAMS + Suppress(")")
).setParseAction(lambda res: {"name": res.name, "input": res.input})
parse_header = OneOrMore(HEADER | Suppress(SkipTo(HEADER)))
parse_header.ignore(COMMENT)
parse_header.ignore(cStyleComment)
try:
headers = parse_header.parseString(self._sql)
except Exception as error:
print self._fpath
raise error
return headers
示例11: loadSource
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
class PulseProgram:
""" Encapsulates a PulseProgrammer Program
loadSource( filename ) loads the contents of the file
The code is compiled in the following steps
parse() generates self.code
toBytecode() generates self.bytecode
toBinary() generates self.binarycode
the procedure updateVariables( dictionary ) updates variable values in the bytecode
"""
def __init__(self):
self.variabledict = collections.OrderedDict() # keeps information on all variables to easily change them later
self.labeldict = dict() # keep information on all labels
self.source = collections.OrderedDict() # dictionary of source code files (stored as strings)
self.code = [] # this is a list of lines
self.bytecode = [] # list of op, argument tuples
self.binarycode = bytearray() # binarycode to be uploaded
self._exitcodes = dict() # generate a reverse dictionary of variables of type exitcode
self.constDict = dict()
class Board:
channelLimit = 1
halfClockLimit = 500000000
self.adIndexList = [(x, 0) for x in range(6) ]
self.adBoards = [ Board() ]*6
self.timestep = Q(20.0, 'ns')
self.initBNF()
def initBNF(self):
constdecl = (CONST + NAME + VALUE).setParseAction(self.const_action)
vardecl = (VAR + NAME + VALUE + Optional( COMMA + Regex("[^#\n]*")) ).setParseAction(self.var_action)
insertdecl = (INSERT + dblQuotedString + LineEnd().suppress()).setParseAction(self.insert_action)
LABEL = IDENTIFIER + COLON
COMMANDEXP = (IDENTIFIER.setWhitespaceChars(" \t") + Regex("[^#\n]*").setWhitespaceChars(" \t") + LineEnd().suppress() )
COMMAND = COMMANDEXP.setParseAction(self.command_action)
LABELEDCOMMAND = (LABEL + COMMANDEXP ).setParseAction(self.label_command_action)
decl = constdecl | vardecl | insertdecl | LABELEDCOMMAND | COMMAND
self.program = ZeroOrMore(decl)
self.program.ignore(pythonStyleComment)
def const_action( self, text, loc, arg ):
""" add the const to the self.constDict dictionary
"""
logger = logging.getLogger(__name__)
logger.debug("{0}:{1} const {2}".format(self.currentFile, lineno(loc, text), arg))
label, value = arg
if label in self.constDict:
logger.error( "Error parsing const in file '{0}': attempted to redefine'{1}' to '{2}' from '{3}'".format(self.currentFile, label, value, self.constDict[label]) )
raise ppexception("Redefining variable", self.currentFile, lineno, label)
else:
self.constDict[label] = int(value)
def var_action( self, text, loc, arg):
print("var_action", self.currentFile, lineno(loc, text), arg[0:2], arg[2].split(",") if len(arg)>2 else "")
""" add a variable to the self.variablesdict
"""
logger = logging.getLogger(__name__)
logger.debug( "{0}:{1} Variable {2}".format( self.currentFile, lineno(loc, text), arg ) )
var = Variable()
label, data = arg[:2]
fields = arg[2].split(",") if len(arg)>2 else [None]*3
fields += [None]*(3-len(fields))
var.type, unit, var.encoding = [ x if x is None or '' else x.strip() for x in fields ]
var.name = label
var.origin = self.currentFile
var.enabled = True
if var.encoding not in encodings:
raise ppexception("unknown encoding {0} in file '{1}':{2}".format(var.encoding, self.currentFile, lineno(loc, text)), self.currentFile, lineno, var.encoding)
try:
data = str(eval(data, globals(), self.defines))
except Exception:
logger.exception( "Evaluation error in file '{0}' on line: '{1}'".format(self.currentFile, data) )
if unit is not None:
var.value = Q(float(data), unit)
data = self.convertParameter( var.value, var.encoding )
else:
var.value = Q(float(data))
data = int(round(float(data)))
if label in self.defines:
logger.error( "Error in file '%s': attempted to reassign '%s' to '%s' (from prev. value of '%s') in a var statement." %(self.currentFile, label, data, self.defines[label]) )
raise ppexception("variable redifinition", self.currentFile, lineno, label)
else:
self.defines[label] = label # add the variable to the dictionary of definitions to prevent identifiers and variables from having the same name
# however, we do not want it replaced with a number but keep the name for the last stage of compilation
pass
var.data = data
self.variabledict.update({ label: var})
if var.type == "exitcode":
self._exitcodes[data & 0x0000ffff] = var
def command_action( self, text, loc, arg):
print("command_action", self.currentFile, lineno(loc, text), arg[0:1], arg[1].split(",") if len(arg)>1 else "")
#.........这里部分代码省略.........
示例12: get_parser
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
def get_parser(self):
declaration = Forward()
keyword = (
Keyword("enum") |
Keyword("case") |
Keyword("struct") |
Keyword("default") |
Keyword("switch") |
Keyword("union") |
Keyword("const") |
Keyword("unsigned") |
Keyword("int") |
Keyword("hyper") |
Keyword("float") |
Keyword("double") |
Keyword("bool") |
Keyword("typedef") |
Keyword("opaque") |
Keyword("string") |
Keyword("void") |
Keyword("program") |
Keyword("version")
)
identifier = NotAny(keyword) + Word(alphas + alphas.upper(), alphanums + alphanums.upper() + "_", asKeyword=True)
constant = Combine(Optional("-") + Word(nums))
constant.setParseAction(lambda s,l,t: [int(t[0])])
value = constant | identifier
enum_body = Literal("{").suppress() + identifier + Literal("=").suppress() + value + ZeroOrMore(Literal(",").suppress() + identifier + Literal("=").suppress() + value) + Literal("}").suppress()
enum_type_spec = Literal("enum").suppress() + enum_body
enum_body.setParseAction(self.parse_enum)
struct_body = Literal("{").suppress() + OneOrMore(declaration + Literal(";").suppress()) + Literal("}").suppress()
struct_type_spec = Literal("struct").suppress() + struct_body
struct_body.setParseAction(self.parse_struct)
case_stmt = Literal("case").suppress() + value + Literal(":").suppress() + declaration + Literal(";").suppress()
default_stmt = Literal("default") + Literal(":").suppress() + declaration + Literal(";").suppress()
union_body = Literal("switch").suppress() + Literal("(").suppress() + declaration + Literal(")").suppress() + Literal("{").suppress() + Group(OneOrMore(Group(case_stmt)) + Optional(Group(default_stmt))) + Literal("}").suppress()
union_type_spec = Literal("union").suppress() + union_body
union_body.setParseAction(self.parse_union)
constant_def = Literal("const").suppress() + identifier + Literal("=").suppress() + constant + Literal(";").suppress()
constant_def.setParseAction(self.parse_const)
type_spec = (
(Optional(Literal("unsigned")) + Literal("int")).setParseAction(self.parse_builtin) |
(Optional(Literal("unsigned")) + Literal("hyper")).setParseAction(self.parse_builtin) |
Literal("float").setParseAction(self.parse_builtin) |
Literal("double").setParseAction(self.parse_builtin) |
Literal("bool").setParseAction(self.parse_builtin) |
enum_type_spec |
struct_type_spec |
union_type_spec |
identifier
)
proc_return = Literal("void") | type_spec
procedure_def = proc_return + identifier + Literal("(").suppress() + (Literal("void") | type_spec) + ZeroOrMore(Literal(",").suppress() + type_spec) + Literal(")").suppress() + Literal("=").suppress() + constant + Literal(";").suppress()
procedure_def.setParseAction(self.parse_procedure_def)
version_def = Literal("version").suppress() + identifier + Literal("{").suppress() + OneOrMore(procedure_def) + Literal("}").suppress() + Literal("=").suppress() + constant + Literal(";").suppress()
version_def.setParseAction(self.parse_version_def)
program_body = Literal("{").suppress() + Group(OneOrMore(version_def)) + Literal("}").suppress()
type_def = (
(Literal("typedef") + declaration + Literal(";")) |
(Literal("enum") + identifier + enum_body + Literal(";")) |
(Literal("struct") + identifier + struct_body + Literal(";")) |
(Literal("union") + identifier + union_body + Literal(";")) |
(Literal("program") + identifier + program_body + Literal("=").suppress() + constant + Literal(";"))
)
type_def.setParseAction(self.parse_type_def)
declaration << (
(type_spec + identifier + Literal("[") + value + Literal("]")) |
(type_spec + identifier + Literal("<") + value + Literal(">")) |
(type_spec + identifier) |
(Literal("opaque") + identifier + Literal("[") + value + Literal("]")) |
(Literal("opaque") + identifier + Literal("<") + value + Literal(">")) |
(Literal("string") + identifier + Literal("<") + value + Literal(">")) |
(type_spec + Literal("*") + identifier) |
Literal("void")
)
declaration.setParseAction(self.parse_decl)
definition = type_def | constant_def
specification = ZeroOrMore(definition)
comment = (Literal("#") + restOfLine).suppress()
specification.ignore(comment)
return specification
示例13: SPICE_BNF
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
#.........这里部分代码省略.........
identifier ^ integer ^ arraySizeSpecImage ^ arraySizeSpecBytes ^ arraySizeSpecCString, default=""
)
+ rbrack
)
variableDef = Group(
typeSpec
+ Optional("*", default=None)
+ identifier
+ Optional(arraySizeSpec, default=None)
+ attributes
- semi
).setParseAction(parseVariableDef)
switchCase = Group(
Group(
OneOrMore(
default_.setParseAction(replaceWith(None)) + colon
| Group(case_.suppress() + Optional("!", default="") + identifier) + colon
)
)
+ variableDef
).setParseAction(lambda toks: ptypes.SwitchCase(toks[0][0], toks[0][1]))
switchBody = Group(
switch_
+ lparen
+ delimitedList(identifier, delim=".", combine=True)
+ rparen
+ lbrace
+ Group(OneOrMore(switchCase))
+ rbrace
+ identifier
+ attributes
- semi
).setParseAction(lambda toks: ptypes.Switch(toks[0][1], toks[0][2], toks[0][3], toks[0][4]))
messageBody = structBody = Group(lbrace + ZeroOrMore(variableDef | switchBody) + rbrace)
structSpec = Group(struct_ + identifier + structBody + attributes).setParseAction(
lambda toks: ptypes.StructType(toks[0][1], toks[0][2], toks[0][3])
)
# have to use longest match for type, in case a user-defined type name starts with a keyword type, like "channel_type"
typeSpec << (
structSpec ^ int8_ ^ uint8_ ^ int16_ ^ uint16_ ^ int32_ ^ uint32_ ^ int64_ ^ uint64_ ^ typename
).setName("type")
flagsBody = enumBody = Group(
lbrace + delimitedList(Group(enumname + Optional(equals + integer))) + Optional(comma) + rbrace
)
messageSpec = (
Group(message_ + messageBody + attributes).setParseAction(
lambda toks: ptypes.MessageType(None, toks[0][1], toks[0][2])
)
| typename
)
channelParent = Optional(colon + typename, default=None)
channelMessage = Group(
messageSpec + identifier + Optional(equals + integer, default=None) + semi
).setParseAction(lambda toks: ptypes.ChannelMember(toks[0][1], toks[0][0], toks[0][2]))
channelBody = channelParent + Group(
lbrace + ZeroOrMore(server_ + colon | client_ + colon | channelMessage) + rbrace
)
enum_ = enum32_ | enum16_ | enum8_
flags_ = flags32_ | flags16_ | flags8_
enumDef = Group(enum_ + identifier + enumBody + attributes - semi).setParseAction(
lambda toks: ptypes.EnumType(toks[0][0], toks[0][1], toks[0][2], toks[0][3])
)
flagsDef = Group(flags_ + identifier + flagsBody + attributes - semi).setParseAction(
lambda toks: ptypes.FlagsType(toks[0][0], toks[0][1], toks[0][2], toks[0][3])
)
messageDef = Group(message_ + identifier + messageBody + attributes - semi).setParseAction(
lambda toks: ptypes.MessageType(toks[0][1], toks[0][2], toks[0][3])
)
channelDef = Group(channel_ + identifier + channelBody + attributes - semi).setParseAction(
lambda toks: ptypes.ChannelType(toks[0][1], toks[0][2], toks[0][3], toks[0][4])
)
structDef = Group(struct_ + identifier + structBody + attributes - semi).setParseAction(
lambda toks: ptypes.StructType(toks[0][1], toks[0][2], toks[0][3])
)
typedefDef = Group(typedef_ + identifier + typeSpec + attributes - semi).setParseAction(
lambda toks: ptypes.TypeAlias(toks[0][1], toks[0][2], toks[0][3])
)
definitions = typedefDef | structDef | enumDef | flagsDef | messageDef | channelDef
protocolChannel = Group(typename + identifier + Optional(equals + integer, default=None) + semi).setParseAction(
lambda toks: ptypes.ProtocolMember(toks[0][1], toks[0][0], toks[0][2])
)
protocolDef = Group(
protocol_ + identifier + Group(lbrace + ZeroOrMore(protocolChannel) + rbrace) + semi
).setParseAction(lambda toks: ptypes.ProtocolType(toks[0][1], toks[0][2]))
bnf = ZeroOrMore(definitions) + protocolDef + StringEnd()
singleLineComment = "//" + restOfLine
bnf.ignore(singleLineComment)
bnf.ignore(cStyleComment)
return bnf
示例14: Group
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
release_site_definition = Group(identifier.setResultsName('name') + release_site_ + lbrace + dictOf(key,value).setResultsName('entries') + rbrace)
object_definition = Group(identifier.setResultsName('compartmentName') + Suppress(object_) + (bracketidentifier | identifier) + (nestedExpr('{', '}',content=statement)).setResultsName('compartmentOptions'))
hashed_initialization_section = Group(hashsymbol + Suppress(instantiate_) + identifier.setResultsName('name') +
identifier.setResultsName('type') + lbrace + Group(ZeroOrMore(release_site_definition | object_definition)).setResultsName('entries') + rbrace )
other_sections = section_enclosure_
#statement = Group(identifier + equal + (quotedString | OneOrMore(mathElements))) + Suppress(LineEnd() | StringEnd())
grammar = ZeroOrMore(Suppress(other_sections) | Suppress(statement) | hashed_system_constants.setResultsName('systemConstants')
| hashed_molecule_section.setResultsName('molecules') | hashed_reaction_section.setResultsName('reactions')
| hashed_observable_section.setResultsName('observables')
| hashed_initialization_section.setResultsName('initialization')
| hashed_function_section.setResultsName('math_functions')
#| Suppress(hashed_section)
)
nonhashedgrammar = ZeroOrMore(Suppress(statement) | Suppress(hashed_section) | Dict(other_sections))
statementGrammar = ZeroOrMore(statement | Suppress(other_sections) | Suppress(hashed_section))
singleLineComment = "//" + restOfLine
grammar.ignore(singleLineComment)
grammar.ignore(cppStyleComment)
nonhashedgrammar.ignore(singleLineComment)
nonhashedgrammar.ignore(cppStyleComment)
statementGrammar.ignore(singleLineComment)
statementGrammar.ignore(cppStyleComment)
示例15: Optional
# 需要导入模块: from pyparsing import ZeroOrMore [as 别名]
# 或者: from pyparsing.ZeroOrMore import ignore [as 别名]
selectStatement << ( selectToken +
columnNameList.setResultsName("columns") +
fromToken +
identifier.setResultsName("tablename") +
Optional(whereClause) +
Optional(orderByClause) +
Optional(limitClause) )
BQLStatement = (selectStatement | createBtableStatement) + Optional(';')
BQL = ZeroOrMore(BQLStatement)
## allows comments
dashComment = "--" + restOfLine
BQL.ignore(dashComment)
def test( str ):
print str,"->"
try:
tokens = BQL.parseString( str )
print "tokens = ", tokens
print "tokens.tablename =", tokens.tablename
print "tokens.filename =", tokens.filename
#print "tokens.where =", tokens.where
except ParseException, err:
print " "*err.loc + "^\n" + err.msg
print err
print