示例#1
0
def test4():
    g = Grammar("start: '\(' name_list (COMMA MUL NAME)? '\)'; @name_list: NAME | name_list COMMA NAME ;  MUL: '\*'; COMMA: ','; NAME: '\w+'; ")
    l = g.parse('(a,b,c,*x)')

    g = Grammar("start: '\(' name_list (COMMA MUL NAME)? '\)'; @name_list: NAME | name_list COMMA NAME ;  MUL: '\*'; COMMA: ','; NAME: '\w+'; ")
    l2 = g.parse('(a,b,c,*x)')
    assert l == l2, '%s != %s' % (l,l2)
示例#2
0
def test_python_parse2(n):
    g = Grammar(file(python_g_file))
    if n == 0:
        s = """
a = \\
        \\
        1\\
        +2\\
-3
print a
"""
    elif n == 1:
        s = "a=b;c=d;x=e\n"

    elif n == 2:
        s = r"""
@spam3 (\
this,\
blahblabh\
)
def eggs9():
    pass

"""
    else:
        assert False

    logging.debug( g.parse(s) )
示例#3
0
 def __init__(self):
     self.dataclose = self.datas[0].close
     self.indicators = []
     self.strategy_expression_buy = self.params.strategy_expression_buy
     self.strategy_expression_sell = self.params.strategy_expression_sell
     self.strategies_parameters = self.params.strategies_parameters
     for s, p in self.strategies_parameters.items():
         if p["name"] == "CCI_buy_Strategy":
             self.indicators.append(bt.indicators.CommodityChannelIndex())
         elif p["name"] == "CCI_sell_Strategy":
             self.indicators.append(bt.indicators.CommodityChannelIndex())
         elif p["name"] == "Crossover_SMA_Strategy":
             sma_fast, sma_slow = bt.ind.SMA(period=p["parameter"]["fast"]), bt.ind.SMA(period=p["parameter"]["slow"])
             self.indicators.append(bt.indicators.CrossOver(sma_fast, sma_slow))
     self.strategy_parser = Grammar("""
                                     start: exp ;
                                     @exp : strategy | atomic ;
                                     atomic: '\(' exp op exp '\)' | exp op exp ;
                                     strategy: 's\d+' ;
                                     op: '\&|\|' ;
                                     SPACES: '[ ]+' (%ignore) ;
                                 """)
     self.strategy_expression_buy = self.strategy_parser.parse(self.strategy_expression_buy)
     self.calc_buy = self.Calc(self.indicators, self.strategies_parameters)
     self.strategy_expression_sell = self.strategy_parser.parse(self.strategy_expression_sell)
     self.calc_sell = self.Calc(self.indicators, self.strategies_parameters)
示例#4
0
def test_python_with_filters():
    g = Grammar(file('python3.g'))
    #pprint(g.parse('f(1,2,3)\n'))
    #pprint(g.parse('if a:\n\tb\n'))
    #pprint(g.parse(FIB))
    #pprint(g.parse('a or not b and c\n'))
    pprint(g.parse(file('../plyplus.py').read()))
示例#5
0
def test3():
    # Multiple parsers and colliding tokens
    g = Grammar("start: B A ; B: '12'; A: '1'; ", auto_filter_tokens=False)
    g2 = Grammar("start: B A; B: '12'; A: '2'; ", auto_filter_tokens=False)
    x = g.parse('121')
    assert x.head == 'start' and x.tail == ['12', '1'], x
    x = g2.parse('122')
    assert x.head == 'start' and x.tail == ['12', '2'], x
示例#6
0
def test2():
    g = Grammar("start: A+ B A@+ 'b' A*; B: 'b'; A: 'a';")
    #print g.parse('aaabaab')
    for x in g.parse('aaabaab'):
        if isinstance(x, TokValue):
            tok = x
            print 'tok #%d: %s = %s {%d:%d}' % (tok.index, tok.type, tok, tok.line, tok.column)
        else:
            print type(x), x
