-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathppl_symbol_simplifier.py
executable file
·74 lines (67 loc) · 2.38 KB
/
ppl_symbol_simplifier.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
#
# This file is part of PyFOPPL, an implementation of a First Order Probabilistic Programming Language in Python.
#
# License: MIT (see LICENSE.txt)
#
# 20. Mar 2018, Tobias Kohn
# 21. Mar 2018, Tobias Kohn
#
from ..ppl_ast import *
from ..aux.ppl_transform_visitor import TransformVisitor
class SymbolSimplifier(TransformVisitor):
def __init__(self):
super().__init__()
self.names_map = {}
self.name_count = {}
def simplify_symbol(self, name: str):
if name in self.names_map:
return self.names_map[name]
elif name.startswith('__'):
if '____' in name:
short = name[:name.index('____')+2]
if short not in self.name_count:
self.name_count[short] = 1
else:
self.name_count[short] += 1
short += "_{}".format(self.name_count[short])
self.names_map[name] = short
return short
else:
return name
elif '__' in name:
short = name[:name.index('__')]
if short not in self.name_count:
self.name_count[short] = 1
else:
self.name_count[short] += 1
short += "_{}".format(self.name_count[short])
self.names_map[name] = short
return short
else:
self.names_map[name] = name
if name not in self.name_count:
self.name_count[name] = 1
else:
self.name_count[name] += 1
return name
def visit_def(self, node: AstDef):
value = self.visit(node.value)
name = self.simplify_symbol(node.name)
if name != node.name or value is not node.value:
return node.clone(name=name, value=value)
else:
return node
def visit_let(self, node: AstLet):
source = self.visit(node.source)
name = self.simplify_symbol(node.target)
body = self.visit(node.body)
if name == node.target and source is node.source and body is node.body:
return node
else:
return node.clone(target=name, source=source, body=body)
def visit_symbol(self, node: AstSymbol):
name = self.simplify_symbol(node.name)
if name != node.name:
return node.clone(name=name)
else:
return node