• R/O
  • SSH

提交

标签
No Tags

Frequently used words (click to add to your profile)

javac++androidlinuxc#windowsobjective-ccocoa誰得qtpythonphprubygameguibathyscaphec計画中(planning stage)翻訳omegatframeworktwitterdomtestvb.netdirectxゲームエンジンbtronarduinopreviewer

Commit MetaInfo

修订版4679c0e5b14a0163c03e58c74358357b7753e6c6 (tree)
时间2013-12-22 21:49:43
作者Albert Mietus < albert AT ons-huis DOT net >
CommiterAlbert Mietus < albert AT ons-huis DOT net >

Log Message

added try6

更改概述

差异

diff -r 17bddb44a5ef -r 4679c0e5b14a compiler/py/TryOut/IPyNb/Try5.py
--- a/compiler/py/TryOut/IPyNb/Try5.py Sun Dec 22 11:50:08 2013 +0100
+++ b/compiler/py/TryOut/IPyNb/Try5.py Sun Dec 22 13:49:43 2013 +0100
@@ -192,68 +192,4 @@
192192
193193 # <codecell>
194194
195-aSym=xxx_sym[0][0]
196-print "name:", aSym.getName(), "type=", type(aSym)
197-print "qualified name:", aSym.getName(qualified=True), "type=", type(aSym)
198-
199-# <codecell>
200-
201-aSym.name
202-
203-# <codecell>
204-
205-for node,_,_ in ast2.walk_ast():
206- try: name = node.getName(True)
207- except AttributeError: continue
208- if not isinstance(name, tuple): name = list(name) # Expand the generators
209- if not isinstance(name[0], basestring):
210- print "NotAStr %-35s %s" %( repr(name[0]), type(node))
211-
212-# <codecell>
213-
214-for node,_,_ in ast2.walk_ast():
215- try: name = node.getName(False)
216- except AttributeError: continue
217- if not ( (name == name.split()[0]) and (name == name.split('.')[0]) ):
218- print "NotAnID: %-40s %s" %( str(name)[:40], type(node)),
219-
220-
221-# <codecell>
222195
223-for node,_,_ in ast2.walk_ast():
224- try:
225- name = node.getName(False)
226- if not isinstance(name, basestring):
227- print "\n%-40s %-20s node=%s" %( str(name)[:40], type(name), type(node)),
228- else: print ".",
229- except AttributeError: pass
230-
231-# <codecell>
232-
233-for node,_,_ in ast2.walk_ast():
234- try:
235- name = node.getName(False)
236- print "\n%-40s node=%s" %( str(name)[:40], type(node)),
237- except AttributeError: pass
238-
239-# <codecell>
240-
241-nodes[1]
242-
243-# <codecell>
244-
245-foo= nodes[1].name
246-foo
247-
248-# <codecell>
249-
250-tuple((foo,))
251-
252-# <codecell>
253-
254-foo="aap beer"
255-foo.split()[0]
256-
257-# <codecell>
258-
259-
diff -r 17bddb44a5ef -r 4679c0e5b14a compiler/py/TryOut/IPyNb/Try6.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/compiler/py/TryOut/IPyNb/Try6.py Sun Dec 22 13:49:43 2013 +0100
@@ -0,0 +1,179 @@
1+# -*- coding: utf-8 -*-
2+# <nbformat>3.0</nbformat>
3+
4+# <markdowncell>
5+
6+# Config
7+# ======
8+
9+# <codecell>
10+
11+#SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/Typing.Castle"
12+#SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/small.Castle"
13+#SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/try.Castle" # REF CODE
14+SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/very_small.Castle"
15+#SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/qaz.Castle"
16+
17+#LOGLEVEL= DEBUG/INFO/WARNING/ERROR/CRITICAL
18+#LOGLEVEL="INFO"
19+global LOGLEVEL
20+
21+LOGLEVEL="DEBUG"
22+
23+
24+print "Last run on:", datetime.datetime.now().isoformat(' ')
25+
26+# <markdowncell>
27+
28+# Set-up
29+# -------
30+# Run some shared stuff: the (development) directories are added to pypath; GV (and debug_GV) to show an AST2.
31+#
32+# And the logging modules has to be initialized (see Config section for LOGLEVEL)
33+#
34+# Also, load try6_walk (*%load* will import python-filesinto the current-namespace, everytime)
35+
36+# <codecell>
37+
38+import logging
39+logging.basicConfig(format='** %(asctime)s %(levelname)-9s %(module)20s::%(funcName)-20s\n\t# %(message)s', level=LOGLEVEL)
40+
41+# <codecell>
42+
43+import sys
44+%run ./shared_stuff
45+
46+%run ../NS/try6_walk
47+
48+# <markdowncell>
49+
50+# Start experiment (Try5)
51+# =======================
52+
53+# <codecell>
54+
55+from donjon.sdg.namespace import NameSpace
56+from donjon.ast import *
57+
58+def mk_FooTypes():
59+ hack=NameSpace(node=None, parent=None, infoName="FooHack_XXX_")
60+
61+ for t in ('Foo',):
62+ hack.defineSymbol(types.Type(t))
63+
64+ return hack
65+
66+# <markdowncell>
67+
68+# Load an run TryCode
69+# --------------------
70+#
71+# Load the try5_*Types* file. And reimplement `main()`; this way we can experiment and reach the local-vars.
72+#
73+# * Load and parse the source file (or an picked version) _The SOUREFILE is defined in the config-part, above_
74+# * Define the global and builtins namespace. The latter hold all standard types, BuildingBlocks, Callable's etc
75+# * Find the scopes (creating empty namespaces), fill those namespaces
76+# * Resolve all symbols.
77+#
78+# Show the steps graphicly, when LOGLEVEL is "DEBUG"
79+
80+# <codecell>
81+
82+import donjon.aux.parseLib as parseLib
83+import try5_Types as try5
84+
85+ast2=parseLib.read_ast2(SOURCEFILE)
86+
87+FooHack = mk_FooTypes()
88+
89+builtins=try5.mk_builtins(FooHack)
90+global_ns=try5.add_namespace(ast2, parent_ns=builtins, infoName="GLOBAL")
91+
92+try5.find_scopes(ast2, global_ns)
93+try5.fill_namespaces(ast2, global_ns)
94+
95+try5.build_symrefs(ast2, global_ns)
96+
97+# <markdowncell>
98+
99+# Some experiments
100+# ----------------
101+# Show the resulted AST (or is it an SDG already?)
102+
103+# <codecell>
104+
105+GV(ast2)
106+
107+# <codecell>
108+
109+from IPython.core.display import display
110+
111+# <codecell>
112+
113+display
114+
115+# <markdowncell>
116+
117+# Show nodes that *need work*
118+# ---------------------------
119+#
120+# They are marked with attribute _.xxx_
121+
122+# <codecell>
123+
124+def show_xxx(some_nke):
125+ FORMAT="{node:<50}|{pl:>2}| {dad}"
126+ print FORMAT.format(node="NODE", pl="PL", dad="PARENT-node (last of path)")
127+ for (node,kids,env) in some_nke:
128+ print FORMAT.format(node=graphviz._GVlabel(node),
129+ pl=len(env['path']),
130+ dad=graphviz._GVlabel(env['path'][-1],55))
131+
132+# <codecell>
133+
134+import donjon
135+xxx_nodes = [(n,k,e) for n,k,e in ast2.walk_ast() if n.__dict__.get('xxx')]
136+show_xxx(xxx_nodes)
137+if len(xxx_nodes) == 0: print "Found NO nodes that need attention"
138+
139+# <codecell>
140+
141+xxx_sym = [(n,k,e) for n,k,e in ast2.walk_ast()
142+ if n.__dict__.get('xxx') and not isinstance(n, donjon.ast.symbols.SymbolBase)]
143+show_xxx(xxx_sym)
144+
145+# <headingcell level=3>
146+
147+# More experiments
148+
149+# <headingcell level=4>
150+
151+# NSS: All namespaces
152+
153+# <codecell>
154+
155+nss = set(env['ns'] for (n,k,env) in ast2.walk_ast())
156+nss.discard(None)
157+while nss is not None:
158+ more = set(ns.parent for ns in nss if ns.parent not in nss)
159+ more.discard(None)
160+ if len(more) == 0: break
161+ nss.update(more)
162+
163+# <codecell>
164+
165+for ns in nss:
166+ print ns.infoName
167+ for sym in ns.dict:
168+ print "\t", sym
169+
170+# <codecell>
171+
172+
173+# <headingcell level=4>
174+
175+# XXX
176+
177+# <codecell>
178+
179+
diff -r 17bddb44a5ef -r 4679c0e5b14a compiler/py/TryOut/IPyNb/getName_BUG_check.py
--- a/compiler/py/TryOut/IPyNb/getName_BUG_check.py Sun Dec 22 11:50:08 2013 +0100
+++ b/compiler/py/TryOut/IPyNb/getName_BUG_check.py Sun Dec 22 13:49:43 2013 +0100
@@ -10,8 +10,8 @@
1010
1111 #SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/Typing.Castle"
1212 #SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/small.Castle"
13-#SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/try.Castle" # REF CODE
14-SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/very_small.Castle"
13+SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/try.Castle" # REF CODE
14+#SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/very_small.Castle"
1515 #SOURCEFILE="/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/qaz.Castle"
1616
1717 #LOGLEVEL= DEBUG/INFO/WARNING/ERROR/CRITICAL
@@ -85,7 +85,7 @@
8585 except AttributeError: continue
8686 if not isinstance(name, tuple): name = list(name) # Expand the generators
8787 if not isinstance(name[0], basestring):
88- print "NotAStr:\t%-40s %s" %( repr(name[0]), type(node))
88+ print "NotAStr: %-40s %s" %( repr(name[0]), type(node))
8989
9090 # <codecell>
9191
@@ -93,7 +93,9 @@
9393 try: name = node.getName(False)
9494 except AttributeError: continue
9595 if not ( (name == name.split()[0]) and (name == name.split('.')[0]) ):
96- print "NotAnID:\t%-40s %s" %( str(name)[:40], type(node)),
96+ print "NotAnID: %-40s %s" %( str(name)[:40], type(node))
97+
98+# <codecell>
9799
98100
99101 # <codecell>
diff -r 17bddb44a5ef -r 4679c0e5b14a compiler/py/TryOut/IPyNb/shared_stuff.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/compiler/py/TryOut/IPyNb/shared_stuff.py Sun Dec 22 13:49:43 2013 +0100
@@ -0,0 +1,58 @@
1+# -*- coding: utf-8 -*-
2+# <nbformat>3.0</nbformat>
3+
4+# <markdowncell>
5+
6+# shared_stuff
7+# ============
8+#
9+# This (kind of) *module* can be *imported* by other Notebook/Ipython script by **%run** `path/`**shared_stuff**.
10+#
11+# This only works when it is converted to python-code; so use `--script`! Also, no ipython-magic is allowed, so use pure python code.
12+
13+# <headingcell level=2>
14+
15+# Be able to import all CC-Castle modules
16+
17+# <codecell>
18+
19+import sys
20+
21+sys.path.append("/Users/albert/work/CC-Castle/TRUNK/compiler/py")
22+sys.path.append("/Users/albert/work/CC-Castle/TRUNK/compiler/external")
23+sys.path.append("/Users/albert/work/CC-Castle/TRUNK/compiler/py/tools")
24+sys.path.append("/Users/albert/work/CC-Castle/TRUNK/compiler/py/TryOut/NS/")
25+
26+# <headingcell level=2>
27+
28+# Show the AST2 with (debug_)`GV`
29+
30+# <codecell>
31+
32+import donjon.aux.graphviz as graphviz
33+from IPython.display import SVG, display
34+
35+import tempfile
36+import subprocess
37+
38+tmpdir=tempfile.mkdtemp(suffix='__Castle__', prefix='TMP.', dir='.')
39+
40+# <codecell>
41+
42+def GV(ast,filename=None):
43+ global tmpdir
44+ if not filename: filename=tempfile.mktemp(dir=tmpdir,suffix=".gv", prefix="OUT_%s_" % graphviz._GVid(ast))
45+ file(filename,'w').write(graphviz.dumpGV(ast,header=True))
46+
47+ subprocess.call(['dot', '-O', '-Tsvg', '%s' % filename])
48+
49+ print filename
50+ display(SVG(filename=filename+'.svg'))
51+
52+def GV_debug(*l,**kw):
53+ if logging.getLogger().isEnabledFor(logging.DEBUG):
54+ GV(*l,**kw)
55+
56+# <codecell>
57+
58+
diff -r 17bddb44a5ef -r 4679c0e5b14a compiler/py/TryOut/NS/try6_walk.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/compiler/py/TryOut/NS/try6_walk.py Sun Dec 22 13:49:43 2013 +0100
@@ -0,0 +1,219 @@
1+# Copyright (C) ALbert Mietus, SoftwareBeterMaken.nl; 2013. Part of Castle-project
2+
3+"""In try5_Types.py, most of the type problesm ar solved. Now continue on walking the ast and buildng the SGD.
4+ As with try5, there is an IPyNotebook (See /../IPyNb/Try6*) to experiment; but now from the start . This mean "main" is less importante
5+"""
6+
7+import sys
8+
9+from donjon.aux.parseLib import *
10+from donjon.ast import *
11+from donjon.sdg.namespace import NameSpace
12+from donjon.sdg import vsymbols
13+
14+import logging
15+
16+HAS_OWN_SCOPE = ( component.Component,
17+ implementation.ImplementationBase, # implement, callable's etc
18+ protocol.Protocol, protocol.ProtocolKindBase, # Event, for now
19+ statement.Body, statement.For, # for: itor
20+ )
21+
22+NEW_SYM = ( member.MemberBase, # sub, alias, vardef, ..
23+ component.ComponentKindBase,
24+ protocol.ProtocolKindBase, # Event and such
25+ ) # new symbols (all have .name attr)
26+
27+VIRT_PROT = ( protocol.Protocol,)
28+VIRT_COMP = ( component.Component, implementation.Implement)
29+VIRTSYM = VIRT_PROT + VIRT_COMP
30+
31+HAS_PARMS = (implementation.CallableWithBodyBase, protocol.Event) #All Callables can have parameters (Also EventDef?
32+PORT_HANDLERS = (implementation.EventHandler, implementation.DataHandler) # Event/data handlers have a port with is a kind of parameter (but are QualIDs)
33+HAS_SELF = (implementation.Implement,)
34+
35+###
36+### Aux
37+###
38+
39+def shorten(s, MAX_LENGTH=50):
40+ retval = str(s).replace('"',r'\"').replace('\n','').replace('\t','')
41+ if len(retval) > MAX_LENGTH: retval = retval[:MAX_LENGTH-3]+'...'
42+ return retval
43+
44+def log(node, tag="XXX ", *xtra, **kw):
45+ label=shorten(repr(node))
46+ level=logging._checkLevel(kw.get('level',"DEBUG"))
47+ logging.log(level, ("{:>10} {:>2} {:<50}".format(tag,node._node_no(), label) +
48+ " ".join([str(e) for e in xtra])))
49+
50+allNSs=[]
51+def add_namespace(node, parent_ns=None, infoName=None):
52+ if node.__dict__.get('namespace') is not None:
53+ log(node, "SKIP", "Does already have a namespace set")
54+ return None
55+ new_ns = NameSpace(parent=parent_ns, node=node, infoName=infoName)
56+ allNSs.append(new_ns)
57+ node.namespace = new_ns
58+ return new_ns
59+
60+###
61+### Walk over tree, add a NS where needed
62+###
63+def find_scopes(tree, current_ns):
64+ for node,descendants,env in tree.walk_ast(): # OK-walk (due del descendants & recursieve call)
65+ if node is tree: continue # Already done :-)
66+
67+ if isinstance(node, HAS_OWN_SCOPE):
68+ namespace = add_namespace(node, current_ns)
69+ log(node, 'NEW_NS', namespace)
70+
71+ del descendants[:] # No need to continue this walk ...
72+ find_scopes(node, namespace) # .. as that sub-tree has it own scope-walker
73+
74+
75+def fill_namespaces(tree, ns):
76+ if not isinstance(tree, astBase.ASTBase): return; ### Solve in AST/types
77+ node, kids = tree, tree._descendants()
78+ if isinstance(node, NEW_SYM): defsym_new_sym(node,ns)
79+ if isinstance(node, VIRTSYM): defsym_virtsym(node,ns)
80+ if isinstance(node, HAS_SELF): defsym_self_symbol(node, ns) # Note: self doesn't exist in AST2! XXX
81+ if isinstance(node, HAS_PARMS): defsym_has_parms(node, ns)
82+
83+ try: ns=node.namespace;
84+ except AttributeError: pass # keep using the same/inherited namespace
85+ #else: log(tree,"set NS", ns)
86+ for n in kids: fill_namespaces(n,ns)
87+
88+
89+##################################################
90+###
91+### defsym_*::
92+### define all kind of symbols into the correctly scoped namespace
93+###
94+
95+def defsym_new_sym(node, ns):
96+ ns.defineSymbol(node)
97+ log(node, "NEW_SYM",ns)
98+
99+def defsym_has_parms(node, ns):
100+ try: ns=node.namespace;
101+ except AttributeError: pass # keep using the same/inherited namespace
102+ # else: log(node,"set NS", ns)
103+
104+ log(node,'HAS_PARMS', ns)
105+ parms = node.parameterTuple.elms
106+ for elm in parms:
107+ log(elm.name, "PARM_SYM", ns)
108+ ns.defineSymbol(elm)
109+
110+
111+def defsym_self_symbol(node, ns): # Use NS off node, not passed NS!
112+ ns=node.namespace
113+ ns.defineSymbol(symbols.SelfID(),node)
114+ log(node, 'Self', ns, "added SelfID(); XXX This pseudo-node isn't part of the tree!")
115+
116+
117+def defsym_virtsym(node,ns):
118+ if isinstance(node, VIRT_PROT):
119+ log(node, "VIRT_PROT",ns)
120+ ns.defineSymbol(node); # XXX TMP
121+ elif isinstance(node, VIRT_COMP):
122+ vsym = ns.checkName(node, hierarchical=False)
123+ if vsym is None:
124+ vsym = vsymbols.SymbComp(node.getName(), node)
125+ ns.defineSymbol(vsym)
126+ log(node, "VIRT_COMP1",ns, shorten(repr(vsym),25), "1st site=",shorten(repr(node),25))
127+ else:
128+ vsym.add_other(side=node)
129+ log(node, "VIRT_COMP2",ns, repr(vsym), "2nd side=",shorten(repr(node),25))
130+ else:
131+ log(node, "ERROR", "XXX Don't know how to handle this virtual symbol")
132+
133+
134+
135+
136+def build_symrefs(tree, ns):
137+ for node,descendants,env in tree.walk_ast():
138+ ns=env.get('ns')
139+ if not ns: continue # For as long ns=None
140+
141+ if isinstance(node, PORT_HANDLERS): findsym_port_of_handler(node, ns) # ?
142+ if isinstance(node, (symbols.NameID, symbols.QualID, types.Type)):
143+ sym = ns.checkName(node)
144+ if sym:
145+ if sym is not node:
146+ node.ref = sym # Add a ref!
147+ log(node, "FOUND", "as:", sym._node_no(), repr(sym))
148+ else: log(node, "ME FOUND", "As it is I;-)")
149+ else:
150+ log(node, "NOT1 FOUND","XXX")
151+ node.xxx = ',style=radial, fillcolor="red:maroon"'
152+
153+
154+
155+def findsym_port_of_handler(node, ns): # XXX
156+ port = node.port # Note: a port is a QualID, not a NameID!
157+ log(port, "XXX PORT", "XXX HOW TO STORE THIS?\t\t")
158+ node.xxx = ',style=radial, fillcolor="red:pink"'
159+
160+
161+
162+def mk_builtins(parent=None):
163+ builtins=NameSpace(node=None, parent=parent, infoName="__builtins__")
164+
165+ for t in ('float', 'complex', 'int', 'char', 'string', 'bool', 'type', 'void', 'kind'): # Types
166+ builtins.defineSymbol(types.Type(t))
167+
168+ for bbs in ('Component', 'Protocol', 'Port','Implement'): # BuildingBlockSymbol?
169+ builtins.defineSymbol(symbols.NameID(name=bbs))
170+
171+ for c in ('function', 'event', 'stream', 'data'): # Callable?
172+ builtins.defineSymbol(symbols.NameID(name=c))
173+
174+ for c in ('self', 'super'): # Keywords? XXX
175+ builtins.defineSymbol(symbols.NameID(name=c))
176+
177+ return builtins
178+
179+###
180+### Main
181+###
182+
183+def main(filenames):
184+ fails=[]
185+ for fn in filenames:
186+ try:
187+ out_file = "./OUT_" + str(int(sys.argv[0].split('_')[0][3:])) + "." + fn.split("/")[-1] + ATS2_PICKLE_EXT
188+
189+ logging.info("Going to read the ast2, from: %s ..." % fn)
190+ ast2 = read_ast2(fn)
191+
192+ logging.info("Building builtins+GLOBAL namespace")
193+ builtins=mk_builtins()
194+ global_ns=add_namespace(ast2, parent_ns=builtins, infoName="GLOBAL")
195+
196+ logging.info("Going to: find_scopes() ...")
197+ find_scopes(ast2, global_ns)
198+
199+ logging.info("Going to: fill_namespace() # NS.defineSymbol// defsym_*) ...")
200+ fill_namespaces(ast2, global_ns)
201+
202+ logging.info("Going to: build_symrefs() ...")
203+ build_symrefs(ast2, global_ns)
204+
205+ # Save the result
206+ logging.info("Work done. Going to save result: %s" % out_file)
207+ ast2_pickle(ast2, out_file)
208+
209+ except Exception as e:
210+ logging.error("Something got wrong in file: %s (error=%s). Continue... (with next file)" % (fn,e))
211+ fails.append((fn,e))
212+
213+ if len(fails) >0:
214+ sys.exit(-1)
215+
216+
217+if __name__ == "__main__":
218+ logging.basicConfig(format='** %(asctime)s %(levelname)-9s %(module)20s::%(funcName)-20s \t# %(message)s', level=logging.INFO)
219+ main(sys.argv[1:])