示例#7
0
def test_python_lex(code=FIB, expected=54):
    g = Grammar(file('python.g').read())
    l = g.lex(code)
    for x in l:
        y = x.value
        if isinstance(y, TokValue):
            logging.debug('%s %s %s', y.type, y, y.line, y.column)
        else:
            logging.debug('%s %s', x.type, x.value)
    assert len(l) == expected, len(l)
示例#8
0
def test_config_parser():
    g = Grammar(file('../grammars/config.g'), auto_filter_tokens=True)
    res = g.parse("""
        [ bla Blah bla ]
        thisAndThat = hel!l%o/
        one1111:~$!@ and all that stuff

        [Section2]
        whatever: whatever
        """)
    print res
示例#9
0
def test_python_lib_with_filters(path = PYTHON_LIB):
    import glob, os
    g = Grammar(file('python3.g'))

    files = glob.glob(path+'\\*.py')
    start = time.time()
    for f in files:
        f2 = os.path.join(path,f)
        print f2
        l = g.parse(file(f2).read())

    end = time.time()
    logging.info("Test3 (%d files), time: %s secs"%(len(files), end-start))
示例#10
0
def test_python_lib():
    import glob, os
    g = Grammar(file(python_g_file))

    path = PYTHON_LIB
    files = glob.glob(path+'/*.py')
    start = time.time()
    for f in files:
        f2 = os.path.join(path,f)
        logging.info( f2 )
        l = g.parse(file(f2).read())

    end = time.time()
    logging.info( "Test3 (%d files), time: %s secs"%(len(files), end-start) )
示例#11
0
def test():
    #p = grammar_parser.parse(file('sample_grammar.txt').read())
    #pt = ParseTree(p)
    #t = FlattenGrammar_Visitor().visit(p)
    #t = SimplifyGrammar_Visitor('simp_').visit(p)
    #pt.visit(FlattenGrammar_Visitor())

    g = Grammar(file('sample_grammar.txt').read())
    for x in g.parse(file('sample_input.txt').read())[1][1]:
        if isinstance(x, TokValue):
            tok = x
            #print 'tok #%d: %s = %s {%d:%d}' % (tok.index, tok.type, tok, tok.line, tok.column)
        else:
            #print type(x), x
            pass

    #g = Grammar("start: 'a' 'a' B* ('c'? de)+; B: 'b'; C: 'c'; @de: DE; DE: 'de'; ")
    #print g.parse('aabbbde')
    #print g.parse('aacdede')


    #g = Grammar("start: A | a -> A; a: B (A|B) -> B; A: 'a'; B: 'b';")
    #print g.parse('aaabaab')
    pass
示例#12
0
文件: json.py 项目: zhukeming/plyplus
from plyplus import Grammar, STransformer

json_grammar = Grammar(r"""
@start: value ;

?value : object | array | string | number | boolean | null ;

string : '".*?(?<!\\)(\\\\)*?"' ;
number : '-?([1-9]\d*|\d)(\.\d+)?([eE][+-]?\d+)?' ;
pair : string ':' value ;
object : '\{' ( pair ( ',' pair )* )? '\}' ;
array : '\[' ( value ( ',' value ) * )? '\]' ;
boolean : 'true' | 'false' ;
null : 'null' ;

WS: '[ \t\n]+' (%ignore) (%newline);
""")


class JSON_Transformer(STransformer):
    """Transforms JSON AST into Python native objects."""
    number = lambda self, node: float(node.tail[0])
    string = lambda self, node: node.tail[0][1:-1]
    boolean = lambda self, node: True if node.tail[0] == 'true' else False
    null = lambda self, node: None
    array = lambda self, node: node.tail
    pair = lambda self, node: {node.tail[0]: node.tail[1]}

    def object(self, node):
        result = {}
        for i in node.tail:
