forked from processing-js/processing-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.js
More file actions
executable file
·1744 lines (1609 loc) · 68.3 KB
/
Parser.js
File metadata and controls
executable file
·1744 lines (1609 loc) · 68.3 KB
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
/**
* The parser for turning Processing syntax into Pjs JavaScript.
* This code is not trivial; unless you know what you're doing,
* you shouldn't be changing things in here =)
*/
module.exports = function setupParser(Processing, options) {
var defaultScope = options.defaultScope,
PConstants = defaultScope.PConstants,
aFunctions = options.aFunctions,
Browser = options.Browser,
document = Browser.document,
undef;
// Processing global methods and constants for the parser
function getGlobalMembers() {
// The names array contains the names of everything that is inside "p."
// When something new is added to "p." it must also be added to this list.
var names = [ /* this code is generated by jsglobals.js */
"abs", "acos", "alpha", "ambient", "ambientLight", "append", "applyMatrix",
"arc", "arrayCopy", "asin", "atan", "atan2", "background", "beginCamera",
"beginDraw", "beginShape", "bezier", "bezierDetail", "bezierPoint",
"bezierTangent", "bezierVertex", "binary", "blend", "blendColor",
"blit_resize", "blue", "box", "breakShape", "brightness",
"camera", "ceil", "Character", "color", "colorMode",
"concat", "constrain", "copy", "cos", "createFont",
"createGraphics", "createImage", "cursor", "curve", "curveDetail",
"curvePoint", "curveTangent", "curveTightness", "curveVertex", "day",
"degrees", "directionalLight", "disableContextMenu",
"dist", "draw", "ellipse", "ellipseMode", "emissive", "enableContextMenu",
"endCamera", "endDraw", "endShape", "exit", "exp", "expand", "externals",
"fill", "filter", "floor", "focused", "frameCount", "frameRate", "frustum",
"get", "glyphLook", "glyphTable", "green", "height", "hex", "hint", "hour",
"hue", "image", "imageMode", "intersect", "join", "key",
"keyCode", "keyPressed", "keyReleased", "keyTyped", "lerp", "lerpColor",
"lightFalloff", "lights", "lightSpecular", "line", "link", "loadBytes",
"loadFont", "loadGlyphs", "loadImage", "loadPixels", "loadShape", "loadXML",
"loadStrings", "log", "loop", "mag", "map", "match", "matchAll", "max",
"millis", "min", "minute", "mix", "modelX", "modelY", "modelZ", "modes",
"month", "mouseButton", "mouseClicked", "mouseDragged", "mouseMoved",
"mouseOut", "mouseOver", "mousePressed", "mouseReleased", "mouseScroll",
"mouseScrolled", "mouseX", "mouseY", "name", "nf", "nfc", "nfp", "nfs",
"noCursor", "noFill", "noise", "noiseDetail", "noiseSeed", "noLights",
"noLoop", "norm", "normal", "noSmooth", "noStroke", "noTint", "ortho",
"param", "parseBoolean", "parseByte", "parseChar", "parseFloat",
"parseInt", "parseXML", "peg", "perspective", "PImage", "pixels",
"PMatrix2D", "PMatrix3D", "PMatrixStack", "pmouseX", "pmouseY", "point",
"pointLight", "popMatrix", "popStyle", "pow", "print", "printCamera",
"println", "printMatrix", "printProjection", "PShape", "PShapeSVG",
"pushMatrix", "pushStyle", "quad", "radians", "random", "randomGaussian",
"randomSeed", "rect", "rectMode", "red", "redraw", "requestImage",
"resetMatrix", "reverse", "rotate", "rotateX", "rotateY", "rotateZ",
"round", "saturation", "save", "saveFrame", "saveStrings", "scale",
"screenX", "screenY", "screenZ", "second", "set", "setup", "shape",
"shapeMode", "shared", "shearX", "shearY", "shininess", "shorten", "sin", "size", "smooth",
"sort", "specular", "sphere", "sphereDetail", "splice", "split",
"splitTokens", "spotLight", "sq", "sqrt", "status", "str", "stroke",
"strokeCap", "strokeJoin", "strokeWeight", "subset", "tan", "text",
"textAlign", "textAscent", "textDescent", "textFont", "textLeading",
"textMode", "textSize", "texture", "textureMode", "textWidth", "tint", "toImageData",
"touchCancel", "touchEnd", "touchMove", "touchStart", "translate", "transform",
"triangle", "trim", "unbinary", "unhex", "updatePixels", "use3DContext",
"vertex", "width", "XMLElement", "XML", "year", "__contains", "__equals",
"__equalsIgnoreCase", "__frameRate", "__hashCode", "__int_cast",
"__instanceof", "__keyPressed", "__mousePressed", "__printStackTrace",
"__replace", "__replaceAll", "__replaceFirst", "__toCharArray", "__split",
"__codePointAt", "__startsWith", "__endsWith", "__matches"];
// custom functions and properties are added here
if(aFunctions) {
Object.keys(aFunctions).forEach(function(name) {
names.push(name);
});
}
// custom libraries that were attached to Processing
var members = {};
var i, l;
for (i = 0, l = names.length; i < l ; ++i) {
members[names[i]] = null;
}
for (var lib in Processing.lib) {
if (Processing.lib.hasOwnProperty(lib)) {
if (Processing.lib[lib].exports) {
var exportedNames = Processing.lib[lib].exports;
for (i = 0, l = exportedNames.length; i < l; ++i) {
members[exportedNames[i]] = null;
}
}
}
}
return members;
}
/*
Parser converts Java-like syntax into JavaScript.
Creates an Abstract Syntax Tree -- "Light AST" from the Java-like code.
It is an object tree. The root object is created from the AstRoot class, which contains statements.
A statement object can be of type: AstForStatement, AstCatchStatement, AstPrefixStatement, AstMethod, AstClass,
AstInterface, AstFunction, AstStatementBlock and AstLabel.
AstPrefixStatement can be a statement of type: if, switch, while, with, do, else, finally, return, throw, try, break, and continue.
These object's toString function returns the JavaScript code for the statement.
Any processing calls need "processing." prepended to them.
Similarly, calls from inside classes need "$this_1.", prepended to them,
with 1 being the depth level for inner classes.
This includes members passed down from inheritance.
The resulting code is then eval'd and run.
*/
function parseProcessing(code) {
var globalMembers = getGlobalMembers();
// masks parentheses, brackets and braces with '"A5"'
// where A is the bracket type, and 5 is the index in an array containing all brackets split into atoms
// 'while(true){}' -> 'while"B1""A2"'
// parentheses() = B, brackets[] = C and braces{} = A
function splitToAtoms(code) {
var atoms = [];
var items = code.split(/([\{\[\(\)\]\}])/);
var result = items[0];
var stack = [];
for(var i=1; i < items.length; i += 2) {
var item = items[i];
if(item === '[' || item === '{' || item === '(') {
stack.push(result); result = item;
} else if(item === ']' || item === '}' || item === ')') {
var kind = item === '}' ? 'A' : item === ')' ? 'B' : 'C';
var index = atoms.length; atoms.push(result + item);
result = stack.pop() + '"' + kind + (index + 1) + '"';
}
result += items[i + 1];
}
atoms.unshift(result);
return atoms;
}
// replaces strings and regexs keyed by index with an array of strings
function injectStrings(code, strings) {
return code.replace(/'(\d+)'/g, function(all, index) {
var val = strings[index];
if(val.charAt(0) === "/") {
return val;
}
return (/^'((?:[^'\\\n])|(?:\\.[0-9A-Fa-f]*))'$/).test(val) ? "(new $p.Character(" + val + "))" : val;
});
}
// trims off leading and trailing spaces
// returns an object. object.left, object.middle, object.right, object.untrim
function trimSpaces(string) {
var m1 = /^\s*/.exec(string), result;
if(m1[0].length === string.length) {
result = {left: m1[0], middle: "", right: ""};
} else {
var m2 = /\s*$/.exec(string);
result = {left: m1[0], middle: string.substring(m1[0].length, m2.index), right: m2[0]};
}
result.untrim = function(t) { return this.left + t + this.right; };
return result;
}
// simple trim of leading and trailing spaces
function trim(string) {
return string.replace(/^\s+/,'').replace(/\s+$/,'');
}
function appendToLookupTable(table, array) {
for(var i=0,l=array.length;i<l;++i) {
table[array[i]] = null;
}
return table;
}
function isLookupTableEmpty(table) {
for(var i in table) {
if(table.hasOwnProperty(i)) {
return false;
}
}
return true;
}
function getAtomIndex(templ) { return templ.substring(2, templ.length - 1); }
// remove carriage returns "\r"
var codeWoExtraCr = code.replace(/\r\n?|\n\r/g, "\n");
// masks strings and regexs with "'5'", where 5 is the index in an array containing all strings and regexs
// also removes all comments
var strings = [];
var codeWoStrings = codeWoExtraCr.replace(/("(?:[^"\\\n]|\\.)*")|('(?:[^'\\\n]|\\.)*')|(([\[\(=|&!\^:?]\s*)(\/(?![*\/])(?:[^\/\\\n]|\\.)*\/[gim]*)\b)|(\/\/[^\n]*\n)|(\/\*(?:(?!\*\/)(?:.|\n))*\*\/)/g,
function(all, quoted, aposed, regexCtx, prefix, regex, singleComment, comment) {
var index;
if(quoted || aposed) { // replace strings
index = strings.length; strings.push(all);
return "'" + index + "'";
}
if(regexCtx) { // replace RegExps
index = strings.length; strings.push(regex);
return prefix + "'" + index + "'";
}
// kill comments
return comment !== "" ? " " : "\n";
});
// protect character codes from namespace collision
codeWoStrings = codeWoStrings.replace(/__x([0-9A-F]{4})/g, function(all, hexCode) {
// $ = __x0024
// _ = __x005F
// this protects existing character codes from conversion
// __x0024 = __x005F_x0024
return "__x005F_x" + hexCode;
});
// convert dollar sign to character code
codeWoStrings = codeWoStrings.replace(/\$/g, "__x0024");
// Remove newlines after return statements
codeWoStrings = codeWoStrings.replace(/return\s*[\n\r]+/g, "return ");
// removes generics
var genericsWereRemoved;
var codeWoGenerics = codeWoStrings;
var replaceFunc = function(all, before, types, after) {
if(!!before || !!after) {
return all;
}
genericsWereRemoved = true;
return "";
};
do {
genericsWereRemoved = false;
codeWoGenerics = codeWoGenerics.replace(/([<]?)<\s*((?:\?|[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\[\])*(?:\s+(?:extends|super)\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)?(?:\s*,\s*(?:\?|[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\[\])*(?:\s+(?:extends|super)\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)?)*)\s*>([=]?)/g, replaceFunc);
} while (genericsWereRemoved);
var atoms = splitToAtoms(codeWoGenerics);
var replaceContext;
var declaredClasses = {}, currentClassId, classIdSeed = 0;
function addAtom(text, type) {
var lastIndex = atoms.length;
atoms.push(text);
return '"' + type + lastIndex + '"';
}
function generateClassId() {
return "class" + (++classIdSeed);
}
function appendClass(class_, classId, scopeId) {
class_.classId = classId;
class_.scopeId = scopeId;
declaredClasses[classId] = class_;
}
// functions defined below
var transformClassBody, transformInterfaceBody, transformStatementsBlock, transformStatements, transformMain, transformExpression;
var classesRegex = /\b((?:(?:public|private|final|protected|static|abstract)\s+)*)(class|interface)\s+([A-Za-z_$][\w$]*\b)(\s+extends\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)*)?(\s+implements\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\b)*)?\s*("A\d+")/g;
var methodsRegex = /\b((?:(?:public|private|final|protected|static|abstract|synchronized)\s+)*)((?!(?:else|new|return|throw|function|public|private|protected)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+"|;)/g;
var fieldTest = /^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:else|new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*([A-Za-z_$][\w$]*\b)\s*(?:"C\d+"\s*)*([=,]|$)/;
var cstrsRegex = /\b((?:(?:public|private|final|protected|static|abstract)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b)\s*("B\d+")(\s*throws\s+[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*,\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)*)?\s*("A\d+")/g;
var attrAndTypeRegex = /^((?:(?:public|private|final|protected|static)\s+)*)((?!(?:new|return|throw)\b)[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*(?:\s*"C\d+")*)\s*/;
var functionsRegex = /\bfunction(?:\s+([A-Za-z_$][\w$]*))?\s*("B\d+")\s*("A\d+")/g;
// This converts classes, methods and functions into atoms, and adds them to the atoms array.
// classes = E, methods = D and functions = H
function extractClassesAndMethods(code) {
var s = code;
s = s.replace(classesRegex, function(all) {
return addAtom(all, 'E');
});
s = s.replace(methodsRegex, function(all) {
return addAtom(all, 'D');
});
s = s.replace(functionsRegex, function(all) {
return addAtom(all, 'H');
});
return s;
}
// This converts constructors into atoms, and adds them to the atoms array.
// constructors = G
function extractConstructors(code, className) {
var result = code.replace(cstrsRegex, function(all, attr, name, params, throws_, body) {
if(name !== className) {
return all;
}
return addAtom(all, 'G');
});
return result;
}
// AstParam contains the name of a parameter inside a function declaration
function AstParam(name) {
this.name = name;
}
AstParam.prototype.toString = function() {
return this.name;
};
// AstParams contains an array of AstParam objects
function AstParams(params, methodArgsParam) {
this.params = params;
this.methodArgsParam = methodArgsParam;
}
AstParams.prototype.getNames = function() {
var names = [];
for(var i=0,l=this.params.length;i<l;++i) {
names.push(this.params[i].name);
}
return names;
};
AstParams.prototype.prependMethodArgs = function(body) {
if (!this.methodArgsParam) {
return body;
}
return "{\nvar " + this.methodArgsParam.name +
" = Array.prototype.slice.call(arguments, " +
this.params.length + ");\n" + body.substring(1);
};
AstParams.prototype.toString = function() {
if(this.params.length === 0) {
return "()";
}
var result = "(";
for(var i=0,l=this.params.length;i<l;++i) {
result += this.params[i] + ", ";
}
return result.substring(0, result.length - 2) + ")";
};
function transformParams(params) {
var paramsWoPars = trim(params.substring(1, params.length - 1));
var result = [], methodArgsParam = null;
if(paramsWoPars !== "") {
var paramList = paramsWoPars.split(",");
for(var i=0; i < paramList.length; ++i) {
var param = /\b([A-Za-z_$][\w$]*\b)(\s*"[ABC][\d]*")*\s*$/.exec(paramList[i]);
if (i === paramList.length - 1 && paramList[i].indexOf('...') >= 0) {
methodArgsParam = new AstParam(param[1]);
break;
}
result.push(new AstParam(param[1]));
}
}
return new AstParams(result, methodArgsParam);
}
function preExpressionTransform(expr) {
var s = expr;
// new type[] {...} --> {...}
s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"C\d+")+\s*("A\d+")/g, function(all, type, init) {
return init;
});
// new Runnable() {...} --> "F???"
s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)(?:\s*"B\d+")\s*("A\d+")/g, function(all, type, init) {
return addAtom(all, 'F');
});
// function(...) { } --> "H???"
s = s.replace(functionsRegex, function(all) {
return addAtom(all, 'H');
});
// new type[?] --> createJavaArray('type', [?])
s = s.replace(/\bnew\s+([A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*)\s*("C\d+"(?:\s*"C\d+")*)/g, function(all, type, index) {
var args = index.replace(/"C(\d+)"/g, function(all, j) { return atoms[j]; })
.replace(/\[\s*\]/g, "[null]").replace(/\s*\]\s*\[\s*/g, ", ");
var arrayInitializer = "{" + args.substring(1, args.length - 1) + "}";
var createArrayArgs = "('" + type + "', " + addAtom(arrayInitializer, 'A') + ")";
return '$p.createJavaArray' + addAtom(createArrayArgs, 'B');
});
// .length() --> .length
s = s.replace(/(\.\s*length)\s*"B\d+"/g, "$1");
// #000000 --> 0x000000
s = s.replace(/#([0-9A-Fa-f]{6})\b/g, function(all, digits) {
return "0xFF" + digits;
});
// delete (type)???, except (int)???
s = s.replace(/"B(\d+)"(\s*(?:[\w$']|"B))/g, function(all, index, next) {
var atom = atoms[index];
if(!/^\(\s*[A-Za-z_$][\w$]*\b(?:\s*\.\s*[A-Za-z_$][\w$]*\b)*\s*(?:"C\d+"\s*)*\)$/.test(atom)) {
return all;
}
if(/^\(\s*int\s*\)$/.test(atom)) {
return "(int)" + next;
}
var indexParts = atom.split(/"C(\d+)"/g);
if(indexParts.length > 1) {
// even items contains atom numbers, can check only first
if(! /^\[\s*\]$/.test(atoms[indexParts[1]])) {
return all; // fallback - not a cast
}
}
return "" + next;
});
// (int)??? -> __int_cast(???)
s = s.replace(/\(int\)([^,\]\)\}\?\:\*\+\-\/\^\|\%\&\~<\>\=]+)/g, function(all, arg) {
var trimmed = trimSpaces(arg);
return trimmed.untrim("__int_cast(" + trimmed.middle + ")");
});
// super() -> $superCstr(), super. -> $super.;
s = s.replace(/\bsuper(\s*"B\d+")/g, "$$superCstr$1").replace(/\bsuper(\s*\.)/g, "$$super$1");
// 000.43->0.43 and 0010f->10, but not 0010
s = s.replace(/\b0+((\d*)(?:\.[\d*])?(?:[eE][\-\+]?\d+)?[fF]?)\b/, function(all, numberWo0, intPart) {
if( numberWo0 === intPart) {
return all;
}
return intPart === "" ? "0" + numberWo0 : numberWo0;
});
// 3.0f -> 3.0
s = s.replace(/\b(\.?\d+\.?)[fF]\b/g, "$1");
// Weird (?) parsing errors with %
s = s.replace(/([^\s])%([^=\s])/g, "$1 % $2");
// Since frameRate() and frameRate are different things,
// we need to differentiate them somehow. So when we parse
// the Processing.js source, replace frameRate so it isn't
// confused with frameRate(), as well as keyPressed and mousePressed
s = s.replace(/\b(frameRate|keyPressed|mousePressed)\b(?!\s*"B)/g, "__$1");
// "boolean", "byte", "int", etc. => "parseBoolean", "parseByte", "parseInt", etc.
s = s.replace(/\b(boolean|byte|char|float|int)\s*"B/g, function(all, name) {
return "parse" + name.substring(0, 1).toUpperCase() + name.substring(1) + "\"B";
});
// "pixels" replacements:
// pixels[i] = c => pixels.setPixel(i,c) | pixels[i] => pixels.getPixel(i)
// pixels.length => pixels.getLength()
// pixels = ar => pixels.set(ar) | pixels => pixels.toArray()
s = s.replace(/\bpixels\b\s*(("C(\d+)")|\.length)?(\s*=(?!=)([^,\]\)\}]+))?/g,
function(all, indexOrLength, index, atomIndex, equalsPart, rightSide) {
if(index) {
var atom = atoms[atomIndex];
if(equalsPart) {
return "pixels.setPixel" + addAtom("(" +atom.substring(1, atom.length - 1) +
"," + rightSide + ")", 'B');
}
return "pixels.getPixel" + addAtom("(" + atom.substring(1, atom.length - 1) +
")", 'B');
}
if(indexOrLength) {
// length
return "pixels.getLength" + addAtom("()", 'B');
}
if(equalsPart) {
return "pixels.set" + addAtom("(" + rightSide + ")", 'B');
}
return "pixels.toArray" + addAtom("()", 'B');
});
// Java method replacements for: replace, replaceAll, replaceFirst, equals, hashCode, etc.
// xxx.replace(yyy) -> __replace(xxx, yyy)
// "xx".replace(yyy) -> __replace("xx", yyy)
var repeatJavaReplacement;
function replacePrototypeMethods(all, subject, method, atomIndex) {
var atom = atoms[atomIndex];
repeatJavaReplacement = true;
var trimmed = trimSpaces(atom.substring(1, atom.length - 1));
return "__" + method + ( trimmed.middle === "" ? addAtom("(" + subject.replace(/\.\s*$/, "") + ")", 'B') :
addAtom("(" + subject.replace(/\.\s*$/, "") + "," + trimmed.middle + ")", 'B') );
}
do {
repeatJavaReplacement = false;
s = s.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*\.\s*(?:[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*\.\s*)*)(replace|replaceAll|replaceFirst|contains|equals|equalsIgnoreCase|hashCode|toCharArray|printStackTrace|split|startsWith|endsWith|codePointAt|matches)\s*"B(\d+)"/g,
replacePrototypeMethods);
} while (repeatJavaReplacement);
// xxx instanceof yyy -> __instanceof(xxx, yyy)
function replaceInstanceof(all, subject, type) {
repeatJavaReplacement = true;
return "__instanceof" + addAtom("(" + subject + ", " + type + ")", 'B');
}
do {
repeatJavaReplacement = false;
s = s.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*(?:\.\s*[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*)*)instanceof\s+([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)/g,
replaceInstanceof);
} while (repeatJavaReplacement);
// this() -> $constr()
s = s.replace(/\bthis(\s*"B\d+")/g, "$$constr$1");
return s;
}
function AstInlineClass(baseInterfaceName, body) {
this.baseInterfaceName = baseInterfaceName;
this.body = body;
body.owner = this;
}
AstInlineClass.prototype.toString = function() {
return "new (" + this.body + ")";
};
function transformInlineClass(class_) {
var m = new RegExp(/\bnew\s*([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)\s*"B\d+"\s*"A(\d+)"/).exec(class_);
var oldClassId = currentClassId, newClassId = generateClassId();
currentClassId = newClassId;
var uniqueClassName = m[1] + "$" + newClassId;
var inlineClass = new AstInlineClass(uniqueClassName,
transformClassBody(atoms[m[2]], uniqueClassName, "", "implements " + m[1]));
appendClass(inlineClass, newClassId, oldClassId);
currentClassId = oldClassId;
return inlineClass;
}
function AstFunction(name, params, body) {
this.name = name;
this.params = params;
this.body = body;
}
AstFunction.prototype.toString = function() {
var oldContext = replaceContext;
// saving "this." and parameters
var names = appendToLookupTable({"this":null}, this.params.getNames());
replaceContext = function (subject) {
return names.hasOwnProperty(subject.name) ? subject.name : oldContext(subject);
};
var result = "function";
if(this.name) {
result += " " + this.name;
}
var body = this.params.prependMethodArgs(this.body.toString());
result += this.params + " " + body;
replaceContext = oldContext;
return result;
};
function transformFunction(class_) {
var m = new RegExp(/\b([A-Za-z_$][\w$]*)\s*"B(\d+)"\s*"A(\d+)"/).exec(class_);
return new AstFunction( m[1] !== "function" ? m[1] : null,
transformParams(atoms[m[2]]), transformStatementsBlock(atoms[m[3]]));
}
function AstInlineObject(members) {
this.members = members;
}
AstInlineObject.prototype.toString = function() {
var oldContext = replaceContext;
replaceContext = function (subject) {
return subject.name === "this" ? "this" : oldContext(subject); // saving "this."
};
var result = "";
for(var i=0,l=this.members.length;i<l;++i) {
if(this.members[i].label) {
result += this.members[i].label + ": ";
}
result += this.members[i].value.toString() + ", ";
}
replaceContext = oldContext;
return result.substring(0, result.length - 2);
};
function transformInlineObject(obj) {
var members = obj.split(',');
for(var i=0; i < members.length; ++i) {
var label = members[i].indexOf(':');
if(label < 0) {
members[i] = { value: transformExpression(members[i]) };
} else {
members[i] = { label: trim(members[i].substring(0, label)),
value: transformExpression( trim(members[i].substring(label + 1)) ) };
}
}
return new AstInlineObject(members);
}
function expandExpression(expr) {
if(expr.charAt(0) === '(' || expr.charAt(0) === '[') {
return expr.charAt(0) + expandExpression(expr.substring(1, expr.length - 1)) + expr.charAt(expr.length - 1);
}
if(expr.charAt(0) === '{') {
if(/^\{\s*(?:[A-Za-z_$][\w$]*|'\d+')\s*:/.test(expr)) {
return "{" + addAtom(expr.substring(1, expr.length - 1), 'I') + "}";
}
return "[" + expandExpression(expr.substring(1, expr.length - 1)) + "]";
}
var trimmed = trimSpaces(expr);
var result = preExpressionTransform(trimmed.middle);
result = result.replace(/"[ABC](\d+)"/g, function(all, index) {
return expandExpression(atoms[index]);
});
return trimmed.untrim(result);
}
function replaceContextInVars(expr) {
return expr.replace(/(\.\s*)?((?:\b[A-Za-z_]|\$)[\w$]*)(\s*\.\s*([A-Za-z_$][\w$]*)(\s*\()?)?/g,
function(all, memberAccessSign, identifier, suffix, subMember, callSign) {
if(memberAccessSign) {
return all;
}
var subject = { name: identifier, member: subMember, callSign: !!callSign };
return replaceContext(subject) + (suffix === undef ? "" : suffix);
});
}
function AstExpression(expr, transforms) {
this.expr = expr;
this.transforms = transforms;
}
AstExpression.prototype.toString = function() {
var transforms = this.transforms;
var expr = replaceContextInVars(this.expr);
return expr.replace(/"!(\d+)"/g, function(all, index) {
return transforms[index].toString();
});
};
transformExpression = function(expr) {
var transforms = [];
var s = expandExpression(expr);
s = s.replace(/"H(\d+)"/g, function(all, index) {
transforms.push(transformFunction(atoms[index]));
return '"!' + (transforms.length - 1) + '"';
});
s = s.replace(/"F(\d+)"/g, function(all, index) {
transforms.push(transformInlineClass(atoms[index]));
return '"!' + (transforms.length - 1) + '"';
});
s = s.replace(/"I(\d+)"/g, function(all, index) {
transforms.push(transformInlineObject(atoms[index]));
return '"!' + (transforms.length - 1) + '"';
});
return new AstExpression(s, transforms);
};
function AstVarDefinition(name, value, isDefault) {
this.name = name;
this.value = value;
this.isDefault = isDefault;
}
AstVarDefinition.prototype.toString = function() {
return this.name + ' = ' + this.value;
};
function transformVarDefinition(def, defaultTypeValue) {
var eqIndex = def.indexOf("=");
var name, value, isDefault;
if(eqIndex < 0) {
name = def;
value = defaultTypeValue;
isDefault = true;
} else {
name = def.substring(0, eqIndex);
value = transformExpression(def.substring(eqIndex + 1));
isDefault = false;
}
return new AstVarDefinition( trim(name.replace(/(\s*"C\d+")+/g, "")),
value, isDefault);
}
function getDefaultValueForType(type) {
if(type === "int" || type === "float") {
return "0";
}
if(type === "boolean") {
return "false";
}
if(type === "color") {
return "0x00000000";
}
return "null";
}
function AstVar(definitions, varType) {
this.definitions = definitions;
this.varType = varType;
}
AstVar.prototype.getNames = function() {
var names = [];
for(var i=0,l=this.definitions.length;i<l;++i) {
names.push(this.definitions[i].name);
}
return names;
};
AstVar.prototype.toString = function() {
return "var " + this.definitions.join(",");
};
function AstStatement(expression) {
this.expression = expression;
}
AstStatement.prototype.toString = function() {
return this.expression.toString();
};
function transformStatement(statement) {
if(fieldTest.test(statement)) {
var attrAndType = attrAndTypeRegex.exec(statement);
var definitions = statement.substring(attrAndType[0].length).split(",");
var defaultTypeValue = getDefaultValueForType(attrAndType[2]);
for(var i=0; i < definitions.length; ++i) {
definitions[i] = transformVarDefinition(definitions[i], defaultTypeValue);
}
return new AstVar(definitions, attrAndType[2]);
}
return new AstStatement(transformExpression(statement));
}
function AstForExpression(initStatement, condition, step) {
this.initStatement = initStatement;
this.condition = condition;
this.step = step;
}
AstForExpression.prototype.toString = function() {
return "(" + this.initStatement + "; " + this.condition + "; " + this.step + ")";
};
function AstForInExpression(initStatement, container) {
this.initStatement = initStatement;
this.container = container;
}
AstForInExpression.prototype.toString = function() {
var init = this.initStatement.toString();
if(init.indexOf("=") >= 0) { // can be without var declaration
init = init.substring(0, init.indexOf("="));
}
return "(" + init + " in " + this.container + ")";
};
function AstForEachExpression(initStatement, container) {
this.initStatement = initStatement;
this.container = container;
}
AstForEachExpression.iteratorId = 0;
AstForEachExpression.prototype.toString = function() {
var init = this.initStatement.toString();
var iterator = "$it" + (AstForEachExpression.iteratorId++);
var variableName = init.replace(/^\s*var\s*/, "").split("=")[0];
var initIteratorAndVariable = "var " + iterator + " = new $p.ObjectIterator(" + this.container + "), " +
variableName + " = void(0)";
var nextIterationCondition = iterator + ".hasNext() && ((" +
variableName + " = " + iterator + ".next()) || true)";
return "(" + initIteratorAndVariable + "; " + nextIterationCondition + ";)";
};
function transformForExpression(expr) {
var content;
if (/\bin\b/.test(expr)) {
content = expr.substring(1, expr.length - 1).split(/\bin\b/g);
return new AstForInExpression( transformStatement(trim(content[0])),
transformExpression(content[1]));
}
if (expr.indexOf(":") >= 0 && expr.indexOf(";") < 0) {
content = expr.substring(1, expr.length - 1).split(":");
return new AstForEachExpression( transformStatement(trim(content[0])),
transformExpression(content[1]));
}
content = expr.substring(1, expr.length - 1).split(";");
return new AstForExpression( transformStatement(trim(content[0])),
transformExpression(content[1]), transformExpression(content[2]));
}
function sortByWeight(array) {
array.sort(function (a,b) {
return b.weight - a.weight;
});
}
function AstInnerInterface(name, body, isStatic) {
this.name = name;
this.body = body;
this.isStatic = isStatic;
body.owner = this;
}
AstInnerInterface.prototype.toString = function() {
return "" + this.body;
};
function AstInnerClass(name, body, isStatic) {
this.name = name;
this.body = body;
this.isStatic = isStatic;
body.owner = this;
}
AstInnerClass.prototype.toString = function() {
return "" + this.body;
};
function transformInnerClass(class_) {
var m = classesRegex.exec(class_); // 1 - attr, 2 - class|int, 3 - name, 4 - extends, 5 - implements, 6 - body
classesRegex.lastIndex = 0;
var isStatic = m[1].indexOf("static") >= 0;
var body = atoms[getAtomIndex(m[6])], innerClass;
var oldClassId = currentClassId, newClassId = generateClassId();
currentClassId = newClassId;
if(m[2] === "interface") {
innerClass = new AstInnerInterface(m[3], transformInterfaceBody(body, m[3], m[4]), isStatic);
} else {
innerClass = new AstInnerClass(m[3], transformClassBody(body, m[3], m[4], m[5]), isStatic);
}
appendClass(innerClass, newClassId, oldClassId);
currentClassId = oldClassId;
return innerClass;
}
function AstClassMethod(name, params, body, isStatic) {
this.name = name;
this.params = params;
this.body = body;
this.isStatic = isStatic;
}
AstClassMethod.prototype.toString = function(){
var paramNames = appendToLookupTable({}, this.params.getNames());
var oldContext = replaceContext;
replaceContext = function (subject) {
return paramNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject);
};
var body = this.params.prependMethodArgs(this.body.toString());
var result = "function " + this.methodId + this.params + " " + body +"\n";
replaceContext = oldContext;
return result;
};
function transformClassMethod(method) {
var m = methodsRegex.exec(method);
methodsRegex.lastIndex = 0;
var isStatic = m[1].indexOf("static") >= 0;
var body = m[6] !== ';' ? atoms[getAtomIndex(m[6])] : "{}";
return new AstClassMethod(m[3], transformParams(atoms[getAtomIndex(m[4])]),
transformStatementsBlock(body), isStatic );
}
function AstClassField(definitions, fieldType, isStatic) {
this.definitions = definitions;
this.fieldType = fieldType;
this.isStatic = isStatic;
}
AstClassField.prototype.getNames = function() {
var names = [];
for(var i=0,l=this.definitions.length;i<l;++i) {
names.push(this.definitions[i].name);
}
return names;
};
AstClassField.prototype.toString = function() {
var thisPrefix = replaceContext({ name: "[this]" });
if(this.isStatic) {
var className = this.owner.name;
var staticDeclarations = [];
for(var i=0,l=this.definitions.length;i<l;++i) {
var definition = this.definitions[i];
var name = definition.name, staticName = className + "." + name;
var declaration = "if(" + staticName + " === void(0)) {\n" +
" " + staticName + " = " + definition.value + "; }\n" +
"$p.defineProperty(" + thisPrefix + ", " +
"'" + name + "', { get: function(){return " + staticName + ";}, " +
"set: function(val){" + staticName + " = val;} });\n";
staticDeclarations.push(declaration);
}
return staticDeclarations.join("");
}
return thisPrefix + "." + this.definitions.join("; " + thisPrefix + ".");
};
function transformClassField(statement) {
var attrAndType = attrAndTypeRegex.exec(statement);
var isStatic = attrAndType[1].indexOf("static") >= 0;
var definitions = statement.substring(attrAndType[0].length).split(/,\s*/g);
var defaultTypeValue = getDefaultValueForType(attrAndType[2]);
for(var i=0; i < definitions.length; ++i) {
definitions[i] = transformVarDefinition(definitions[i], defaultTypeValue);
}
return new AstClassField(definitions, attrAndType[2], isStatic);
}
function AstConstructor(params, body) {
this.params = params;
this.body = body;
}
AstConstructor.prototype.toString = function() {
var paramNames = appendToLookupTable({}, this.params.getNames());
var oldContext = replaceContext;
replaceContext = function (subject) {
return paramNames.hasOwnProperty(subject.name) ? subject.name : oldContext(subject);
};
var prefix = "function $constr_" + this.params.params.length + this.params.toString();
var body = this.params.prependMethodArgs(this.body.toString());
if(!/\$(superCstr|constr)\b/.test(body)) {
body = "{\n$superCstr();\n" + body.substring(1);
}
replaceContext = oldContext;
return prefix + body + "\n";
};
function transformConstructor(cstr) {
var m = new RegExp(/"B(\d+)"\s*"A(\d+)"/).exec(cstr);
var params = transformParams(atoms[m[1]]);
return new AstConstructor(params, transformStatementsBlock(atoms[m[2]]));
}
function AstInterfaceBody(name, interfacesNames, methodsNames, fields, innerClasses, misc) {
var i,l;
this.name = name;
this.interfacesNames = interfacesNames;
this.methodsNames = methodsNames;
this.fields = fields;
this.innerClasses = innerClasses;
this.misc = misc;
for(i=0,l=fields.length; i<l; ++i) {
fields[i].owner = this;
}
}
AstInterfaceBody.prototype.getMembers = function(classFields, classMethods, classInners) {
if(this.owner.base) {
this.owner.base.body.getMembers(classFields, classMethods, classInners);
}
var i, j, l, m;
for(i=0,l=this.fields.length;i<l;++i) {
var fieldNames = this.fields[i].getNames();
for(j=0,m=fieldNames.length;j<m;++j) {
classFields[fieldNames[j]] = this.fields[i];
}
}
for(i=0,l=this.methodsNames.length;i<l;++i) {
var methodName = this.methodsNames[i];
classMethods[methodName] = true;
}
for(i=0,l=this.innerClasses.length;i<l;++i) {
var innerClass = this.innerClasses[i];
classInners[innerClass.name] = innerClass;
}
};
AstInterfaceBody.prototype.toString = function() {
function getScopeLevel(p) {
var i = 0;
while(p) {
++i;
p=p.scope;
}
return i;
}
var scopeLevel = getScopeLevel(this.owner);
var className = this.name;
var staticDefinitions = "";
var metadata = "";
var thisClassFields = {}, thisClassMethods = {}, thisClassInners = {};
this.getMembers(thisClassFields, thisClassMethods, thisClassInners);
var i, l, j, m;
if (this.owner.interfaces) {
// interface name can be present, but interface is not
var resolvedInterfaces = [], resolvedInterface;
for (i = 0, l = this.interfacesNames.length; i < l; ++i) {
if (!this.owner.interfaces[i]) {
continue;
}
resolvedInterface = replaceContext({name: this.interfacesNames[i]});
resolvedInterfaces.push(resolvedInterface);
staticDefinitions += "$p.extendInterfaceMembers(" + className + ", " + resolvedInterface + ");\n";
}
metadata += className + ".$interfaces = [" + resolvedInterfaces.join(", ") + "];\n";
}
metadata += className + ".$isInterface = true;\n";
metadata += className + ".$methods = [\'" + this.methodsNames.join("\', \'") + "\'];\n";
sortByWeight(this.innerClasses);
for (i = 0, l = this.innerClasses.length; i < l; ++i) {
var innerClass = this.innerClasses[i];
if (innerClass.isStatic) {
staticDefinitions += className + "." + innerClass.name + " = " + innerClass + ";\n";
}
}
for (i = 0, l = this.fields.length; i < l; ++i) {
var field = this.fields[i];
if (field.isStatic) {
staticDefinitions += className + "." + field.definitions.join(";\n" + className + ".") + ";\n";
}
}
return "(function() {\n" +
"function " + className + "() { throw \'Unable to create the interface\'; }\n" +
staticDefinitions +
metadata +
"return " + className + ";\n" +
"})()";
};
transformInterfaceBody = function(body, name, baseInterfaces) {
var declarations = body.substring(1, body.length - 1);
declarations = extractClassesAndMethods(declarations);
declarations = extractConstructors(declarations, name);
var methodsNames = [], classes = [];
declarations = declarations.replace(/"([DE])(\d+)"/g, function(all, type, index) {
if(type === 'D') { methodsNames.push(index); }
else if(type === 'E') { classes.push(index); }
return "";
});
var fields = declarations.split(/;(?:\s*;)*/g);
var baseInterfaceNames;
var i, l;