本文整理汇总了Python中pyparsing.OneOrMore.ignore方法的典型用法代码示例。如果您正苦于以下问题:Python OneOrMore.ignore方法的具体用法?Python OneOrMore.ignore怎么用?Python OneOrMore.ignore使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.OneOrMore
的用法示例。
在下文中一共展示了OneOrMore.ignore方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ifParser
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def ifParser():
comma = Literal(",").suppress()
hash = Literal("#").suppress()
equal = Literal("=").suppress()
# Rules and labels
rulename = Word (alphanums + "_")
rulecategory = oneOf("Protocol_Rules Invariant_Rules Decomposition_Rules Intruder_Rules Init Goal")
label = hash + Literal("lb") + equal + rulename + comma + Literal("type") + equal + rulecategory
labeledrule = Group(label) + Group(ruleParser())
def labeledruleAction(s,l,t):
if t[0][3] == "Protocol_Rules":
print "-----------------"
print "- Detected rule -"
print "-----------------"
print t[0]
print t[1]
print
labeledrule.setParseAction(labeledruleAction)
# A complete file
parser = OneOrMore(labeledrule)
parser.ignore("##" + restOfLine)
return parser
示例2: INTERFACECL_BNF
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def INTERFACECL_BNF():
"""\
pyparser grammar for the yapocis interface specification. Inspired by an IDL parser by Paul McGuire, shipped as a demo with pyparser.
"""
global bnf
if not bnf:
# punctuation
lbrace = Literal("{")
rbrace = Literal("}")
lparen = Literal("(")
rparen = Literal(")")
dot = Literal(".")
star = Literal("*")
semi = Literal(";")
# keywords
boolean_ = Keyword("boolean")
char_ = Keyword("char")
complex64_ = Keyword("complex64")
float_ = Keyword("float")
float32_ = Keyword("float32")
inout_ = Keyword("inout")
interface_ = Keyword("interface")
in_ = Keyword("in")
int_ = Keyword("int")
int16_ = Keyword("int16")
int32_ = Keyword("int32")
kernel_ = Keyword("kernel")
out_ = Keyword("out")
short_ = Keyword("short")
uint16_ = Keyword("uint16")
uint32_ = Keyword("uint32")
void_ = Keyword("void")
# Special keywords
alias_ = Keyword("alias")
as_ = Keyword("as")
outlike_ = Keyword("outlike")
resident_ = Keyword("resident")
widthof_ = Keyword("widthof")
heightof_ = Keyword("heightof")
sizeof_ = Keyword("sizeof")
identifier = Word( alphas, alphanums + "_" )
typeName = (boolean_ ^ char_ ^ int16_ ^ int32_ ^ float32_ ^ complex64_ ^ uint16_ ^ uint32_ ^ int_ ^ float_ ^ short_)
bufferHints = (inout_ | in_ | out_ | outlike_ | resident_ | widthof_ | heightof_ | sizeof_)
paramlist = delimitedList( Group(bufferHints + Optional(typeName) + Optional(star) + identifier))
interfaceItem = ((kernel_^void_^alias_^typeName) + identifier + Optional(Group(as_+identifier)) + lparen + Optional(paramlist) + rparen + semi)
interfaceDef = Group(interface_ + identifier + lbrace + ZeroOrMore(interfaceItem) + rbrace + semi)
moduleItem = interfaceDef
bnf = OneOrMore( moduleItem )
singleLineComment = "//" + restOfLine
bnf.ignore( singleLineComment )
bnf.ignore( cStyleComment )
return bnf
示例3: _build
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def _build():
"""Encapsulate so the variables don't leak out."""
# Basic punctuation
colon = Literal(':').suppress()
hashmark = Literal('#').suppress()
comment = (hashmark + restOfLine).suppress()
# Enforce Python-style naming conventions
command_name = Word(srange("[A-Z]"), srange("[a-zA-Z0-9]")) # StudlyCaps
field_name = Word(srange("[a-z_]"), srange("[a-z0-9_]")) # lower_underscore
# Put it all together
fields = Dict(OneOrMore(Group(field_name + colon + restOfLine)))
fields = nestedExpr(opener="{", closer="}", content=fields)
command = Group(command_name + fields)
# Configure the parser
tml_parser = OneOrMore(command) + stringEnd
tml_parser.ignore(comment)
return tml_parser
示例4: _buildParser
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def _buildParser():
from pyparsing import Word, Group, Optional, Literal, delimitedList, OneOrMore, restOfLine, Suppress
upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lower = 'abcdefghijklmnopqrstuvwxyz'
alpha = '_' + upper + lower
alpha_num = alpha + '0123456789'
consId = Word(upper, alpha_num)
typeId = Word(lower + alpha_num)
id = Word(upper + lower, alpha_num)
field = Group(typeId + Optional(Literal("?") | Literal("*"), default="") + Optional(id, default=""))
cons = Group(consId + Group(Optional(Suppress("(") + delimitedList(field, delim=",") + Suppress(")"))))
prod = Group(typeId + Suppress("=") + Group(delimitedList(cons, delim="|")))
spec = OneOrMore(prod)
comment = '--' + restOfLine
spec.ignore(comment)
return spec
示例5: parse
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def parse(self, file_path):
string = Word(printables, excludeChars="|?,:").setParseAction(self._remove_dots)
comment = "|" + restOfLine
delimiter = Suppress(".") | LineEnd()
enum = (Empty().copy().setParseAction(lambda t: self.ENUM) +
Group(delimitedList(string))("next_arg").setParseAction(lambda t: {'values': t.next_arg.asList()}))
discrete = Literal("discrete") + Suppress(Word(nums))
attr_type = (Literal("continuous") | Literal("ignore") | discrete | enum)("type")
attribute = string("name") + Suppress(":") + attr_type
cls = string("cls")
cls.addParseAction(self._get_class)
classes = delimitedList(cls)
entry = attribute | classes
attribute.setParseAction(self._create_attribute)
parser = OneOrMore(entry + Optional(delimiter))
parser.ignore(comment)
try:
parser.parseFile(file_path, parseAll=True)
except ParseException as e:
raise HeaderError(FileType.DATA, e.lineno, e.col, e.line, e)
示例6: find_procedures_headers
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore 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
示例7: dict_from_key_values_pyparsing
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def dict_from_key_values_pyparsing(file, lowercase_keys=False):
"""
>>> filename = os.path.dirname(__file__)
>>> filename = os.path.join(filename, "data/iradio-initial.pls")
>>> with open(filename, "rt", encoding="utf8") as fh:
... d = dict_from_key_values_pyparsing(fh)
>>> for key in sorted(d.keys())[-4:]:
... print("{0}: {1}".format(key, d[key]))
title6: Virgin Xtreme (Broadband)
title7: Virgin Classic Rock (Modem)
title8: Virgin Classic Rock (Broadband)
title9: CBC Radio One (Canada)
>>> d["file13"]
'http://media.hiof.no/streams/m3u/nrk-petre-172.ogg.m3u'
>>> d["genre15"]
''
>>> len(d.keys())
54
"""
def accumulate(tokens):
key, value = tokens
key = key.lower() if lowercase_keys else key
key_values[key] = value
key_values = {}
left_bracket, right_bracket, equals = map(Suppress, "[]=")
ini_header = left_bracket + CharsNotIn("]") + right_bracket
key_value = Word(alphanums) + equals + restOfLine
key_value.setParseAction(accumulate)
comment = "#" + restOfLine
parser = OneOrMore(ini_header | key_value)
parser.ignore(comment)
try:
parser.parseFile(file)
except ParseException as err:
print("parse error: {0}".format(err))
return {}
return key_values
示例8: ifParser
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def ifParser():
comma = Literal(",")
hash = Literal("#")
equal = Literal("=")
# Rules and labels
rulename = Word(alphanums + "_")
rulecategory = oneOf("Protocol_Rules Invariant_Rules Decomposition_Rules Intruder_Rules Init Goal")
label = hash + Literal("lb") + equal + rulename + comma + Literal("type") + equal + rulecategory
label.setParseAction(lambda s, l, t: [If.Label(t[3], t[7])])
labeledrule = label + ruleParser()
def labeledruleAction(s, l, t):
rule = t[1]
rule.setLabel(t[0])
return [rule]
labeledrule.setParseAction(labeledruleAction)
# A complete file
parser = OneOrMore(labeledrule)
parser.ignore("##" + restOfLine)
return parser
示例9: graph_definition
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
#.........这里部分代码省略.........
# keywords
strict_ = CaselessLiteral("strict")
graph_ = CaselessLiteral("graph")
digraph_ = CaselessLiteral("digraph")
subgraph_ = CaselessLiteral("subgraph")
node_ = CaselessLiteral("node")
edge_ = CaselessLiteral("edge")
# token definitions
identifier = Word(alphanums + "_." ).setName("identifier")
double_quoted_string = QuotedString('"', multiline=True, unquoteResults=False) # dblQuotedString
_noncomma = "".join([c for c in printables if c != ","])
alphastring_ = OneOrMore(CharsNotIn(_noncomma + ' '))
def parse_html(s, loc, toks):
return '<%s>' % ''.join(toks[0])
opener = '<'
closer = '>'
html_text = nestedExpr( opener, closer,
( CharsNotIn( opener + closer ) )
).setParseAction(parse_html).leaveWhitespace()
ID = ( identifier | html_text |
double_quoted_string | #.setParseAction(strip_quotes) |
alphastring_ ).setName("ID")
float_number = Combine(Optional(minus) +
OneOrMore(Word(nums + "."))).setName("float_number")
righthand_id = (float_number | ID ).setName("righthand_id")
port_angle = (at + ID).setName("port_angle")
port_location = (OneOrMore(Group(colon + ID)) |
Group(colon + lparen + ID + comma + ID + rparen)).setName("port_location")
port = (Group(port_location + Optional(port_angle)) |
Group(port_angle + Optional(port_location))).setName("port")
node_id = (ID + Optional(port))
a_list = OneOrMore(ID + Optional(equals + righthand_id) +
Optional(comma.suppress())).setName("a_list")
attr_list = OneOrMore(lbrack.suppress() + Optional(a_list) +
rbrack.suppress()).setName("attr_list")
attr_stmt = (Group(graph_ | node_ | edge_) + attr_list).setName("attr_stmt")
edgeop = (Literal("--") | Literal("->")).setName("edgeop")
stmt_list = Forward()
graph_stmt = Group(lbrace.suppress() + Optional(stmt_list) +
rbrace.suppress() + Optional(semi.suppress()) ).setName("graph_stmt")
edge_point = Forward()
edgeRHS = OneOrMore(edgeop + edge_point)
edge_stmt = edge_point + edgeRHS + Optional(attr_list)
subgraph = Group(subgraph_ + Optional(ID) + graph_stmt).setName("subgraph")
edge_point << Group(subgraph | graph_stmt | node_id ).setName('edge_point')
node_stmt = (node_id + Optional(attr_list) + Optional(semi.suppress())).setName("node_stmt")
assignment = (ID + equals + righthand_id).setName("assignment")
stmt = (assignment | edge_stmt | attr_stmt | subgraph | graph_stmt | node_stmt).setName("stmt")
stmt_list << OneOrMore(stmt + Optional(semi.suppress()))
graphparser = OneOrMore( (Optional(strict_) + Group((graph_ | digraph_)) +
Optional(ID) + graph_stmt).setResultsName("graph") )
singleLineComment = Group("//" + restOfLine) | Group("#" + restOfLine)
# actions
graphparser.ignore(singleLineComment)
graphparser.ignore(cStyleComment)
assignment.setParseAction(push_attr_list)
a_list.setParseAction(push_attr_list)
edge_stmt.setParseAction(push_edge_stmt)
node_stmt.setParseAction(push_node_stmt)
attr_stmt.setParseAction(push_default_stmt)
subgraph.setParseAction(push_subgraph_stmt)
graph_stmt.setParseAction(push_graph_stmt)
graphparser.setParseAction(push_top_graph_stmt)
return graphparser
示例10: NumberParser
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
#.........这里部分代码省略.........
("octodecillion", int(1e57)),
("novemdecillion", int(1e60)),
("vigintillion", int(1e63)),
]
self.units = Or(
[convert_to_literal(s, v) for s, v in self.defined_units]
)
self.tens = Or(
[convert_to_literal(s, v) for s, v in self.defined_tens]
)
self.hundreds = convert_to_literal("hundred", 100)
self.majors = Or(
[convert_to_literal(s, v) for s, v in self.defined_majors]
)
self.word_product = lambda t: functools.reduce(mul, t)
self.word_sum = lambda t: sum(t)
self.number_partial = (
(
(
(
self.units + Optional(self.hundreds)
).setParseAction(self.word_product) + Optional(self.tens)
).setParseAction(self.word_sum) ^ self.tens
) + Optional(self.units)).setParseAction(self.word_sum)
self.number_words = OneOrMore(
(self.number_partial +
Optional(self.majors)).setParseAction(self.word_product)
).setParseAction(self.word_sum) + StringEnd()
self.number_words.ignore(CaselessLiteral("-"))
self.number_words.ignore(CaselessLiteral("and"))
self.roman_numerals = [
['M', 1000],
['CM', 900],
['D', 500],
['CD', 400],
['C', 100],
['XC', 90],
['L', 50],
['XL', 40],
['X', 10],
['IX', 9],
['V', 5],
['IV', 4],
['I', 1]
]
@classmethod
def is_float(cls, data):
"""Checks to see if the value is a float"""
try:
return True, float(data)
except ValueError:
return False, 0
@classmethod
def is_integer(cls, data):
"""Checks to see if the value is an integer"""
try:
return True, int(data)
except ValueError:
示例11: input_from_blif
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
def input_from_blif(blif, block=None, merge_io_vectors=True):
""" Read an open blif file or string as input, updating the block appropriately
Assumes the blif has been flattened and their is only a single module.
Assumes that there is only one single shared clock and reset
Assumes that output is generated by Yosys with formals in a particular order
Ignores reset signal (which it assumes is input only to the flip flops)
"""
import pyparsing
import six
from pyparsing import (Word, Literal, OneOrMore, ZeroOrMore,
Suppress, Group, Keyword)
block = working_block(block)
try:
blif_string = blif.read()
except AttributeError:
if isinstance(blif, six.string_types):
blif_string = blif
else:
raise PyrtlError('input_blif expecting either open file or string')
def SKeyword(x):
return Suppress(Keyword(x))
def SLiteral(x):
return Suppress(Literal(x))
def twire(x):
""" find or make wire named x and return it """
s = block.get_wirevector_by_name(x)
if s is None:
s = WireVector(bitwidth=1, name=x)
return s
# Begin BLIF language definition
signal_start = pyparsing.alphas + '$:[]_<>\\\/'
signal_middle = pyparsing.alphas + pyparsing.nums + '$:[]_<>\\\/.'
signal_id = Word(signal_start, signal_middle)
header = SKeyword('.model') + signal_id('model_name')
input_list = Group(SKeyword('.inputs') + OneOrMore(signal_id))('input_list')
output_list = Group(SKeyword('.outputs') + OneOrMore(signal_id))('output_list')
cover_atom = Word('01-')
cover_list = Group(ZeroOrMore(cover_atom))('cover_list')
namesignal_list = Group(OneOrMore(signal_id))('namesignal_list')
name_def = Group(SKeyword('.names') + namesignal_list + cover_list)('name_def')
# asynchronous Flip-flop
dffas_formal = (SLiteral('C=') + signal_id('C') +
SLiteral('R=') + signal_id('R') +
SLiteral('D=') + signal_id('D') +
SLiteral('Q=') + signal_id('Q'))
dffas_keyword = SKeyword('$_DFF_PN0_') | SKeyword('$_DFF_PP0_')
dffas_def = Group(SKeyword('.subckt') + dffas_keyword + dffas_formal)('dffas_def')
# synchronous Flip-flop
dffs_def = Group(SKeyword('.latch') +
signal_id('D') +
signal_id('Q') +
SLiteral('re') +
signal_id('C'))('dffs_def')
command_def = name_def | dffas_def | dffs_def
command_list = Group(OneOrMore(command_def))('command_list')
footer = SKeyword('.end')
model_def = Group(header + input_list + output_list + command_list + footer)
model_list = OneOrMore(model_def)
parser = model_list.ignore(pyparsing.pythonStyleComment)
# Begin actually reading and parsing the BLIF file
result = parser.parseString(blif_string, parseAll=True)
# Blif file with multiple models (currently only handles one flattened models)
assert(len(result) == 1)
clk_set = set([])
ff_clk_set = set([])
def extract_inputs(model):
start_names = [re.sub(r'\[([0-9]+)\]$', '', x) for x in model['input_list']]
name_counts = collections.Counter(start_names)
for input_name in name_counts:
bitwidth = name_counts[input_name]
if input_name == 'clk':
clk_set.add(input_name)
elif not merge_io_vectors or bitwidth == 1:
block.add_wirevector(Input(bitwidth=1, name=input_name))
else:
wire_in = Input(bitwidth=bitwidth, name=input_name, block=block)
for i in range(bitwidth):
bit_name = input_name + '[' + str(i) + ']'
bit_wire = WireVector(bitwidth=1, name=bit_name, block=block)
bit_wire <<= wire_in[i]
def extract_outputs(model):
start_names = [re.sub(r'\[([0-9]+)\]$', '', x) for x in model['output_list']]
name_counts = collections.Counter(start_names)
for output_name in name_counts:
bitwidth = name_counts[output_name]
if not merge_io_vectors or bitwidth == 1:
#.........这里部分代码省略.........
示例12: Verilog_BNF
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
#.........这里部分代码省略.........
outputDecl |
inoutDecl |
regDecl |
netDecl3 |
netDecl1 |
netDecl2 |
timeDecl |
integerDecl |
realDecl |
eventDecl |
gateDecl |
parameterOverride |
continuousAssign |
specifyBlock |
initialStmt |
alwaysStmt |
task |
functionDecl |
# these have to be at the end - they start with identifiers
moduleInstantiation |
udpInstantiation
)
""" All possible moduleItems, from Verilog grammar spec
x::= <parameter_declaration>
x||= <input_declaration>
x||= <output_declaration>
x||= <inout_declaration>
?||= <net_declaration> (spec does not seem consistent for this item)
x||= <reg_declaration>
x||= <time_declaration>
x||= <integer_declaration>
x||= <real_declaration>
x||= <event_declaration>
x||= <gate_declaration>
x||= <UDP_instantiation>
x||= <module_instantiation>
x||= <parameter_override>
x||= <continuous_assign>
x||= <specify_block>
x||= <initial_statement>
x||= <always_statement>
x||= <task>
x||= <function>
"""
portRef = subscrIdentifier
portExpr = portRef | Group( LBRACE + delimitedList( portRef ) + RBRACE )
port = portExpr | Group( ( DOT + identifier + LPAR + portExpr + RPAR ) )
moduleHdr = Group ( oneOf("module macromodule") + identifier +
Optional( LPAR + Group( Optional( delimitedList(
Group(oneOf("input output") +
(netDecl1Arg | netDecl2Arg | netDecl3Arg) ) |
port ) ) ) +
RPAR ) + SEMI ).setName("moduleHdr")
module = Group( moduleHdr +
Group( ZeroOrMore( moduleItem ) ) +
"endmodule" ).setName("module")#.setDebug()
udpDecl = outputDecl | inputDecl | regDecl
#~ udpInitVal = oneOf("1'b0 1'b1 1'bx 1'bX 1'B0 1'B1 1'Bx 1'BX 1 0 x X")
udpInitVal = (Regex("1'[bB][01xX]") | Regex("[01xX]")).setName("udpInitVal")
udpInitialStmt = Group( "initial" +
identifier + EQ + udpInitVal + SEMI ).setName("udpInitialStmt")
levelSymbol = oneOf("0 1 x X ? b B")
levelInputList = Group( OneOrMore( levelSymbol ).setName("levelInpList") )
outputSymbol = oneOf("0 1 x X")
combEntry = Group( levelInputList + COLON + outputSymbol + SEMI )
edgeSymbol = oneOf("r R f F p P n N *")
edge = Group( LPAR + levelSymbol + levelSymbol + RPAR ) | \
Group( edgeSymbol )
edgeInputList = Group( ZeroOrMore( levelSymbol ) + edge + ZeroOrMore( levelSymbol ) )
inputList = levelInputList | edgeInputList
seqEntry = Group( inputList + COLON + levelSymbol + COLON + ( outputSymbol | "-" ) + SEMI ).setName("seqEntry")
udpTableDefn = Group( "table" +
OneOrMore( combEntry | seqEntry ) +
"endtable" ).setName("table")
"""
<UDP>
::= primitive <name_of_UDP> ( <name_of_variable> <,<name_of_variable>>* ) ;
<UDP_declaration>+
<UDP_initial_statement>?
<table_definition>
endprimitive
"""
udp = Group( "primitive" + identifier +
LPAR + Group( delimitedList( identifier ) ) + RPAR + SEMI +
OneOrMore( udpDecl ) +
Optional( udpInitialStmt ) +
udpTableDefn +
"endprimitive" )
verilogbnf = OneOrMore( module | udp ) + StringEnd()
verilogbnf.ignore( cppStyleComment )
verilogbnf.ignore( compilerDirective )
return verilogbnf
示例13: Word
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
# Plugin
#
pluginType = Word(alphanums)
pluginName = Word(alphanums + "@_")
pluginDesc = Group(pluginType + pluginName + lbrace + Group(ZeroOrMore(pluginAttr)) + rbrace).setParseAction(
getPluginDesc
)
pluginDesc.ignore("//" + restOfLine)
pluginDesc.ignore(cStyleComment)
# Scene
#
sceneDesc = OneOrMore(pluginDesc)
sceneDesc.ignore("//" + restOfLine)
sceneDesc.ignore(cStyleComment)
nameParser = ZeroOrMore(Group(pluginType + pluginName + lbrace))
nameParser.ignore("//" + restOfLine)
nameParser.ignore(cStyleComment)
def ParseVrscene(filepath):
return sceneDesc.parseString(open(filepath, "r").read())
def GetMaterialsNames(filepath):
materialPluginNames = []
with open(filepath, "r") as f:
for l in f:
示例14: Suppress
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
define_function_scope = (Suppress(define) + field + scope)
define_function_scope.setParseAction(define_fn)
if_expression = (Suppress(if_) + Suppress(Literal('(')) + expression + Suppress(Literal(')')))
if_scope = (if_expression + scope)
if_scope.setParseAction(if_scope_fn)
elif_expression = (Suppress(elif_) + Suppress(Literal('(')) + expression + Suppress(Literal(')')))
elif_scope = (elif_expression + scope)
elif_scope.setParseAction(elif_scope_fn)
elif_scopes = ZeroOrMore(Group(elif_scope))
elif_scopes.setParseAction(elif_scopes_fn)
else_scope = (Suppress(else_) + scope)
else_scope.setParseAction(else_scope_fn)
conditional = (if_scope + Optional(elif_scopes) + Optional(else_scope))
conditional.setParseAction(conditional_fn)
while_expression = (Suppress(while_) + Suppress(Literal('(')) + expression + Suppress(Literal(')')))
while_scope = (while_expression + scope)
while_scope.setParseAction(while_scope_fn)
statement = ((array_assignment | assignment | conditional | call | return_expression | while_scope | define_function_scope) + Suppress(';'))
statement.setParseAction(statement_fn)
block = OneOrMore((statement | cStyleComment | pythonStyleComment))
block.setParseAction(block_fn)
block.ignore(cStyleComment)
block.ignore(pythonStyleComment)
scope << (Suppress(Literal('{')) + Group(block) + Suppress(Literal('}')))
scope.setParseAction(scope_fn)
示例15: Verilog_BNF
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import ignore [as 别名]
#.........这里部分代码省略.........
outputDecl |
inoutDecl |
regDecl |
netDecl3 |
netDecl1 |
netDecl2 |
# timeDecl |
# integerDecl |
# realDecl |
# eventDecl |
# gateDecl |
# parameterOverride |
# continuousAssign |
# specifyBlock |
# initialStmt |
# alwaysStmt |
# task |
# functionDecl |
# these have to be at the end - they start with identifiers
moduleInstantiation #|
# udpInstantiation
)
""" All possible moduleItems, from Verilog grammar spec
x::= <parameter_declaration>
x||= <input_declaration>
x||= <output_declaration>
x||= <inout_declaration>
?||= <net_declaration> (spec does not seem consistent for this item)
x||= <reg_declaration>
x||= <time_declaration>
x||= <integer_declaration>
x||= <real_declaration>
x||= <event_declaration>
x||= <gate_declaration>
x||= <UDP_instantiation>
x||= <module_instantiation>
x||= <parameter_override>
x||= <continuous_assign>
x||= <specify_block>
x||= <initial_statement>
x||= <always_statement>
x||= <task>
x||= <function>
"""
portRef = subscrIdentifier
portExpr = portRef | Group( "{" + delimitedList( portRef ) + "}" )
port = portExpr | Group( ( "." + identifier + "(" + portExpr + ")" ) )
moduleHdr = Group ( oneOf("module macromodule") + identifier +
Optional( "(" + Group( Optional( delimitedList(
Group(oneOf("input output") +
(netDecl1Arg | netDecl2Arg | netDecl3Arg) ) |
port ) ) ) +
")" ) + semi ).setName("moduleHdr")
module = Group( moduleHdr +
Group( ZeroOrMore( moduleItem ) ) +
"endmodule" ).setName("module").setParseAction(removeUselessStuff).setParseAction(printStatus)#.setDebug()
# udpDecl = outputDecl | inputDecl | regDecl
#~ udpInitVal = oneOf("1'b0 1'b1 1'bx 1'bX 1'B0 1'B1 1'Bx 1'BX 1 0 x X")
# udpInitVal = (Regex("1'[bB][01xX]") | Regex("[01xX]")).setName("udpInitVal")
# udpInitialStmt = Group( "initial" +
# identifier + "=" + udpInitVal + semi ).setName("udpInitialStmt")
# levelSymbol = oneOf("0 1 x X ? b B")
# levelInputList = Group( OneOrMore( levelSymbol ).setName("levelInpList") )
# outputSymbol = oneOf("0 1 x X")
# combEntry = Group( levelInputList + ":" + outputSymbol + semi )
# edgeSymbol = oneOf("r R f F p P n N *")
# edge = Group( "(" + levelSymbol + levelSymbol + ")" ) | \
# Group( edgeSymbol )
# edgeInputList = Group( ZeroOrMore( levelSymbol ) + edge + ZeroOrMore( levelSymbol ) )
# inputList = levelInputList | edgeInputList
# seqEntry = Group( inputList + ":" + levelSymbol + ":" + ( outputSymbol | "-" ) + semi ).setName("seqEntry")
# udpTableDefn = Group( "table" +
# OneOrMore( combEntry | seqEntry ) +
# "endtable" ).setName("table")
"""
<UDP>
::= primitive <name_of_UDP> ( <name_of_variable> <,<name_of_variable>>* ) ;
<UDP_declaration>+
<UDP_initial_statement>?
<table_definition>
endprimitive
"""
# udp = Group( "primitive" + identifier +
# "(" + Group( delimitedList( identifier ) ) + ")" + semi +
# OneOrMore( udpDecl ) +
# Optional( udpInitialStmt ) +
# udpTableDefn +
# "endprimitive" )
verilogbnf = OneOrMore( module ) + StringEnd()
verilogbnf.ignore( cppStyleComment )
# verilogbnf.ignore( compilerDirective )
return verilogbnf