示例#13
0
文件: dml.py 项目: nnog/dml
            sectindex = headerindex + 1
            assert sectindex < len(parts)
            s = 'def %s(self, tree):\n%s\n_userfunc = %s' % (name, parts[sectindex], name)
            exec s
            setattr(transformer, name, types.MethodType(_userfunc, transformer))

    if len(pyheaders) >= 1:
        for s in pysections:
            exec s
            if preparse != preparse_funcs[-1]:
                preparse_funcs.append(preparse)
            if postparse != postparse_funcs[-1]:
                postparse_funcs.append(postparse)

    #Construct grammar from combined grammar source
    grammar = Grammar(grammarsrc);
    
    #Process styles from combined style source
    styles = Style(stylesrc)
    tikzpicture_env_options = styles.get(elem='tikzpicture', override=tikzpicture_env_options)
    
    #Apply sequence of preparse functions
    for prefunc in preparse_funcs:
        source = prefunc(source)

    #Make substitutions
    docpreamble = docpreamble.replace('%_document_class_%', document_class)
    docpreamble = docpreamble.replace('%_document_class_options_%', document_class_options)
    docpreamble = docpreamble.replace('%_tikz_package_options_%', tikz_package_options)
    docpreamble = docpreamble.replace('%_tikz_libraries_%', ','.join(tikz_libraries))
    docpreamble = docpreamble.replace('%_additional_preamble_%', additional_preamble)
示例#14
0
user_grammar = Grammar("""
  start: logical_or;

  ?logical_or: logical_or op_or logical_and | logical_and;
  ?logical_and: logical_and op_and expr | expr;

  ?expr: un_string_expr | un_expr | bin_expr | '\(' logical_or '\)';

  ?bin_expr: (bin_string_expr | bin_passwd_expr | bin_pk_expr | bin_date_expr |
              bin_bool_expr);

  un_string_expr: (string_field | password) pr;
  un_expr: (date_field | bool_field) pr;
  bin_string_expr: string_field string_op t_string;
  bin_passwd_expr: password eq t_string;
  bin_pk_expr: pk eq t_string;
  bin_date_expr: date_field date_op t_date;
  bin_bool_expr: bool_field eq t_bool;

  ?string_op: eq | co | sw;
  ?date_op: eq | gt | ge | lt | le;

  ?op_or: '(?i)or';
  ?op_and: '(?i)and';
  pr: '(?i)pr';
  eq: '(?i)eq';
  co: '(?i)co';
  sw: '(?i)sw';
  gt: '(?i)gt';
  ge: '(?i)ge';
  lt: '(?i)lt';
  le: '(?i)le';

  ?string_field: username | first_name | last_name | email;
  ?date_field: date_joined;
  ?bool_field: is_active;

  username: '******';
  first_name: '(?i)name\.givenName' | '(?i)givenName';
  last_name: '(?i)name\.familyName' | '(?i)familyName';
  password: '******';
  pk: '(?i)id';
  date_joined: '(?i)meta\.created' | '(?i)created';
  email: '(?i)emails\.value' | '(?i)emails';
  is_active: '(?i)active';

  t_string: '"(?:[^"\\\\]|\\\\.)*"' ;
  t_date: '"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[Zz]?"';
  t_bool: 'false' | 'true';

  SPACES: '[ ]+' (%ignore);
  """)
示例#15
0
import sys, os
import logging

sys.path.insert(0, os.path.abspath(".."))
sys.path.insert(0, os.path.abspath("../grammars"))
from plyplus import Grammar, TokValue, STree
from selector import selector
from pprint import pprint

logging.basicConfig(level=logging.INFO)

tree_grammar = Grammar("start: branch; branch: name ('{' branch@* '}')?; name: '[a-z]';")

tree1 = tree_grammar.parse("a{b{cde}}")
tree2 = tree_grammar.parse("a{abc{bbab}c}")


def test_elem_head():
    assert len(selector("name").match(tree1)) == 5
    assert len(selector("branch").match(tree1)) == 5
    assert len(selector("name").match(tree2)) == 9
    assert len(selector("branch").match(tree2)) == 9


