ZIO
Python and C++ interface to ZeroMQ and Zyre
lispish.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 
3 import rule # bv's modified version
4 from pyparsing import *
5 def parser(params = None):
6 
7  params = params or dict()
8 
9  TRUE = CaselessKeyword("true").setParseAction(lambda m: True)
10  FALSE = CaselessKeyword("false").setParseAction(lambda m: False)
11  boolean = TRUE | FALSE
12 
13  param = Word(alphas +"_", alphanums + '_').setParseAction(lambda m:params[m[0]])
14  sstring = QuotedString('"').setName("stringliteral")
15  dstring = QuotedString("'").setName("stringliteral")
16  string = sstring | dstring
17  integer = Word(nums).setParseAction(lambda m:int(m[0]))
18 
19  ops = ">= <= != > < = == + - * / | & "
20  ops += "ge le ne gt lt eq add sub mul div or and"
21  operator = oneOf(ops).setName("operator")
22  atom = boolean | string | integer | operator | param
23 
24  lp = Suppress("(")
25  rp = Suppress(")")
26  sexp = Forward()
27  func = Group( lp + ZeroOrMore(sexp) + rp )
28  sexp << ( atom | func )
29  return sexp
30 
31 
32 def dump_parsed(pr):
33  for one in pr:
34  print (one, type(one), dir(one))
35 
36 def test():
37 
38  params = dict(a=3,b=2,name="Manfred")
39  sp = parser(params)
40 
41 
42  try:
43  pr = sp.parseString("undefined")
44  except KeyError:
45  pass
46  else:
47  raise RuntimeError("should have gotten an KeyError on 'undefined'")
48 
49 
50  for want, toparse in [
51  (True, "(or 0 1)"),
52  (True, "true"),
53  (True, "True"),
54  (False, "false"),
55  (True, "(or (= a 5) (= b 2))"),
56  (True, "(or (= a 5) (= b 2))"),
57  (True, "(and (eq name 'Manfred') (eq b 2))"),
58  (True, "(and (= name 'Manfred') (or (= a 5) (= b 2)))"),
59  (True, "(== a (+ 1 b))"),
60  (False, '(== name "Ada")'),
61  (True, '(== name "Manfred")'),
62  (True, "(== name 'Manfred')"),
63  (True, '(!= name "Ada")'),
64  (False, '(!= name "Manfred")'),
65  (True, '(| a b)'),
66  (True, '(| (< a b) (> a b))'),
67  (True, '(& (= a 3) (= 2 b))'),
68  (True, '(and (== a 3) (eq 2 b))'),
69  (True, '(!= name "name")'),
70  ]:
71 
72  pr = sp.parseString(toparse, parseAll=True)
73  #if len(pr) == 1 and len(pr[0]) == 1:
74  print (pr)
75  pr = pr[0]
76  print ("parsed:",type(pr), pr)
77  if isinstance(pr, ParseResults):
78  r = rule.Rule(pr, return_bool=True)
79  print("rule:",r)
80  result = r.match()
81  print (f'Rule result: "{toparse}" on {params} gives {result}')
82  else:
83  result = True if pr else False
84  print (f'Literal result: "{toparse}" on {params} gives {result}')
85 
86  assert(want == result)
87  print ()
88 
89 
90 if '__main__' == __name__:
91  test()
92 
def dump_parsed(pr)
Definition: lispish.py:32
def test()
Definition: lispish.py:36
def parser(params=None)
Definition: lispish.py:5