-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathlang.py
700 lines (515 loc) · 20.5 KB
/
lang.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
from . import engine, logger
class avalue(object):
def __init__(self, name, left = None, sid = None, op = None, right = None):
self._name = name
self._left = left
self._sid = sid
self._op = op
self._right = right
def __add__(self, other):
return self._set_right('$add', other)
def __sub__(self, other):
return self._set_right('$sub', other)
def __mul__(self, other):
return self._set_right('$mul', other)
def __div__(self, other):
return self._set_right('$div', other)
def __truediv__(self, other):
return self._set_right('$div', other)
def __lshift__(self, other):
other.alias = self._name
return other
def __getattr__(self, name):
if self._left:
self._left = '{0}.{1}'.format(self._left, name)
else:
self._left = name
return self
def __lt__(self, other):
raise Exception('Only binary arithmetic operators supported')
def __le__(self, other):
raise Exception('Only binary arithmetic operators supported')
def __gt__(self, other):
raise Exception('Only binary arithmetic operators supported')
def __ge__(self, other):
raise Exception('Only binary arithmetic operators supported')
def __eq__(self, other):
raise Exception('Only binary arithmetic operators supported')
def __ne__(self, other):
raise Exception('Only binary arithmetic operators supported')
def __neg__(self):
raise Exception('Only binary arithmetic operators supported')
def __pos__(self):
raise Exception('Only binary arithmetic operators supported')
def _set_right(self, op, other):
if self._right:
self._left = avalue(self._name, self._left, self._sid, self._op, self._right)
self._op = op
self._right = other
return self
def define(self, parent_name = None):
if not self._left:
raise Exception('Property name for {0} not defined'.format(self._name))
if self._name == '$s':
raise Exception('s not allowed as rvalue')
if not self._op:
if self._sid:
return {self._name: {'name': self._left, 'id': self._sid}}
else:
return {self._name: self._left}
left_definition = None
if isinstance(self._left, avalue):
left_definition = self._left.define()
else:
left_definition = {self._name: self._left}
righ_definition = self._right
if isinstance(self._right, avalue):
righ_definition = self._right.define()
return {self._op: {'$l': left_definition, '$r': righ_definition}}
class closure(object):
def __getattr__(self, name):
return avalue(name)
class value(object):
def __init__(self, vtype = None, left = None, op = None, right = None, alias = None):
self.alias = alias
self._type = vtype
self._left = left
self._op = op
self._right = right
def __lt__(self, other):
return value(self._type, self._left, '$lt', other, self.alias)
def __le__(self, other):
return value(self._type, self._left, '$lte', other, self.alias)
def __gt__(self, other):
return value(self._type, self._left, '$gt', other, self.alias)
def __ge__(self, other):
return value(self._type, self._left, '$gte', other, self.alias)
def __eq__(self, other):
return value(self._type, self._left, '$eq', other, self.alias)
def __ne__(self, other):
return value(self._type, self._left, '$neq', other, self.alias)
def __neg__(self):
return value(self._type, self._left, '$nex', None, self.alias)
def __pos__(self):
return value(self._type, self._left, '$ex', None, self.alias)
def allItems(self, other):
return value(self._type, self._left, '$iall', other, self.alias)
def anyItem(self, other):
return value(self._type, self._left, '$iany', other, self.alias)
def matches(self, other):
return value(self._type, self._left, '$mt', other, self.alias)
def imatches(self, other):
return value(self._type, self._left, '$imt', other, self.alias)
def __and__(self, other):
return value(self._type, self, '$and', other, self.alias)
def __or__(self, other):
return value(self._type, self, '$or', other, self.alias)
def __add__(self, other):
return avalue(self._type, self._left, None, '$add', other)
def __sub__(self, other):
return avalue(self._type, self._left, None, '$sub', other)
def __mul__(self, other):
return avalue(self._type, self._left, None, '$mul', other)
def __div__(self, other):
return avalue(self._type, self._left, None, '$div', other)
def __truediv__(self, other):
return avalue(self._type, self._left, None, '$div', other)
def __getattr__(self, name):
if self._type:
if self._left:
return value(self._type, '{0}.{1}'.format(self._left, name))
else:
return value(self._type, name)
else:
return value(self.alias, name)
def define(self):
if not self._left:
raise Exception('Property name for {0} not defined'.format(self._type))
new_definition = None
right_definition = self._right
if isinstance(self._right, value) or isinstance(self._right, avalue):
right_definition = right_definition.define();
if self._op == '$or' or self._op == '$and':
left_definition = self._left.define()
if not self._op in left_definition:
left_definition = [left_definition, right_definition]
else:
left_definition = left_definition[self._op]
left_definition.append(right_definition)
new_definition = {self._op: left_definition}
elif self._op == '$nex' or self._op == '$ex':
new_definition = {self._op: {self._left: 1}}
elif self._op == '$eq':
new_definition = {self._left: right_definition}
elif not self._op:
if self._type == '$s':
raise Exception('s not allowed as rvalue')
logger.debug('defining %s, %s', self._type, self._left)
new_definition = {self._type: self._left}
else:
new_definition = {self._op: {self._left: right_definition}}
if self._type == '$s':
return {'$and': [new_definition, {'$s': 1}]}
else:
return new_definition
class run(object):
def __init__(self, func):
if len(_rule_stack) > 0:
_rule_stack[-1].func = [func]
else:
raise Exception('Invalid rule context')
self.func = func
class rule(object):
def __init__(self, operator, multi, *args):
self.operator = operator
self.multi = multi
self.alias = None
if len(_ruleset_stack) and isinstance(_ruleset_stack[-1], ruleset):
_ruleset_stack[-1].rules.append(self)
if not len(args):
raise Exception('Invalid number of arguments')
self.count = None
self.pri = None
self.cap = None
self.dist = None
self.func = []
new_args = []
for arg in args:
if isinstance(arg, dict):
if 'count' in arg:
self.count = arg['count']
elif 'pri' in arg:
self.pri = arg['pri']
elif 'cap' in arg:
self.cap = arg['cap']
elif 'dist' in arg:
self.dist = arg['dist']
else:
self.func = arg
elif isinstance(arg, value) or isinstance(arg, rule):
new_args.append(arg)
else:
self.func = arg
if not multi:
self.expression = new_args[0]
else:
self.expression = new_args
def __enter__(self):
_rule_stack.append(self)
def __exit__(self, exc_type, exc_value, traceback):
_rule_stack.pop()
def __call__(self, *args):
if (len(args) == 1 and hasattr(args[0], '__call__')):
self.func = [args[0]]
return self
def define(self, parent_name = None):
defined_expression = None
if not self.multi:
defined_expression = self.expression.define()
else:
index = 0
defined_expression = []
for current_expression in self.expression:
new_expression = None
name = None
if current_expression.alias:
name = current_expression.alias
elif len(self.expression) == 1:
if parent_name:
name = '{0}.m'.format(parent_name)
else:
name = 'm'
else:
if parent_name:
name = '{0}.m_{1}'.format(parent_name, index)
else:
name = 'm_{0}'.format(index)
if isinstance(current_expression, all):
new_expression = {'{0}$all'.format(name): current_expression.define(name)['all']}
elif isinstance(current_expression, any):
new_expression = {'{0}$any'.format(name): current_expression.define(name)['any']}
elif isinstance(current_expression, none):
new_expression = {'{0}$not'.format(name): current_expression.define()['none'][0]['m']}
else:
new_expression = {name: current_expression.define()}
defined_expression.append(new_expression)
index += 1
if len(self.func):
if len(self.func) == 1 and not hasattr(self.func[0], 'define'):
defined_expression = {self.operator: defined_expression, 'run': self.func[0]}
elif self.operator:
defined_expression = {self.operator: defined_expression}
if self.count:
defined_expression['count'] = self.count
if self.pri:
defined_expression['pri'] = self.pri
if self.cap:
defined_expression['cap'] = self.cap
if self.dist == True:
defined_expression['dist'] = 1
if self.dist == False:
defined_expression['dist'] = 0
return defined_expression
class when_all(rule):
def __init__(self, *args):
super(when_all, self).__init__('all', True, *args)
class when_any(rule):
def __init__(self, *args):
super(when_any, self).__init__('any', True, *args)
class all(rule):
def __init__(self, *args):
_ruleset_stack.append(self)
super(all, self).__init__('all', True, *args)
_ruleset_stack.pop()
class any(rule):
def __init__(self, *args):
_ruleset_stack.append(self)
super(any, self).__init__('any', True, *args)
_ruleset_stack.pop()
class none(rule):
def __init__(self, *args):
_ruleset_stack.append(self)
super(none, self).__init__('none', True, *args)
_ruleset_stack.pop()
class when_start(object):
def __init__(self, func):
if isinstance(_ruleset_stack[-1], ruleset):
_ruleset_stack[-1].rules.append(self)
elif isinstance(_ruleset_stack[-1], statechart):
_ruleset_stack[-1].states.append(self)
elif isinstance(_ruleset_stack[-1], flowchart):
_ruleset_stack[-1].stages.append(self)
self.func = func
def __call__(self, *args):
return self.func(*args)
class ruleset(object):
def __init__(self, name):
self.name = name
self.rules = []
if not len(_ruleset_stack):
_rulesets[name] = self
elif len(_rule_stack) > 0:
_rule_stack[-1].func.append(self)
else:
raise Exception('Invalid rule context')
def __enter__(self):
_ruleset_stack.append(self)
def __exit__(self, exc_type, exc_value, traceback):
_ruleset_stack.pop()
def define(self):
index = 0
new_definition = {}
for rule in self.rules:
new_definition['r_{0}'.format(index)] = rule.define()
index += 1
return self.name, new_definition
class to(object):
def __init__(self, state_name, func = None):
if not len(_ruleset_stack):
raise Exception('Invalid state context')
if isinstance(_ruleset_stack[-1], state):
_ruleset_stack[-1].triggers.append(self)
elif isinstance(_ruleset_stack[-1], stage):
_ruleset_stack[-1].switches.append(self)
else:
raise Exception('Invalid state context')
self.state_name = state_name
self.rule = None
self.func = func
def when_all(self, *args):
self.rule = rule('all', True, *args)
return self.rule
def when_any(self, *args):
self.rule = rule('any', True, *args)
return self.rule
def __call__(self, *args):
if len(args) == 1:
if isinstance(args[0], rule):
self.rule = args[0]
elif hasattr(args[0], '__call__'):
self.func = args[0]
return self
def define(self):
if self.rule:
return self.state_name, self.rule.define()
else:
if self.func:
return self.state_name, {'run': self.func}
else:
return self.state_name, None
class state(object):
def __init__(self, state_name):
if not len(_ruleset_stack):
raise Exception('Invalid statechart context')
if isinstance(_ruleset_stack[-1], state):
_ruleset_stack[-1].states.append(self)
elif isinstance(_ruleset_stack[-1], statechart):
_ruleset_stack[-1].states.append(self)
else:
raise Exception('Invalid statechart context')
self.state_name = state_name
self.triggers = []
self.states = []
def __enter__(self):
_ruleset_stack.append(self)
def __exit__(self, exc_type, exc_value, traceback):
_ruleset_stack.pop()
def define(self):
index = 0
new_definition = {}
for trigger in self.triggers:
trigger_to, trigger_rule = trigger.define()
if not trigger_rule:
trigger_rule = {}
trigger_rule['to'] = trigger_to
new_definition['t_{0}'.format(index)] = trigger_rule
index += 1
if len(self.states):
chart = {}
for state in self.states:
state_name, state_definition = state.define()
chart[state_name] = state_definition
new_definition['$chart'] = chart
return self.state_name, new_definition
class statechart(object):
def __init__(self, name):
self.name = name
self.states = []
self.root = True
if not len(_ruleset_stack):
_rulesets[name] = self
elif len(_rule_stack) > 0:
_rule_stack[-1].func.append(self)
else:
raise Exception('Invalid rule context')
def __enter__(self):
_ruleset_stack.append(self)
def __exit__(self, exc_type, exc_value, traceback):
_ruleset_stack.pop()
def define(self):
new_definition = {}
for state in self.states:
state_name, state_definition = state.define()
new_definition[state_name] = state_definition
return '{0}$state'.format(self.name), new_definition
class stage(object):
def __init__(self, stage_name, func = None):
if not len(_ruleset_stack) or not isinstance(_ruleset_stack[-1], flowchart):
raise Exception('Invalid flowchart context')
_ruleset_stack[-1].stages.append(self)
self.stage_name = stage_name
if func:
self.func = [func]
else:
self.func = []
self.switches = []
def __enter__(self):
_ruleset_stack.append(self)
_rule_stack.append(self)
def __exit__(self, exc_type, exc_value, traceback):
_ruleset_stack.pop()
_rule_stack.pop()
def define(self):
new_definition = {}
if len(self.func):
if len(self.func) == 1 and not hasattr(self.func[0], 'define'):
new_definition['run'] = self.func[0]
else:
ruleset_definitions = {}
for rset in self.func:
ruleset_name, ruleset_definition = rset.define()
ruleset_definitions[ruleset_name] = ruleset_definition
new_definition['run'] = ruleset_definitions
if (len(self.switches)):
to = {}
for switch in self.switches:
stage_name, switch_definition = switch.define()
if not switch_definition:
to = stage_name
break
elif 'all' in switch_definition:
switch_definition = {'all': switch_definition['all']}
elif 'any' in switch_definition:
switch_definition = {'any': switch_definition['any']}
to[stage_name] = switch_definition
new_definition['to'] = to
return self.stage_name, new_definition
class flowchart(object):
def __init__(self, name):
self.name = name
self.stages = []
if not len(_ruleset_stack):
_rulesets[name] = self
elif len(_rule_stack) > 0:
_rule_stack[-1].func.append(self)
else:
raise Exception('Invalid rule context')
def __enter__(self):
_ruleset_stack.append(self)
def __exit__(self, exc_type, exc_value, traceback):
_ruleset_stack.pop()
def define(self):
new_definition = {}
for stage in self.stages:
stage_name, stage_definition = stage.define()
new_definition[stage_name] = stage_definition
return '{0}$flow'.format(self.name), new_definition
def timeout(name):
return all(avalue('base') << value('$m', '$timerName') == name,
avalue('timeout') << value('$m', '$time') >= avalue('base', '$baseTime'))
def count(value):
return {'count': value}
def pri(value):
return {'pri': value}
def cap(value):
return {'cap': value}
def distinct(value):
return {'dist': value}
def select(name):
if name in _rulesets:
return _rulesets[name]
raise Exception('Ruleset {0} not found'.format(name))
m = value('$m')
s = value('$s')
item = value('$i', '$i')
c = closure()
_rule_stack = []
_ruleset_stack = []
_rulesets = {}
_main_host = None
def get_host():
global _main_host
global _rulesets
if not _main_host:
_main_host = engine.Host()
try:
ruleset_definitions = {}
for name, rset in _rulesets.items():
full_name, ruleset_definition = rset.define()
ruleset_definitions[full_name] = ruleset_definition
_main_host.register_rulesets(ruleset_definitions)
finally:
_rulesets = {}
return _main_host
def post(ruleset_name, message, complete = None):
return get_host().post(ruleset_name, message, complete)
def post_batch(ruleset_name, messages, complete = None):
return get_host().post_batch(ruleset_name, messages, complete)
def assert_fact(ruleset_name, fact, complete = None):
return get_host().assert_fact(ruleset_name, fact, complete)
def assert_facts(ruleset_name, facts, complete = None):
return get_host().assert_facts(ruleset_name, facts, complete)
def retract_fact(ruleset_name, fact, complete = None):
return get_host().retract_fact(ruleset_name, fact, complete)
def retract_facts(ruleset_name, facts, complete = None):
return get_host().retract_facts(ruleset_name, facts, complete)
def update_state(ruleset_name, state, complete = None):
get_host().update_state(ruleset_name, state, complete)
def get_state(ruleset_name, sid = None):
return get_host().get_state(ruleset_name, sid)
def delete_state(ruleset_name, sid = None):
get_host().delete_state(ruleset_name, sid)
def get_facts(ruleset_name, sid = None):
return get_host().get_facts(ruleset_name, sid)
def get_pending_events(ruleset_name, sid = None):
return get_host().get_pending_events(ruleset_name, sid)