def test_elem_regexp():
    assert len(selector("/[a-c]$/").match(tree1)) == 3
    assert len(selector("/[b-z]$/").match(tree2)) == len("bcbbbc")


def test_elem_any():
    assert len(selector("*").match(tree1)) == 16
示例#16
0
"""Demonstrates the use of the permutation operator."""
from plyplus import Grammar

# Basic Permutations
perm1 = Grammar("""
start : a ^ b? ^ c ;

a : 'a' ;
b : 'b' ;
c : 'c' ;

WS: '[ \t]+' (%ignore);
""")

print perm1.parse(' c b a').pretty()
print perm1.parse('c a ').pretty()

# Permutations with a separator
perm2 = Grammar("""
start : a ^ (b|d)? ^ c ^^ ( COMMA | SEMI ) ;

a : 'a' ;
b : 'b' ;
c : 'c' ;
d : 'd' ;

COMMA : ',' ;
SEMI  : ';' ;

WS: '[ \t]+' (%ignore);
""")
示例#17
0
    # Python 3.x already have lazy map
    pass

__all__ = ["parse"]
__version__ = "0.2.0"

grammar = Grammar(r"""
@start : package ;


package : name extras? specs? comment?;
name : string ;

specs : comparison version (',' comparison version)* ;
comparison : '<' | '<=' | '!=' | '==' | '>=' | '>' | '~=' | '===' ;
version : string ;

extras : '\[' (extra (',' extra)*)? '\]' ;
extra : string ;

comment : '\#.+' ;

@string : '[-A-Za-z0-9_\.]+' ;

SPACES: '[ \t\n]+' (%ignore) (%newline);
""")


class Requirement(object):
    def __init__(self, name=None, extras=None, specs=None, comment=None):
        self.name = name
        self.extras = extras
示例#18
0
def test_auto_filtered_python():
    g = Grammar(file('python3.g'), auto_filter_tokens=True, expand_all_repeaters=True)
    r = g.parse(file('../plyplus.py').read())
    #pprint()
    from sexp import find
    print [x.tail[0] for x in find(r, 'decorator')]
示例#19
0
# Eval and bridge to the scripting lang.

import operator as op
import math

# do not mess with following 3 lines.
from plyplus import Grammar

gram_text = open('grmr.g', 'r').read()
grammar = Grammar(gram_text)


class EvalError(BaseException):
    pass


class Scope:
    def __init__(self, parent, isfunc, kwargs):
        self.parent = parent
        self.vars = {}
        self.isfunc = isfunc
        self.vars.update(kwargs)

    def __getitem__(self, item):
        try:
            return self.vars[item]
        except:
            try:
                return self.parent[item]
            except:
                raise EvalError, "Variable not defined: " + str(item)
示例#20
0
文件: parser2.py 项目: h-ohsaki/cellx
list_parser = Grammar(r"""
start : (command eol)* ; 
command : alpha_command | animate_command | color_command | 'display' | define_command | kill_command | spring_command | 'wait';

alpha_command: 'alpha' pattern number;
animate_command: 'animate' geometry;
color_command: 'color' pattern color;

define_command: box_command ;
// box_command : 'define' name 'box' number number (color)? (geometry)? (option)*;
box_command : 'define' name 'box' number number color;
kill_command: 'kill' pattern ;

sleep_command: 'sleep' number;

spring_command: 'spring' pattern (number number number number)? (option)*;

pattern: name (name)* | regexp ;

option: '-' name;

geometry : number number | name (offset)?;
offset : '\+' number '-' number ;

color: simple_color ('\*' number)?;
simple_color: name | '\#[\da-f]{6,8}' | number ',' number ',' number (',' number)? | name '\*' number; 

name : '[A-Za-z][0-9A-Za-z]*' ;
number : '[\d\.]+' ;

regexp: 'r\'.+?\'' ;

eol : '\n' ;
SPACES : ' +' (%ignore) ;
""")
示例#21
0
import sys, os
import logging
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../grammars'))
from plyplus import Grammar, TokValue, STree
from selector import selector
from pprint import pprint

