Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
sky_color = (pp.Literal('skyColor') + color_datai).setName('sky_color')
background_values = pp.OneOrMore(sky_color)
background = (
pp.Literal('Background') +
dict_open +
pp.Group(background_values) +
dict_close).setName('background')
background.parseString("""
Background {
skyColor 0.1 0.3 1
}
""")
# --------------------------------------
typei = (pp.Literal('type') + pp.quotedString).setName('type')
headlight = (pp.Literal('headlight') + boolean).setName('headlight')
navigation_info_values = pp.OneOrMore(typei | headlight)
navigation_info = (
pp.Literal('NavigationInfo') +
dict_open +
pp.Group(navigation_info_values) +
dict_close).setName('navigation_info')
navigation_info.parseString("""
NavigationInfo {
type "EXAMINE"
headlight TRUE
}
""")
#-----------------------------------------------------
image = pp.Group(
pp.Literal('image') + pp.Group(pint * 3) +
pp.Group(pp.OneOrMore(hexa))
).setName('image')
def __antlrAlternativeConverter(pyparsingRules, antlrAlternative):
elementList = []
for element in antlrAlternative.elements:
rule = None
if hasattr(element.atom, 'c1') and element.atom.c1 != '':
regex = r'['+str(element.atom.c1[0])+'-'+str(element.atom.c2[0]+']')
rule = Regex(regex)("anonymous_regex")
elif hasattr(element, 'block') and element.block != '':
rule = __antlrAlternativesConverter(pyparsingRules, element.block)
else:
ruleRef = element.atom
assert ruleRef in pyparsingRules
rule = pyparsingRules[element.atom](element.atom)
if hasattr(element, 'op') and element.op != '':
if element.op == '+':
rule = Group(OneOrMore(rule))("anonymous_one_or_more")
elif element.op == '*':
rule = Group(ZeroOrMore(rule))("anonymous_zero_or_more")
elif element.op == '?':
rule = Optional(rule)
else:
raise Exception('rule operator not yet implemented : ' + element.op)
rule = rule
elementList.append(rule)
if len(elementList) > 1:
rule = Group(And(elementList))("anonymous_and")
else:
rule = elementList[0]
assert rule != None
return rule
def parse(self, config):
VALUE = OneOrMore(Word(alphanums + "-/.:_+") | QuotedString("'"))
context = []
indent = []
for l in config.splitlines():
ls = l.strip()
if not ls or ls.startswith("!"):
continue # Comment line
match = self.rx_indent.search(l)
ilevel = len(match.group(1))
if not indent:
indent = [ilevel]
context = [ls]
elif indent[-1] == ilevel:
# Same level context
context = context[:-1] + [ls]
elif indent[-1] < ilevel:
# Down
production process. (string) Several equation are seperated by a ;
Returns:
A production_function that can be used in produce etc.
Example:
formula = 'golf_ball = (ball) * (paint / 2); waste = 0.1 * paint'
self.production_function = create_production_function(formula)
self.produce(self.production_function, {'ball' : 1, 'paint' : 2}
//exponential is ** not ^
"""
parse_single_output = pp.Word(pp.alphas+"_", pp.alphanums+"_") + pp.Suppress('=') + pp.Suppress(pp.Word(pp.alphanums + '*/+-().[]{} '))
parse_output = pp.delimitedList(parse_single_output, ';')
parse_single_input = pp.Suppress(pp.Word(pp.alphas+"_", pp.alphanums+"_")) + pp.Suppress('=') \
+ pp.OneOrMore(pp.Suppress(pp.Optional(pp.Word(pp.nums + '*/+-().[]{} '))) + pp.Word(pp.alphas+"_", pp.alphanums+"_"))
parse_input = pp.delimitedList(parse_single_input, ';')
production_function = {}
production_function['type'] = typ
production_function['formula'] = formula
production_function['code'] = compiler.compile(formula, '', 'exec')
production_function['output'] = list(parse_output.parseString(formula))
production_function['input']= list(parse_input.parseString(formula))
return production_function
def get_field_grammar(field):
tag = pp.CaselessLiteral(field.name)
if field.represents_boolean:
grammar = tag.setParseAction(lambda t: True)
elif field.allows_multiple_values:
grammar = tag + pp.OneOrMore(
pp.Word(pp.nums, exact=1).setParseAction(makeInt)
)
else:
grammar = tag + pp.Word(pp.nums).setParseAction(makeInt)
return grammar
compositor_ops = pp.MatchFirst(
[pp.Literal(el.group) for el in Compositor.definitions if el.group])
dotted_path = pp.Combine( pp.Word(ascii_uppercase, exact=1)
+ pp.Word(pp.alphanums+'._'))
pathspec = (dotted_path | compositor_ops).setResultsName("pathspec")
spec_group = pp.Group(pathspec +
(pp.Optional(norm_options)
& pp.Optional(plot_options)
& pp.Optional(style_options)))
opts_spec = pp.OneOrMore(spec_group)
# Aliases that map to the current option name for backward compatibility
aliases = {'horizontal_spacing':'hspace',
'vertical_spacing': 'vspace',
'figure_alpha':' fig_alpha',
'figure_bounds': 'fig_bounds',
'figure_inches': 'fig_inches',
'figure_latex': 'fig_latex',
'figure_rcparams': 'fig_rcparams',
'figure_size': 'fig_size',
'show_xaxis': 'xaxis',
'show_yaxis': 'yaxis'}
deprecations = [('GridImage', 'Image')]
@classmethod
three_xycoords = xycoords + PYP.Optional(comma) + xycoords + PYP.Optional(comma)+xycoords
# TODO optimise this; there has to be a more efficient way to describe this
c_M = PYP.Literal('M') + PYP.OneOrMore(xycoords)
c_m = PYP.Literal('m') + PYP.OneOrMore(xycoords)
c_C = PYP.Literal('C') + PYP.OneOrMore(three_xycoords)
c_c = PYP.Literal('c') + PYP.OneOrMore(three_xycoords)
c_Q = PYP.Literal('Q') + PYP.OneOrMore(two_xycoords)
c_q = PYP.Literal('q') + PYP.OneOrMore(two_xycoords)
c_T = PYP.Literal('T') + PYP.OneOrMore(xycoords)
c_t = PYP.Literal('t') + PYP.OneOrMore(xycoords)
c_L = PYP.Literal('L') + PYP.OneOrMore(xycoords)
c_l = PYP.Literal('l') + PYP.OneOrMore(xycoords)
c_V = PYP.Literal('V') + PYP.OneOrMore(one_coord)
c_v = PYP.Literal('v') + PYP.OneOrMore(one_coord)
c_H = PYP.Literal('H') + PYP.OneOrMore(one_coord)
c_h = PYP.Literal('h') + PYP.OneOrMore(one_coord)
c_S = PYP.Literal('S') + PYP.OneOrMore(two_xycoords)
c_s = PYP.Literal('s') + PYP.OneOrMore(two_xycoords)
c_z = PYP.Literal('z')
c_Z = PYP.Literal('Z')
path_cmd = c_M | c_m | c_C | c_c | c_Q | c_q | c_T | c_t | c_L | c_l | c_V | c_v | c_H | c_h | c_S | c_s | c_Z | c_z
# Recursively convert child elements
# Here we find the most relevant Railroad element for matching pyparsing Element
# We use ``items=[]`` here to hold the place for where the child elements will go once created
if isinstance(element, pyparsing.And):
if _should_vertical(vertical, len(exprs)):
ret = EditablePartial.from_call(railroad.Stack, items=[])
else:
ret = EditablePartial.from_call(railroad.Sequence, items=[])
elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
if _should_vertical(vertical, len(exprs)):
ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
else:
ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
elif isinstance(element, pyparsing.Optional):
ret = EditablePartial.from_call(railroad.Optional, item="")
elif isinstance(element, pyparsing.OneOrMore):
ret = EditablePartial.from_call(railroad.OneOrMore, item="")
elif isinstance(element, pyparsing.ZeroOrMore):
ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
elif isinstance(element, pyparsing.Group):
ret = EditablePartial.from_call(railroad.Group, item=None, label=name)
elif isinstance(element, pyparsing.Empty) and not element.customName:
# Skip unnamed "Empty" elements
ret = None
elif len(exprs) > 1:
ret = EditablePartial.from_call(railroad.Sequence, items=[])
elif len(exprs) > 0:
ret = EditablePartial.from_call(railroad.Group, item="", label=name)
else:
# If the terminal has a custom name, we annotate the terminal with it, but still show the defaultName, because
# it describes the pattern that it matches, which is useful to have present in the diagram
terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
@param preferences_dir: Directory to load/save preferences from/to
@type preferences_dir: str
'''
self._current_node = None
self._root_node = None
self._exit = False
# Grammar of the command line
command = locatedExpr(Word(alphanums + '_'))('command')
var = Word(alphanums + ';,=_\+/.<>()~@:-%[]')
value = var
keyword = Word(alphanums + '_\-')
kparam = locatedExpr(keyword + Suppress('=') + Optional(value, default=''))('kparams*')
pparam = locatedExpr(var)('pparams*')
parameter = kparam | pparam
parameters = OneOrMore(parameter)
bookmark = Regex('@([A-Za-z0-9:_.]|-)+')
pathstd = Regex('([A-Za-z0-9:_.\[\]]|-)*' + '/' + '([A-Za-z0-9:_.\[\]/]|-)*') \
| '..' | '.'
path = locatedExpr(bookmark | pathstd | '*')('path')
parser = Optional(path) + Optional(command) + Optional(parameters)
self._parser = parser
if tty:
readline.set_completer_delims('\t\n ~!#$^&(){}\|;\'",?')
readline.set_completion_display_matches_hook(
self._display_completions)
self.log = log.Log()
if preferences_dir is not None:
preferences_dir = os.path.expanduser(preferences_dir)
graph_ = pyparsing.CaselessLiteral("graph")
digraph_ = pyparsing.CaselessLiteral("digraph")
subgraph_ = pyparsing.CaselessLiteral("subgraph")
node_ = pyparsing.CaselessLiteral("node")
edge_ = pyparsing.CaselessLiteral("edge")
# token definitions
identifier = pyparsing.Word(pyparsing.alphanums + "_.").\
setName("identifier")
# dblpyparsing.QuotedString
double_quoted_string = pyparsing.QuotedString('"', multiline=True,
unquoteResults=False)
noncomma_ = "".join([c for c in pyparsing.printables if c != ","])
alphastring_ = pyparsing.OneOrMore(pyparsing.CharsNotIn(noncomma_ +
' '))
def parse_html(s, loc, toks):
return '<%s>' % ''.join(toks[0])
opener = '<'
closer = '>'
html_text = pyparsing.nestedExpr(
opener, closer,
(pyparsing.CharsNotIn(opener + closer))).\
setParseAction(parse_html).leaveWhitespace()
ID = (
identifier | html_text |
double_quoted_string |
alphastring_).setName("ID")