-
Notifications
You must be signed in to change notification settings - Fork 3
/
compiler.py
2434 lines (2214 loc) · 65.5 KB
/
compiler.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
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
from decimal import *
import pprint, re, sys
def format_float(tval):
if _language == 'c++' or _language == 'js':
return str(tval)
if tval == Decimal('-0'):
return '0.'
val = ('%f' % Decimal(tval)).rstrip('0')
if '.' not in val:
return val + '.'
elif val.startswith('0.'):
return val[1:]
elif val.startswith('-0.'):
return '-' + val[2:]
else:
return val
getcontext().prec = 5
old_float = float
float = Decimal
old_list = list
class list(old_list):
def __hash__(self):
return hash(tuple(self))
def depcopy(deps):
return dict((k, list(v)) for k, v in deps.items())
def regex(pattern, flags=0):
def sub(text):
match = pattern.match(text)
if match == None:
return False
return match.groups()
pattern = re.compile(pattern, flags)
return sub
ffloat = regex(r'(-?[0-9]+\.[0-9]*)')
efloat = regex(r'(-?\.[0-9]+)')
sfloat = regex(r'(-?[0-9]+)')
bint = regex(r'#(-?[0-9]+)')
satis = lambda inp, *funcs: any(func(inp) for func in funcs)
def parse(code):
def sub(elem):
if satis(elem, ffloat, efloat, sfloat):
return float(elem)
elif bint(elem):
return int(elem[1:])
else:
return unicode(elem)
tokens = []
code += u' '
i = 0
whitespace = u' \r\n\t'
while i < len(code):
while i < len(code) and code[i] in whitespace:
i += 1
if i == len(code):
break
token = u''
if code[i] == '"':
i += 1
while True:
if code[i] == '\\':
i += 1
if code[i] == 'n':
token += '\n'
i += 1
elif code[i] == 'r':
token += '\r'
i += 1
elif code[i] == 't':
token += '\t'
i += 1
elif code[i] == '"':
token += '"'
i += 1
elif code[i] == '\\':
token += '\\'
i += 1
elif code[i] == 'x':
i += 1
token += chr(int(code[i:i+2], 16))
i += 2
elif code[i] == '"':
i += 1
break
else:
token += code[i]
i += 1
tokens.append('str-load')
tokens.append(token)
else:
while code[i] not in whitespace:
token += code[i]
i += 1
tokens.append(sub(token))
return tokens
_language = 'glsl'
class Type(object):
def __init__(self, name):
self.name = unicode(name)
self.attributes = []
self.array_count = None
def attribute(self, name):
self.attributes.append(name)
def array(self, count):
self.array_count = count
def __repr__(self):
return ' '.join(self.attributes) + (' ' if self.attributes else '') + self.name + ('' if self.array_count is None else '[%i]' % self.array_count)
def rename(self, tl=False):
body = Compiler.instance.rename(self.name) + ('' if self.array_count is None or tl else '[%i]' % self.array_count)
if _language == 'c++':
return body
return ' '.join(self.attributes) + (' ' if self.attributes else '') + body
class Stack(object):
def __init__(self):
self.list = []
def push(self, elem):
self.list.append(elem)
return self
def pop(self):
if len(self.list) == 0:
self.list.append(Compiler.instance.argument())
return self.list.pop()
def top(self):
if len(self.list) == 0:
self.list.append(Compiler.instance.argument())
return self.list[-1]
def retrieve(self, offset, remove=False):
offset = len(self.list)-offset-1
elem = self.list[offset]
if remove:
self.list = self.list[:offset] + self.list[offset+1:]
return elem
def replace(self, offset, value):
self.list = self.list[:offset] + [value] + self.list[offset+1:]
def __len__(self):
return len(self.list)
def __repr__(self):
return 'Stack(%r)' % self.list
class Code(object):
def __init__(self, elems):
self.elems = elems
self.i = 0
def peek(self):
if self.i >= len(self.elems):
return None
return self.elems[self.i]
def consume(self):
if self.i >= len(self.elems):
raise Exception('Out of range')
self.i += 1
return self.elems[self.i - 1]
def insert(self, atoms):
self.elems = self.elems[:self.i] + list(atoms) + self.elems[self.i:]
return self
def __repr__(self):
return 'Code(parsed=%r, rest=%r)' % (self.elems[:self.i], self.elems[self.i:])
class Block(object):
def __init__(self, compiler, atoms, spec):
self.compiler = compiler
self.macrolocals = {k : v for k, v in compiler.macrolocals.items()}
self.localstack = []
self.atoms = ['__startclosure', self] + list(atoms) + ['__endclosure']
self.spec = spec
self.args = None
def callback(self):
self.args = ['block_%i_arg_%i' % (self.compiler.rename_i, i) for i in xrange(len(self.cbtype.args))]
for i, arg in enumerate(self.args):
self.compiler.locals[arg] = self.cbtype.args[i]
self.compiler.rename_i += 1
for arg in self.args:
self.compiler.rstack.push(('var', arg))
def callback_type(self, type):
self.cbtype = type
def invoke(self):
self.localstack.append({k : v for k, v in self.compiler.macrolocals.items()})
self.compiler.macrolocals.update(self.macrolocals)
self.compiler.blockstack.append(self)
def end(self):
self.compiler.macrolocals.update(self.localstack.pop())
class Callback(object):
def __init__(self, args, ret):
self.args, self.ret = map(Type, args), Type(ret)
self.name = self # Hack hack hack hack hack.
def __repr__(self):
return 'Callback(%r, %r)' % (self.args, self.ret)
def word(symbol, consumes=0):
def dec(fn):
bwords[symbol] = consumes, fn
return fn
return dec
bwords = {
'+' : (2, None),
'-' : (2, None),
'*' : (2, None),
'/' : (2, None),
'**' : (2, None),
'<' : (2, None),
'>' : (2, None),
'<=' : (2, None),
'>=' : (2, None),
'==' : (2, None),
'!=' : (2, None),
}
foldops = {
'+' : lambda a, b: a + b,
'-' : lambda a, b: a - b,
'*' : lambda a, b: a * b,
'/' : lambda a, b: a / b,
'**' : lambda a, b: a ** b,
'==' : lambda a, b: a == b,
'!=' : lambda a, b: a != b,
'>' : lambda a, b: a > b,
'<' : lambda a, b: a < b,
'>=' : lambda a, b: a >= b,
'<=' : lambda a, b: a <= b,
'clamp' : None,
'sign' : None,
'min' : lambda a, b: min(a, b),
'max' : lambda a, b: max(a, b),
'mod' : lambda a, b: a % b,
}
glfuncs = dict(
dot=2,
sin=1,
abs=1,
atan=1,
atan2=2,
bool=1,
cos=1,
exp=1,
sqrt=1,
inversesqrt=1,
mod=2,
tan=1,
min=2,
max=2,
length=1,
normalize=1,
cross=2,
mix=3,
mat2=4,
mat3=9,
mat4=16,
reflect=2,
refract=3,
int=1,
clamp=3,
step=2,
smoothstep=3,
ceil=1,
floor=1,
fract=1,
sign=1,
texture2D=2,
log=1,
log2=1,
vec2=1,
vec3=1,
vec4=1,
dFdx=1,
dFdy=1,
fwidth=1,
)
gltypes = dict(
dot='float',
vec2='vec2',
vec3='vec3',
vec4='vec4',
length='float',
mat2='mat2',
mat3='mat3',
mat4='mat4',
float='float',
int='int',
sampler2D='sampler2D'
)
btypes = 'void int float bool vec2 vec3 vec4 mat2 mat3 mat4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4'.split(' ')
for name, consumes in glfuncs.items():
bwords[name] = (consumes, None)
if '/' in __file__:
compiler_root = __file__.rsplit('/', 1)[0]
elif '\\' in __file__:
compiler_root = __file__.rsplit('\\', 1)[0]
else:
compiler_root = './'
letterElem = dict(x=0, y=1, z=2, w=3, r=0, g=1, b=2, a=3)
class Compiler(object):
def __init__(self, code, utility, language='glsl', shadertoy=False, minimize=False, entry_point=None):
global _language
self.barecode = code
self.code = utility + code
Compiler.imports = []
self.loaded_modules = []
self.blockstack = []
self.tempi = 0
self.language = language
self.gmp = False
if self.language == 'c++-gmp':
self.language, self.gmp = 'c++', True
_language = self.language
self.entry_point = entry_point
self.resetprecision()
self.shadertoy = shadertoy
self.minimize = minimize
Compiler.instance = self
self.globals = dict(
gl_FragCoord=Type('vec4'),
gl_FragColor=Type('vec4'),
)
self.options = []
self.renamed = {}
self.rename_i = 0
self.is_static_frame = False
self.typetags = {}
self.wordtypes = {}
self.externs = {}
self.words, self.wordtypes, self.macros, self.structs, self.externs = self.parsewords(self.code)
self.deps = {}
self.gdeps = {}
self.exports = []
self.mainWords = {}
if self.shadertoy:
self.words['mainImage'] = self.words['main']
del self.words['main']
self.wordtypes['mainImage'] = (('out vec4', 'in vec2'), 'void', ['fragColor', 'fragCoord'])
del self.wordtypes['main']
self.macroglobals['gl_FragColor'] = ('var', 'fragColor')
self.macroglobals['gl_FragCoord'] = ('var', 'fragCoord')
self.mainWords['mainImage'] = 'mainImage'
for name, atoms in (self.words.items() + self.macros.items()):
self.deps[name] = deps = []
for atom in atoms:
if not isinstance(atom, unicode):
continue
if atom[0] in '&\\/=!*?~':
atom = atom[1:]
if (atom in self.words or atom in self.macros) and atom not in deps:
deps.append(atom)
elif atom in self.globals:
if atom not in self.gdeps:
self.gdeps[atom] = []
self.gdeps[atom].append(name)
elif len(atom) > 1 and atom[0] == '$' and atom[1:] in self.globals:
if atom[1:] not in self.gdeps:
self.gdeps[atom[1:]] = []
self.gdeps[atom[1:]].append(name)
remaining = list(self.words.keys())
order = []
while len(remaining):
rep = []
for elem in remaining:
if False in [dep in order or dep in self.macros for dep in self.deps[elem]]:
rep.append(elem)
else:
order.append(elem)
remaining = rep
for name in order:
self.words[name] = self.compile(name, self.words[name])
self.passes, eps = self.parsepasses()
eps.append('mainImage' if shadertoy else 'main')
if self.entry_point is not None:
eps = [self.entry_point]
for i, ep in enumerate(eps):
if len(self.words[ep][1]) == 0:
del eps[i]
if len(eps) == 0 and len(self.exports) > 0:
eps.append(self.exports[0])
self.outcode = {}
for ep in eps:
code = self.output(ep)
if minimize:
self.outcode[ep] = self.minshader(code)
else:
self.outcode[ep] = code.rstrip('\n')
def minshader(self, code):
code = re.sub(r'//.*$', '', code)
code = code.replace('\n', ' ').replace('\t', ' ')
code = re.sub(r' +', ' ', code)
code = re.sub(r'/\*.*?\*/', '', code)
code = re.sub(r' +', ' ', code)
code = re.sub(r'\.0+([^0-9])', r'.\1', code)
code = re.sub(r'0+([1-9]+\.[^a-z_])', r'\1', code, re.I)
code = re.sub(r'0+([1-9]*\.[0-9])', r'\1', code)
code = re.sub(r'\s*(;|{|}|\(|\)|=|\+|-|\*|\/|\[|\]|,|\.|%|!|~|\?|:|<|>)\s*', r'\1', code)
return code.strip()
def emitnl(self, *args):
self.emitted += ' '.join(args) + '\n'
def output(self, main):
def emiteffects(effects, out=True):
accum = ''
for effect in effects:
prev = indentlevel[0]
line = structure(effect)
sup = False
if isinstance(line, tuple):
line, sup = line
if sup:
if prev <= indentlevel[0]:
off = 1
else:
off = 0
if out:
self.emitnl('\t' * (indentlevel[0] - off) + line)
else:
accum += '\t' * (indentlevel[0] - off) + line + '\n'
else:
if out:
self.emitnl('\t' * indentlevel[0] + line + ';')
else:
accum += '\t' * indentlevel[0] + line + ';\n'
return accum
self.emitted = ''
indentlevel = [1]
operators = 'neg + - / * ** < > <= >= == != && ||'.split(' ')
operator_names = {
'+' : 'add',
'-' : 'sub',
'*' : 'mul',
'/' : 'div',
'**' : 'pow',
'<' : 'lt',
'>' : 'gt',
'<=' : 'lte',
'>=' : 'gte',
'==' : 'eq',
'!=' : 'neq',
}
precedence = {
'?:' : 1,
'+' : 2,
'-' : 2,
'*' : 3,
'/' : 3,
'**' : 4,
'==' : 4,
'!=' : 4,
'<' : 4,
'>' : 4,
'<=' : 4,
'>=' : 4,
'||' : 4,
'&&' : 4,
'.' : 10,
'[]' : 10,
'neg' : 10,
}
def minprec(atom, op=None):
if not isinstance(atom, tuple) or len(atom) == 0 or atom[0] not in operators:
return 1000
tmin = min([precedence[atom[0]]] + map(lambda x: minprec(x, atom[0]), atom))
if op is not None and tmin < precedence[op]:
return 1000
return tmin
def paren(atom, op=None, left=None):
need = True
right_div_sub = left == False and op in '-/'
if not isinstance(atom, tuple):
if atom is True:
return 'true'
elif atom is False:
return 'false'
elif isinstance(atom, float):
return format_float(atom)
return unicode(atom)
elif atom[0] not in operators or op is None:
need = False
elif (minprec(atom) >= precedence[op] and not right_div_sub) or (minprec(atom) > precedence[op] and right_div_sub):
need = False
return '(%s)' % structure(atom) if need else structure(atom)
def structure(atom):
if isinstance(atom, Block):
indentlevel[0] += 1
defd.extend(atom.args)
body = emiteffects(atom.effects, out=False)
for arg in atom.args:
defd.remove(arg)
indentlevel[0] -= 1
return 'function(%s) {\n%s%s}' % (', '.join(atom.args), body, '\t' * indentlevel[0])
elif not isinstance(atom, tuple):
if atom is True:
return 'true'
elif atom is False:
return 'false'
elif isinstance(atom, float):
return format_float(atom)
elif isinstance(atom, unicode):
if atom in self.externs:
return self.externs[atom][2]
return self.rename(atom)
return unicode(atom)
if atom[0] == '**' and self.language != 'js':
if self.language == 'c++':
prefix = 'sf_'
else:
prefix = ''
return '%spow(%s, %s)' % (prefix, structure(atom[1]), structure(atom[2]))
elif atom[0] in operators:
if self.language == 'js':
if atom[0] == 'neg':
if self.infertype(atom[1]) in ('float', 'int'):
return '-%s' % paren(atom[1], 'neg')
else:
pass
else:
ltype, rtype = self.infertype(atom[1]), self.infertype(atom[2])
if ltype == rtype == 'float' or ltype == rtype == 'int':
if atom[0] == '**':
return 'Math.pow(%s, %s)' % (structure(atom[1]), structure(atom[2]))
else:
return '%s %s %s' % (paren(atom[1], atom[0], True), atom[0], paren(atom[2], atom[0], False))
else:
return '%s_%s_%s(%s, %s)' % (ltype, operator_names[atom[0]], rtype, structure(atom[1]), structure(atom[2]))
else:
if atom[0] == 'neg':
return '-%s' % paren(atom[1], 'neg')
else:
return '%s %s %s' % (paren(atom[1], atom[0], True), atom[0], paren(atom[2], atom[0], False))
elif atom[0] == '=':
if atom[2] is None:
return '%s' % structure(atom[1])
else:
if isinstance(atom[2], tuple) and atom[2][0] in ('+', '-', '*', '/'):
if (
(atom[2][0] in ('+', '*') and atom[1] in atom[2]) or
(atom[2][1] == atom[1])
):
other = structure([elem for elem in atom[2] if elem != atom[1]][1])
a, b = self.infertype(atom[1]), self.infertype(other)
if self.language != 'js' or (a == b and a in ('float', 'int')):
return '%s %s= %s' % (structure(atom[1]), atom[2][0], other)
return '%s = %s' % (structure(atom[1]), structure(atom[2]))
elif atom[0][0] == '.':
swizzle = atom[0]
if self.language != 'js' and atom[2]:
swizzle = '.' + self.rename(atom[0][1:])
elif self.language == 'c++':
swizzle = swizzle.replace('r', 'x').replace('g', 'y').replace('b', 'z').replace('a', 'w')
if not atom[2] and self.language == 'c++' and len(swizzle) > 2:
val = paren(atom[1], '.')
return 'vec%i(%s)' % (len(swizzle)-1, ', '.join('%s.%s' % (val, x) for x in swizzle[1:]))
elif self.language == 'js':
if atom[2]:
struct = self.structs[self.infertype(atom[1])]
elem_i = None
for i, (ename, _) in enumerate(struct):
if ename == atom[0][1:]:
elem_i = i
break
assert elem_i is not None
return '%s[%i]' % (structure(atom[1]), elem_i)
elif self.infertype(atom[1]) == 'object':
return '%s.%s' % (paren(atom[1], '.'), atom[0][1:])
else:
val = paren(atom[1], '.')
if len(swizzle) > 2:
return '[%s]' % (', '.join('%s[%i]' % (val, letterElem[x]) for x in swizzle[1:]))
else:
return '%s[%i]' % (val, letterElem[swizzle[1]])
return '%s%s' % (paren(atom[1], '.'), swizzle)
elif atom[0] == 'var':
if atom[1].startswith('gl_') or atom[1] in self.globals or atom[1] in defd:
return self.rename(atom[1])
else:
defd.append(atom[1])
if self.language == 'js':
return 'var %s' % self.rename(atom[1])
else:
return '%s %s' % (locals[atom[1]].rename(), self.rename(atom[1]))
elif atom[0] == 'arg':
return self.rename(atom[1])
elif atom[0] == 'return':
if len(atom) == 2:
return 'return %s' % structure(atom[1])
else:
return 'return'
elif atom[0] == 'for':
_, name, start, top = atom
defd.append(name)
name = self.rename(name)
indentlevel[0] += 1
vtype = 'val' if self.language == 'js' else 'int'
return 'for(%s %s = %s; %s < %s; ++%s) {' % (vtype, name, structure(start), name, structure(top), name), True
elif atom[0] == 'if':
indentlevel[0] += 1
return 'if(%s) {' % structure(atom[1]), True
elif atom[0] == 'else':
return '} else {', True
elif atom[0] == 'elif':
return '} else if(%s) {' % structure(atom[1]), True
elif atom[0] == 'endblock':
indentlevel[0] -= 1
return '}', True
elif atom[0] == 'break':
return 'break'
elif atom[0] == 'continue':
return 'continue'
elif atom[0] == 'print':
if self.language == 'c++':
return 'cout << %s << endl' % paren(atom[1])
elif self.language == 'js':
return 'console.log(%s)' % structure(atom[1])
else:
return ''
elif atom[0] == 'string-literal':
assert self.language == 'js' # XXX: C++ support needs to be added.
# XXX: Need to always double quote, for C++
str = `atom[1]`
if str[0] == 'u':
return str[1:]
else:
return str
elif atom[0] == 'string':
assert self.language == 'js' # XXX: C++ support needs to be added.
return paren(atom[1]) + '.toString()'
elif atom[0] == '?:':
c, a, b = atom[1:]
return '(%s ? %s : %s)' % (paren(c, '?:'), paren(a, '?:'), paren(b, '?:'))
elif atom[0] == '[]':
return '%s[%s]' % (paren(atom[1], '[]'), structure(atom[2]))
elif atom[0] == 'carray':
return '{%s}' % (', '.join(structure(elem) for elem in atom[1:]))
elif self.language == 'js' and atom[0] in ('vec2', 'vec3', 'vec4'):
if len(atom) == int(atom[0][3]) + 1:
return '[%s]' % (', '.join(structure(elem) for elem in atom[1:]))
else:
return '%s(%s)' % (atom[0], structure(atom[1]))
elif self.language == 'glsl' and atom[0] in ('vec2', 'vec3', 'vec4'):
first = atom[1]
if False not in [x == first for x in atom[2:]]:
return '%s(%s)' % tuple(map(structure, atom[:2]))
return '%s(%s)' % (structure(atom[0]), ', '.join(map(structure, atom[1:])))
elif atom[0] == 'call':
return '%s(%s)' % (structure(atom[2]), ', '.join(map(structure, atom[3:])))
elif atom[0] == 'method-call':
assert atom[2] in self.externs
name = self.externs[atom[2]][2]
return '%s%s(%s)' % (paren(atom[1], '.'), name, ', '.join(map(structure, atom[3:])))
else:
if self.language in 'c++' and atom[0] in glfuncs:
prefix = 'sf_'
else:
prefix = ''
if atom[0] in self.externs:
name = self.externs[atom[0]][2]
else:
name = self.rename(atom[0])
if self.language == 'js' and atom[0] in glfuncs:
suffix = ''.join('_%s' % self.infertype(arg) for arg in atom[1:])
else:
suffix = ''
return '%s%s%s(%s)' % (prefix, name, suffix, ', '.join(map(structure, atom[1:])))
if self.shadertoy:
self.emitnl('/* Compiled with Shaderforth: https://github.com/daeken/Shaderforth')
self.emitnl(self.barecode.rstrip('\n'))
self.emitnl('*/')
self.emitnl()
if self.language == 'c++':
if self.gmp:
self.emitnl('#define GMP')
self.emitnl('#include "Shaderforth.hpp"')
if main in self.exports:
main = '__placeholder__' # Necessary to stop name rewriting from triggering
required = self.exports
else:
required = [main] + self.exports
checked = []
while len(checked) < len(required):
for dep in required:
if dep in checked:
continue
for elem in self.deps[dep]:
if elem not in required:
required.append(elem)
checked.append(dep)
dead = [name for name in self.words if name not in required]
if self.language == 'js':
for name, elems in self.structs.items():
args = ', '.join(self.rename(ename) for ename, type in elems)
self.emitnl('function %s(%s) {' % (self.rename(name), args))
self.emitnl('\treturn [%s];' % args)
self.emitnl('}')
else:
for name, elems in self.structs.items():
self.emitnl('struct %s {' % self.rename(name))
for ename, type in elems:
self.emitnl('\t%s %s;' % (type.rename(), self.rename(ename)))
if self.language == 'c++':
self.emitnl('\tSF_FUNC %s() {}' % self.rename(name))
self.emitnl('\tSF_FUNC %s(%s) : %s {}' % (
self.rename(name),
', '.join('%s %s' % (type.rename(), self.rename(ename)) for ename, type in elems),
', '.join('%s(%s)' % (self.rename(ename), self.rename(ename)) for ename, type in elems)
))
self.emitnl('};')
for name, type in self.globals.items():
if name.startswith('gl_') or ((self.shadertoy or self.language == 'c++') and 'uniform' in type.attributes):
continue
elif name not in self.gdeps or True not in [x not in dead for x in self.gdeps[name]]:
continue
if self.language == 'js':
self.emitnl('var', self.rename(name) + ';')
else:
self.emitnl(type.rename(tl=True), self.rename(name, type) + ';')
deps = depcopy(self.deps)
wordorder = []
while len(deps):
for name, wdeps in deps.items():
made = True
for dname in wdeps:
if name != dname and dname not in wordorder:
made = False
break
if made:
del deps[name]
wordorder.append(name)
break
for name in wordorder:
if name in dead or name not in self.words:
continue
locals, effects, localorder, argnames = self.words[name]
defd = self.wordtypes[name][2]
effects = self.predeclare(effects, argnames)
Compiler.compiling = [name]
if name == main:
if name in self.mainWords:
pname = self.mainWords[name]
else:
pname = 'main'
else:
pname = name
prefix = ''
if self.language == 'c++':
prefix = 'SF_FUNC '
if self.language == 'js':
self.emitnl('function %s(%s) {' % (self.rename(name) if pname == name else pname, ', '.join(self.rename(self.wordtypes[name][2][i]) for i in xrange(len(self.wordtypes[name][0])))))
else:
self.emitnl('%s%s %s(%s) {' % (prefix, self.rename(self.wordtypes[name][1]) if pname != 'main' else 'void', self.rename(name) if pname == name else pname, ', '.join('%s %s' % (self.rename(type), self.rename(self.wordtypes[name][2][i])) for i, type in enumerate(self.wordtypes[name][0]))))
emiteffects(effects)
self.emitnl('}')
return self.emitted
def addeffect(self, effect):
def tag_and_blockify(elem):
self.typetags[hash((Compiler.compiling[0], elem))] = self.infertype(elem)
if isinstance(elem, tuple):
return tuple(map(tag_and_blockify, elem))
elif isinstance(elem, list):
return list(map(tag_and_blockify, elem))
elif isinstance(elem, Block):
self.atoms.insert(['__start_callback', elem])
return elem
else:
return elem
if effect[0] == '=' and effect[1] == effect[2]:
return
effect = tag_and_blockify(effect)
self.effects.append(effect)
def predeclare(self, effects, argnames):
def vars_referenced(effect):
if not isinstance(effect, tuple) and not isinstance(effect, list):
return list()
if effect[0] == 'var':
return list([effect[1]])
return reduce(lambda a, b: a + b, map(vars_referenced, effect))
declared = list(self.globals.keys())
need = []
decls = [[]]
inside = []
for effect in effects:
if effect[0] in ('if', 'while', 'for'):
decls.append([])
elif effect[0] in ('else', 'elif'):
inside += decls.pop()
assert len(decls)
decls.append([])
elif effect[0] == 'endblock':
inside += decls.pop()
assert len(decls)
elif effect[0] == '=' and effect[1][0] == 'var' and effect[1][1] not in argnames:
decls[-1].append(effect[1][1])
refs = vars_referenced(effect)
for ref in refs:
if ref in inside and ref not in need:
need.append(ref)
return list(('=', ('var', var), None) for var in need if var not in declared and var not in decls[0]) + effects
def rename(self, name, type=None):
if name in glfuncs or name in btypes or name.startswith('gl_'):
if name == 'atan2':
return 'atan'
return name
elif name in self.globals and ('uniform' in self.globals[name].attributes or 'varying' in self.globals[name].attributes):
if type is not None and type.array_count is not None:
return name + '[%i]' % type.array_count
return name
elif name in self.renamed:
return self.renamed[name]
elif not self.minimize:
tname = name
for x in '-><?[]*+/!@#$%^(){}\'':
if x in name:
tname = tname.replace(x, '_' + str(self.rename_i))
self.rename_i += 1
self.renamed[name] = name = tname.replace('__', '_')
return name
else:
first = '_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
rest = first + '0123456789'
ti = self.rename_i
sname = first[ti % len(first)]
ti /= len(first)
while ti > 0:
sname += rest[ti % len(rest)]
ti /= len(rest)
self.renamed[name] = sname
self.rename_i += 1
return sname
def preprocess(self, code):
code = Code(code)
while code.peek() is not None:
token = code.consume()
if token == 'import[':
start = code.i - 1
fp = code.consume()
while fp.endswith('\\'):
fp = fp[:-1] + ' ' + code.consume()
assert code.consume() == ']'
if fp not in self.loaded_modules:
self.loaded_modules.append(fp)
try:
tfp = compiler_root + '/modules/' + fp + '.sfr'
subcode = file(str(tfp)).read()
Compiler.imports.append(tfp)
except:
try:
subcode = file(fp + '.sfr').read()
Compiler.imports.append(fp + '.sfr')
except:
print >>sys.stderr, 'Failed to load import:', `fp`
subcode = ''
subcode = self.preprocess(parse(subcode))
else:
subcode = []
code.elems = code.elems[:start] + subcode + code.elems[code.i:]
code.i = start
return code.elems
def parse_arg_type(self, type):
if type[0] == '(' and type[-1] == ')':
args = []
ret = 'void'
i = 1
nest = None
in_ret = False
while i < len(type)-1:
if type[i] == '(':
nest = '('
i += 1
elif type[i] == ')':
if in_ret:
ret = self.parse_arg_type(nest + ')')
else:
args.append(self.parse_arg_type(nest + ')'))
nest = None
i += 1
elif nest is not None:
nest += type[i]
i += 1
elif type[i] == '-' and type[i+1] == '>':
i += 2
in_ret = True
continue
else:
start = i
while i < len(type)-1 and type[i] not in '*-':
i += 1
if in_ret:
ret = type[start:i]
else:
args.append(type[start:i])
if type[i] == '*':
i += 1
return Callback(args, ret)
return type
def parsewords(self, code):
def sanitize(name, atoms):
mspec = macrospec[name]
if len(atoms) and (len(mspec) or (not len(mspec) and self.has_underscore(atoms))):
if len(mspec) == 0:
spec = ['_']
all_names = spec
stored = []
else:
spec = []
all_names = []
specstack = [spec]
stored = []
in_ret = False
for i, atom in enumerate(mspec):
if atom == ')':
break
if atom == '[':
specstack.append([])
specstack[-2].append(specstack[-1])
elif atom == ']':
specstack.pop()
elif atom == '->':
in_ret = True
elif not in_ret:
if ':' in atom:
atom = atom.split(':', 1)[0]
if atom.startswith('$'):
stored.append(atom[1:])
atom = atom[1:]
specstack[-1].append(atom)
all_names.append(atom)
preamble = []
def recurspec(spec):
for i, elem in enumerate(spec):
if i != len(spec) - 1:
preamble.append(len(spec) - i - 1)
preamble.append('take')
if isinstance(elem, list):
preamble.append('flatten')
recurspec(elem)
continue
if elem in stored:
preamble.append('=$macro_' + name + '_' + elem)
else:
preamble.append('=>macro_' + name + '_' + elem)