logging.basicConfig(level=logging.INFO)

tree_grammar = Grammar("start: branch; branch: name ('{' branch* '}')?; name: '[a-z]';")

tree1 = tree_grammar.parse('a{b{cde}}')
tree2 = tree_grammar.parse('a{abc{bbab}c}')

def test_elem_head():
    assert len( selector('name').match(tree1) ) == 5
    assert len( selector('branch').match(tree1) ) == 5
    assert len( selector('name').match(tree2) ) == 9
    assert len( selector('branch').match(tree2) ) == 9

def test_elem_regexp():
    assert len( selector('/[a-c]$/').match(tree1) ) == 3
    assert len( selector('/[b-z]$/').match(tree2) ) == len('bcbbbc')

def test_elem_any():
    assert len( selector('*').match(tree1) ) == 16
    assert len( selector('*').match(tree2) ) == 28

def test_elem():
    test_elem_head()
示例#22
0
 def buildGrammar(self):
     return Grammar(self.grammar)
示例#23
0
# calc.py - # A simple calculator without using eval
# A shorter and simpler re-implementation of http://www.dabeaz.com/ply/example.html

import operator as op
from plyplus import Grammar, STransformer

calc_grammar = Grammar(open("calc.g"))


class Calc(STransformer):
    def __init__(self):
        super()

    def _bin_operator(self, exp):
        arg1, operator_symbol, arg2 = exp.tail

        operator_func = {
            '+': op.add,
            '-': op.sub,
            '%': op.mod,
            '*': op.mul,
            '/': op.truediv,
            '^': op.pow
        }[operator_symbol]

        print(exp.tail, '=>', operator_func(arg1, arg2))
        return operator_func(arg1, arg2)

    number = lambda self, exp: float(exp.tail[0])
    negate = lambda self, exp: -exp.tail[0]
    __default__ = lambda self, exp: exp.tail[0]
示例#24
0
COMPLEX = """
using Complex

z = a + b i
"""

HELLO_PEPPER = """
main() =
  pr("Hello world!")
"""

HELLO_PYTHON = """
def main():
  pr("Hello world!")

"""


# g = Grammar(file("python.g"))
# print g.parse(FIB_PYTHON)
g = Grammar(file("pepper2.g"), debug=True)

# try:
# pdb.set_trace()
ast = g.parse(HELLO_PEPPER)
print ast
compile.compile_ast(ast, "hello")
# print g.parse(HELLO)
#except:
#  pass
示例#25
0
def test_python_parse():
    g = Grammar(file(python_g_file))
    if 1:
        start = time.time()
        l = g.parse(file('python_sample1.py').read())
        l = g.parse(file('python_sample2.py').read())
        l = g.parse(file('../../examples/calc.py').read())
        l = g.parse(file('../grammar_lexer.py').read())
        l = g.parse(file('../grammar_parser.py').read())
        l = g.parse(file('../strees.py').read())
        l = g.parse(file('../grammars/python_indent_postlex.py').read())
    ##l = g.parse(file('parsetab.py').read())

        l = g.parse(file('../plyplus.py').read())

        l = g.parse("c,d=x,y=a+b\nc,d=a,b\n")
        end = time.time()
        logging.info("Time: %s secs " % (end-start))

    if PYTHON25_LIB:
        l = g.parse(file(PYTHON25_LIB + 'os.py').read())
        l = g.parse(file(PYTHON25_LIB + 'pydoc.py').read())
