-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpynxc.pyw
executable file
·1393 lines (1016 loc) · 38.4 KB
/
pynxc.pyw
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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from __future__ import with_statement
__author__ = 'Brian Blais <[email protected]>'
__version__ = (0,1,6)
import ast_template
import sys
from compiler import parse, walk
from compiler.consts import *
from waxy import *
import os
import subprocess
from optparse import OptionParser
import re
import yaml
pynxc_root,junk=os.path.split(sys.argv[0])
#pynxc_root=os.getcwd()
class MyObject(object):
def __init__(self,name,type='default'):
self.name=name
self.type=type
self.datatype=None
self.value=None
self.variables=[]
def __repr__(self):
return self.type+" "+self.name+" of datatype "+self.datatype.__repr__()+" with value "+self.value.__repr__()
class Variable(MyObject):
def __init__(self,name,datatype='default'):
super(Variable,self).__init__(name,'variable')
self.datatype=datatype
class Function(MyObject):
def __init__(self,name,variables=[]):
super(Function,self).__init__(name,'function')
self.variables=variables
file_lines=[]
class SecondPassVisitor(ast_template.Visitor):
"""This object goes through and output the code"""
def __init__(self,fv,stream=sys.stdout,debug=False):
ast_template.Visitor.__init__(self,stream,debug)
self.fv=fv # first-pass visitor
self.stream=stream
self.erase_assign=False
self.buffer=[]
self.semicolon=True
self.writef('#include "NXCDefs.h"\n')
if os.path.exists("MyDefs.h"):
self.writef(open("MyDefs.h",'rt').read())
for d in fv.defines:
self.writef('#define %s %s\n' % (d[0],d[1]))
self.print_structure_definitions(fv.struct_types)
self.print_typedefs(fv.typedefs)
if self.debug:
print "Module Variables Printing "
self.print_variable_definitions(fv.functions['module'].variables)
self.scope=['module']
def type2str(self,datatype):
if datatype=='Integer':
return 'int'
elif datatype=='IntegerPtr':
return 'int&'
elif datatype=='Word':
return 'word'
elif datatype=='Long':
return 'long'
elif datatype=='Byte':
return 'byte'
elif datatype=='Short':
return 'short'
elif datatype=='String':
return 'string'
elif datatype=='Mutex':
return 'mutex'
elif datatype in self.fv.struct_types:
return datatype
else:
return 'int'
def print_typedefs(self,typedefs):
for types in typedefs:
self.write('typedef %s %s;' % (typedefs[types],types))
self.NEWLINE()
self.flush()
def print_structure_definitions(self,struct_types):
for key in struct_types:
self.write('struct %s ' % key)
self.INDENT()
variables=struct_types[key]
for var in variables:
self.write(self.type2str(variables[var].datatype))
self.write(' %s' % variables[var].name)
self.write(';')
self.NEWLINE()
self.DEDENT()
self.write(';')
self.NEWLINE()
def print_variable_definitions(self,variables):
for var in variables:
if self.debug:
print " Variable ",variables[var]
self.write(self.type2str(variables[var].datatype))
self.write(' %s' % variables[var].name)
if not variables[var].value is None:
if isinstance(variables[var].value,list):
self.write('[]')
if not variables[var].value==[]:
self.write('={')
for v in variables[var].value:
self.write(v.__repr__())
if not v == variables[var].value[-1]:
self.write(',')
self.write('}')
else:
val=variables[var].value.__repr__()
self.write('= %s' % val.replace("'",'"'))
self.write(';')
self.NEWLINE()
if variables[var].datatype in self.fv.struct_types:
variables2=self.fv.struct_types[variables[var].datatype]
for var2 in variables2:
if variables2[var2].value:
val2=variables2[var2].value.__repr__()
self.write('%s.%s' % (var,variables2[var2].name))
self.write('= %s' % val2.replace("'",'"'))
self.write(';')
self.NEWLINE()
self.flush()
def flush(self):
if self.buffer:
for s in self.buffer:
s=s.replace("'",'"')
self.stream.write(s)
self.buffer=[]
def DEDENT(self,with_semicolon=False):
self.indents -=1
self.NEWLINE()
self.write('}')
if with_semicolon:
self.write(';')
self.NEWLINE()
def INDENT(self):
self.indents += 1
self.write(' {')
self.NEWLINE()
def NEWLINE(self):
self.write('\n')
self.write(' ' * 4 * self.indents )
def write(self, data):
self.buffer.append(data)
def writef(self, data):
self.write(data)
self.flush()
def visitBlock(self, block):
self.INDENT()
self.v(block)
self.DEDENT()
def visitAdd(self, node):
self.write("(")
self.v(node.left)
self.write(" + ")
self.v(node.right)
self.write(")")
def visitAnd(self, node):
self.write("(")
for i in range(len(node.nodes)):
self.write("(")
self.v(node.nodes[i])
self.write(")")
if i < (len(node.nodes) - 1):
self.write(" && ")
self.write(")")
def visitAssAttr(self, node):
if self.debug:
print 'visitSecondVisitorAssAttr'
self.v(node.expr, self)
self.write(".%s" % node.attrname)
def visitAssName(self, node):
self.write(node.name)
def visitAssign(self, node):
self.flush()
self.erase_assign=False
n=node.nodes[0]
if self.scope[-1]=='module':
return
# try:
# if (n.name == n.name.upper()) and (len(n.name)>2): # a definition
# return
# except AttributeError:
# pass # probably a subscript?
for i in range(len(node.nodes)):
n = node.nodes[i]
self.v(n)
if i < len(node.nodes):
self.write(" = ")
self.v(node.expr)
self.write("; ")
self.NEWLINE()
if self.erase_assign:
self.buffer=[]
self.flush()
def visitAugAssign(self, node):
self.v(node.node)
self.write(" %s " % node.op)
self.v(node.expr)
self.write("; ")
self.NEWLINE()
def visitBitand(self, node):
for i in range(len(node.nodes)):
self.v(node.nodes[i])
if i < (len(node.nodes) - 1):
self.write(" & ")
def visitBitor(self, node):
for i in range(len(node.nodes)):
self.v(node.nodes[i])
if i < (len(node.nodes) - 1):
self.write(" | ")
def visitBitxor(self, node):
for i in range(len(node.nodes)):
self.v(node.nodes[i])
if i < (len(node.nodes) - 1):
self.write(" ^ ")
def visitBreak(self, node):
self.write("break; ")
self.NEWLINE()
def visitFunction(self, node):
self.scope.append('function')
hasvar = haskw = hasone = hasboth = False
ndefaults = len(node.defaults)
if node.flags & CO_VARARGS:
hasone = hasvar = True
if node.flags & CO_VARKEYWORDS:
hasone = haskw = True
hasboth = hasvar and haskw
kwarg = None
vararg = None
defargs = []
newargs = node.argnames[:]
if ndefaults:
for i in range(ndefaults):
defargs.append((newargs.pop(), node.defaults.pop()))
defargs.reverse()
func_type=self.fv.functions[node.name].datatype
if not func_type:
func_type='void'
if func_type=='default':
func_type='int'
if node.name=='main':
self.write("task %s(" % node.name)
elif node.name.find('task_')==0:
self.write("task %s(" % node.name)
elif node.name.find('sub_')==0:
self.write("sub %s(" % node.name)
elif node.name.find('inline_')==0:
self.write("inline %s %s(" % (func_type,node.name.replace('inline_','')))
else:
self.write("%s %s(" % (func_type,node.name))
for i in range(len(newargs)):
if isinstance(newargs[i], tuple):
self.write("(%s, %s)" % newargs[i])
else:
self.write("int "+newargs[i])
if i < len(newargs) - 1:
self.write(", ")
if defargs and len(newargs):
self.write(", ")
for i in range(len(defargs)):
name, default = defargs[i]
typename=default.node.name
self.write("%s %s" % (self.type2str(typename),name))
#self.v(default)
if i < len(defargs) - 1:
self.write(", ")
if vararg:
if (newargs or defargs):
self.write(", ")
self.write(vararg)
if kwarg:
if (newargs or defargs or vararg):
self.write(", ")
self.write(kwarg)
self.write(") ")
self.INDENT()
self.print_variable_definitions(self.fv.functions[node.name].variables)
self.v(node.code)
self.DEDENT()
self.flush()
self.scope.pop()
def visitCallFunc(self, node):
name=node.node.name
if name=="ASM": # raw ASM
s=node.args[0].value
self.write("asm{%s}" % s)
return
if name=="NXC":
s=node.args[0].value
self.write("%s" % s)
return
if name=="DEFINE":
s=node.args[1].value
d=node.args[0].value
self.write("#define %s %s" %(d,s))
self.NEWLINE()
self.semicolon=False
return
self.v(node.node)
self.write("(")
for i in range(len(node.args)):
self.v(node.args[i])
if i < (len(node.args) - 1):
self.write(", ")
if node.star_args:
if len(node.args):
self.write(", ")
self.write("*")
self.v(node.star_args)
if node.dstar_args:
if node.args or node.star_args:
self.write(", ")
self.write("**")
self.v(node.dstar_args)
self.write(")")
if name in self.fv.types:
self.erase_assign=True
def visitClass(self, node):
self.scope.append('class')
self.flush()
for i in range(len(node.bases)):
self.v(node.bases[i])
self.INDENT()
self.v(node.code)
self.DEDENT()
self.buffer=[] # get rid of all of the stuff in a class def
self.scope.pop()
def visitCompare(self, node):
self.write("(")
self.v(node.expr)
for operator, operand in node.ops:
self.write(" %s " % operator)
self.v(operand)
self.write(")")
def visitConst(self, node):
self.write(repr(node.value))
def visitContinue(self, node):
self.write("continue; ")
def visitDiscard(self, node):
self.semicolon=True
# deal with empty statements, so it doesn't print None
try:
if node.expr.value is None:
pass
else:
self.v(node.expr)
if self.semicolon:
self.write(";")
self.NEWLINE()
except AttributeError:
self.v(node.expr)
if self.semicolon:
self.write(";")
self.NEWLINE()
def visitDiv(self, node):
self.v(node.left)
self.write(" / ")
self.v(node.right)
def visitFor(self, node):
children=node.list.getChildNodes()
start='0'
end='1'
step='1'
if self.debug:
print node.assign.name
print dir(node.assign)
print node.list
print dir(node.list)
print node.list.getChildren()
print children
if children[0].name=='range':
vals=[v.asList()[0] for v in children[1:]]
if node.assign.name=='repeat': # keyword repeat
if len(vals)==1:
end=vals[0]
else:
raise ValueError,"Bad for-loop construction"
self.write("repeat(%s) " % (end))
else:
if len(vals)==1:
end=vals[0]
elif len(vals)==2:
start=vals[0]
end=vals[1]
elif len(vals)==3:
start=vals[0]
end=vals[1]
step=vals[2]
else:
raise ValueError,"Bad for-loop construction"
varname=node.assign.name
self.write("for (%s=%s; %s<%s; %s+=%s) " % (varname,start,
varname,end,
varname,step))
self.INDENT()
self.v(node.body)
self.DEDENT()
else:
raise ValueError,"For-loop construction not implemented"
def visitGenExpr(self, node):
self.write("(")
self.v(node.code)
self.write(")")
def visitGetattr(self, node):
self.v(node.expr)
self.write(".%s" % node.attrname)
def visitIf(self, node):
flag=False
for c, b in node.tests:
if not flag:
self.write("if (")
else:
self.write("else if (")
self.v(c)
self.write(') ')
self.INDENT()
self.v(b)
self.DEDENT()
flag=True
if node.else_:
self.write("else ")
self.INDENT()
self.v(node.else_)
self.DEDENT()
def visitKeyword(self, node):
self.write(node.name)
self.write("=")
self.v(node.expr)
def visitInvert(self, node):
self.write("~")
self.v(node.expr)
def visitLeftShift(self, node):
self.v(node.left)
self.write(" << ")
self.v(node.right)
def visitMod(self, node):
self.v(node.left)
self.write(" % ")
self.v(node.right)
def visitMul(self, node):
self.v(node.left)
self.write(" * ")
self.v(node.right)
def visitName(self, node):
if node.name=='False':
self.write("false")
elif node.name=='True':
self.write("true")
else:
self.write(node.name.replace('inline_',''))
def visitNot(self, node):
self.write(" !(")
self.v(node.expr)
self.write(")")
def visitOr(self, node):
self.write("(")
for i in range(len(node.nodes)):
self.write("(")
self.v(node.nodes[i])
self.write(")")
if i < len(node.nodes) - 1:
self.write(" || ")
self.write(")")
def visitPass(self, node):
self.write("// pass ")
def visitReturn(self, node):
try:
if node.value.value is None:
self.write('return;')
else:
self.write('return(%s);' % node.value.value.__repr__())
except TypeError:
pass
except AttributeError:
self.write("return(")
self.v(node.value)
self.write(");")
def visitRightShift(self, node):
self.v(node.left)
self.write(" >> ")
self.v(node.right)
def visitSubscript(self, node):
isdel = False
if node.flags == OP_DELETE: isdel = True
isdel and self.write("del ")
self.v(node.expr)
self.write("[")
for i in range(len(node.subs)):
self.v(node.subs[i])
if i == len(node.subs) - 1:
self.write("]")
node.flags == OP_DELETE and self.NEWLINE()
def visitSub(self, node):
self.write("(")
self.v(node.left)
self.write(" - ")
self.v(node.right)
self.write(")")
def visitUnaryAdd(self, node):
self.write("+")
self.v(node.expr)
def visitUnarySub(self, node):
self.write("-")
self.v(node.expr)
def visitWhile(self, node):
self.write("while (")
self.v(node.test)
self.write(") ")
self.INDENT()
self.v(node.body)
if node.else_:
self.DEDENT()
self.write("else:")
self.INDENT()
self.v(node.else_)
self.DEDENT()
class FirstPassVisitor(ast_template.Visitor):
"""This object goes through and gets all of the variables.
The second pass will output the code"""
def __init__(self,stream=sys.stdout,debug=False):
ast_template.Visitor.__init__(self,stream,debug)
self.variables={}
self.return_datatype=None
self.types=['Byte','Short','Word','String','Mutex','Integer','Long','Struct']
self.struct_types={}
self.functions={}
self.functions['module']=Function('module',self.variables)
self.variables_assign=[]
self.kwassign=[]
self.use_kwassign=False
self.typedefs={}
self.scope=['module']
self.use_typedef=False
def visitClass(self, node):
self.scope.append('class')
variables={}
old_self_variables=self.variables
self.variables=variables
if self.debug:
print "myvisitClass"
print node.name
basename=node.bases[0].name
for i in range(len(node.bases)):
self.v(node.bases[i])
self.use_typedef=False
self.v(node.code)
if self.use_typedef:
self.typedefs[node.name]=basename
self.types.append(node.name)
else:
self.struct_types[node.name]=variables
self.types.append(node.name)
self.variables=old_self_variables
self.scope.pop()
def visitPass(self, node):
if self.scope[-1]=='class':
self.use_typedef=True
def visitBlock(self, block):
if self.debug:
print "myvisitBlock"
self.v(block)
def visitAssName(self, node):
if self.debug:
print 'visitAssName'
if node.flags == OP_DELETE:
print "del ",
print node.name
n=node
self.variables_assign.append(n.name)
if n.name not in self.variables:
self.variables[n.name]=Variable(n.name)
if self.debug:
print "MyAddVar",n.name
def visitReturn(self, node):
#self.write("return ")
#self.v(node.value)
try:
if node.value.value is None:
self.return_datatype='void'
else:
if isinstance(node.value.value,int):
self.return_datatype='int'
else:
raise TypeError,"Unknown type for "+str(node.value.value)
except TypeError:
pass
except AttributeError: # a name?
name=node.value.name
if name in self.variables:
self.return_datatype=self.variables[name].datatype
else:
raise NameError, "Name"+name+"not found"
def visitFor(self, node):
if self.debug:
print 'myvisitFor'
if node.assign.name!='repeat': # keyword repeat
self.v(node.assign)
self.v(node.body)
def visitAssign(self, node):
if self.debug:
print 'MyvisitAssign'
self.variables_assign=[]
for i in range(len(node.nodes)):
n = node.nodes[i]
if self.debug:
print " Node ",n
self.v(n)
if self.debug:
print "varassign ",self.variables_assign
a=node.expr.asList()[0]
print "varassign expr",node.expr,node.expr.asList()[0],type(a)
if self.scope[-1]=='module':
if self.debug:
print "Module Variables"
for name in self.variables_assign:
val=node.expr.asList()[0]
self.variables[name].value=val
if isinstance(val,str):
self.variables[name].datatype='String'
if self.debug:
print " ",self.variables[name]
self.v(node.expr)
def visitKeyword(self, node):
if self.debug:
print 'myvisitKeyword'
if not self.use_kwassign:
self.v(node.expr)
return
def visitCallFunc(self, node):
if self.debug:
print 'myvisitCallFunc'
print 'funcname: ',node.node.name
name=node.node.name
if not name in self.types:
self.v(node.node)
for i in range(len(node.args)):
self.v(node.args[i])
return
for v in self.variables_assign:
if (name=='Byte' or name=='Word' or name=='Short' or
name=='String' or name=='Integer' or name=='Long' or
name=='Mutex'):
self.variables[v].datatype=name
try:
self.variables[v].value=node.args[0].value
except IndexError:
self.variables[v].value=None # to fix the mutex problem
# was: pass # use the default value
except AttributeError: # list? or mutex
nodelist=node.args[0].asList()
vallist=[]
for l in nodelist:
vallist.append(l.value)
self.variables[v].value=vallist
elif name=='Struct':
self.use_kwassign=True
struct_name=node.args[0].value
if not struct_name in self.struct_types:
self.struct_types.append(struct_name)
for i in range(1,len(node.args)):
if self.debug:
print node.args[i]
print dir(node.args[i])
fun=node.args[i].name
#self.v(node.args[i])
if self.debug:
print " fun",fun
elif name in self.types:
self.variables[v].datatype=name
try:
self.variables[v].value=node.args[0].value
except IndexError:
pass # use the default value
except AttributeError: # list?
self.variables[v].value=[]
def visitFunction(self, node):
self.scope.append('function')
self.return_datatype=None
variables={}
old_self_variables=self.variables
self.variables=variables
if self.debug:
print "myvisitFunction"
print node.name
hasvar = haskw = hasone = hasboth = False
ndefaults = len(node.defaults)
if node.flags & CO_VARARGS:
hasone = hasvar = True
if node.flags & CO_VARKEYWORDS:
hasone = haskw = True
hasboth = hasvar and haskw
kwarg = None
vararg = None
defargs = []
newargs = node.argnames[:]
self.v(node.code)
self.functions[node.name]=Function(node.name,variables)
self.functions[node.name].datatype=self.return_datatype
self.variables=old_self_variables
self.scope.pop()
# remove those variables that are global
remove_var=[]
for var in self.functions[node.name].variables:
if (var in self.variables and
self.functions[node.name].variables[var].datatype=='default'):
remove_var.append(var)
for r in remove_var:
self.functions[node.name].variables.pop(r)
def python_to_nxc(pyfile,nxcfile=None,debug=False):
global file_lines
filename = pyfile
f = open(filename, 'U')
codestring = f.read()
f.close()
if codestring and codestring[-1] != '\n':
codestring = codestring + '\n'
file_lines=open(filename).readlines()
filestr=codestring
defines=re.findall('\s*DEFINE (.*?)=(.*)',filestr)
filestr=re.sub('\s*DEFINE (.*?)=(.*)',"",filestr)
if debug:
print "Filestr"
print filestr
ast = parse(filestr)
v = FirstPassVisitor(debug=debug)
v.v(ast)
v.defines=defines
if nxcfile:
fid=open(nxcfile,'wt')
else:
fid=sys.stdout
v2 = SecondPassVisitor(v,debug=debug,stream=fid)
v2.v(ast)
v2.flush()