示例#26
0
class Main_Strategy(bt.Strategy):
    params = ( ('strategy_expression_buy', None ), ('strategy_expression_sell', None ), ('strategies_parameters', None), )

    class Calc(STransformer):
        def __init__(self, indicators, strategies_parameters):
            self.indicators = indicators
            self.strategies_parameters = strategies_parameters
            self.strategies_functions = {
                "CCI_buy_Strategy": self.CCI_buy_Strategy,
                "CCI_sell_Strategy": self.CCI_sell_Strategy,
                "Crossover_SMA_Strategy": self.Crossover_SMA_Strategy
            }
        def CCI_buy_Strategy(self, parameter, indicator):
            if self.indicators[indicator] < parameter["value"]:
                return 1
            else:
                return 0

        def CCI_sell_Strategy(self, parameter, indicator):
            if self.indicators[indicator] > parameter["value"]:
                return 1
            else:
                return 0

        def Crossover_SMA_Strategy(self, parameter, indicator):
            if self.indicators[indicator] > 0:
                return 1
            else:
                return 0

        def _bin_operator(self, atom):
            arg1, operator_symbol, arg2 = atom.tail
            operator_func = { '&': op.and_, '|': op.or_ }[operator_symbol.tail[0]]
            return operator_func(arg1, arg2)

        def _bin_strategy(self, atom):
            s_p = self.strategies_parameters[atom.tail[0]]
            return self.strategies_functions[s_p["name"]](s_p["parameter"], int(atom.tail[0].replace("s","")))

        strategy = _bin_strategy
        atomic = _bin_operator

    def __init__(self):
        self.dataclose = self.datas[0].close
        self.indicators = []
        self.strategy_expression_buy = self.params.strategy_expression_buy
        self.strategy_expression_sell = self.params.strategy_expression_sell
        self.strategies_parameters = self.params.strategies_parameters
        for s, p in self.strategies_parameters.items():
            if p["name"] == "CCI_buy_Strategy":
                self.indicators.append(bt.indicators.CommodityChannelIndex())
            elif p["name"] == "CCI_sell_Strategy":
                self.indicators.append(bt.indicators.CommodityChannelIndex())
            elif p["name"] == "Crossover_SMA_Strategy":
                sma_fast, sma_slow = bt.ind.SMA(period=p["parameter"]["fast"]), bt.ind.SMA(period=p["parameter"]["slow"])
                self.indicators.append(bt.indicators.CrossOver(sma_fast, sma_slow))
        self.strategy_parser = Grammar("""
                                        start: exp ;
                                        @exp : strategy | atomic ;
                                        atomic: '\(' exp op exp '\)' | exp op exp ;
                                        strategy: 's\d+' ;
                                        op: '\&|\|' ;
                                        SPACES: '[ ]+' (%ignore) ;
                                    """)
        self.strategy_expression_buy = self.strategy_parser.parse(self.strategy_expression_buy)
        self.calc_buy = self.Calc(self.indicators, self.strategies_parameters)
        self.strategy_expression_sell = self.strategy_parser.parse(self.strategy_expression_sell)
        self.calc_sell = self.Calc(self.indicators, self.strategies_parameters)

    def next(self):
        buysig = self.calc_buy.transform(self.strategy_expression_buy).tail[0]
        sellsig = self.calc_sell.transform(self.strategy_expression_sell).tail[0]
        if not self.position:
            if buysig:
                self.buy()
        else:
            if sellsig:
                self.close()

        if len(self.dataclose) == (self.dataclose.buflen())-1:
            self.close()
示例#27
0
calc_grammar = Grammar("""
    @start: assign;
    // Rules
    ?assign: (id eq_symbol)? logic;
    ?logic: (logic logic_symbol)? add;
    ?add: (add add_symbol)? mul;
    ?mul: (mul mul_symbol)? atom;
    @atom: neg | number | '\(' add '\)' | boolean | id;
    neg: '-' atom;
    // Tokens
    number: '[\d.]+';
    eq_symbol: '<-';

    boolean : true | false;
    true: TRUE;
    false: FALSE;
    logic_symbol: '\&' | '\|';

    id: ID;
    ID: '\w+'
    (%unless
    TRUE: 'TRUE';
    FALSE: 'FALSE';
    );

    mul_symbol: '\*' | '/';
    add_symbol: '\+' | '-';


    WS: '[ \t]+' (%ignore);
""")
示例#28
0
def test_python4ply_sample():
    g = Grammar(file(python_g_file))
    l = g.parse(file(r'python4ply-sample.py').read())
示例#29
0
        #tokens = tokens +' '+token[2].lower()

    return tokens


path = 'Programas_MiniJava/programa1.java'

with open(path) as f:
    texto_arq = f.readlines()

#print(texto)
texto = ''
for i in texto_arq:
    texto = texto + i

texto = retornaTokensArquivo(path)
cont = 1
text = ''
for i in texto:
    text = text + i
    if i == ' ':
        #print(text, cont)
        cont += 1
        text = ''
#print(texto)
#texto = retornaTokensArquivo(path)

parser = Grammar(open("MiniJava.g"))
resp = parser.parse(texto)
print(resp)
示例#30
0
def test_into():
    g = Grammar("start: '\(' name_list (COMMA MUL NAME => 2 3)? '\)' => ^1 ^-1; @name_list: NAME | name_list COMMA NAME => 1 3;  MUL: '\*'; COMMA: ','; NAME: '\w+'; ")
    assert g.parse('(a,b,c,*x)') == ['start', 'a', 'b', 'c', '*', 'x']
    assert g.parse('(a,b,c,x)') == ['start', 'a', 'b', 'c', 'x']
示例#31
0
import operator as op
from plyplus import Grammar, STransformer

calc_grammar = Grammar("""
    start: add;
    ?add: (add add_symbol)? mul;
    ?mul: (mul mul_symbol)? atom;
    @atom: neg | number | '\(' add '\)';
    neg: '-' atom;
    number: '[\d.]+';
    mul_symbol: '\*' | '/';
    add_symbol: '\+' | '-';
    WS: '[ \t]+' (%ignore);
""")

class Calc(STransformer):

    def _bin_operator(self, exp):
        arg1, operator_symbol, arg2 = exp.tail

        operator_func = { '+': op.add, '-': op.sub, '*': op.mul, '/': op.div }[operator_symbol]

        return operator_func(arg1, arg2)

    number      = lambda self, exp: float(exp.tail[0])
    neg         = lambda self, exp: -exp.tail[0]
    __default__ = lambda self, exp: exp.tail[0]

    add = _bin_operator
    mul = _bin_operator
示例#32
0
json_grammar = Grammar(r"""

start: sph_type  ;

sph_type : SPH_T VALUE VALUE VALUE VALUE VALUE ;

rpp_type : RPP_T VALUE VALUE VALUE VALUE VALUE VALUE VALUE ;

box_type : BOX_T VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE ;

rcc_type : RCC_T VALUE VALUE VALUE VALUE VALUE VALUE VALUE VALUE ;

type: sph_type | rpp_type | box_type | rcc_type ;

bodies : type bodies | type ;

operator : PLUS | MINUS ;

expr : operator VALUE expr | operator VALUE ;

zone_operation: ZONE_NAME expr | ZONE_NAME VALUE expr ;

zones : zone_operation zones | zone_operation ;

material: VALUE VALUE ;

media: material media | material ;

file : DESCRIPTION SEPARATOR bodies SEPARATOR zones SEPARATOR media ;

VALUE : '-?([0-9]+)(\.[0-9]+)?' ;
SPH_T : 'SPH' ;
RPP_T : 'RPP' ;
BOX_T : 'BOX' ;
RCC_T : 'RCC' ;
SEPARATOR : 'END' ;
MINUS : '\-' ;
PLUS : '\+' ;
DESCRIPTION : '".*"' ;
ZONE_NAME : '[a-zA-Z0-9]{3,3}' ;
WS: '[ \t\n]+' (%ignore);

""")