How to use compile method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

testControlFlow.js

Source: testControlFlow.js Github

copy
1// |jit-test| test-also-noasmjs
2load(libdir + "asm.js");
3
4assertEq(asmLink(asmCompile(USE_ASM + "function f(i,j) { i=i|0;j=+j; if (i) return j; return j+1.0 } return f"))(0, 1.2), 1.2+1.0);
5assertEq(asmLink(asmCompile(USE_ASM + "function f(i,j) { i=i|0;j=+j; if (i) return j; return +~~i } return f"))(1,1.4), 1.4);
6assertEq(asmLink(asmCompile(USE_ASM + "function f(i,j) { i=i|0;j=j|0; if (i) return j^0; return i^1 } return f"))(1, 1), 1);
7assertEq(asmLink(asmCompile(USE_ASM + "function f(i,j) { i=i|0;j=j|0; if (i) return j^0; return i|0 } return f"))(1,8), 8);
8assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; if ((i|0) == 0) return 10; else if ((i|0) == 1) return 12; else if ((i|0) == 2) return 14; return 0} return f"))(2), 14);
9assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; if ((i|0) == 0) return 10; else if ((i|0) == 1) return 12; else if ((i|0) == 2) return 14; else return 16; return 0} return f"))(3), 16);
10assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; if ((i|0) == 0) i = 10; else if ((i|0) == 1) return 12; return (i|0) } return f"))(0), 10);
11
12assertAsmTypeFail(USE_ASM + "function f(i) { i=i|0; if (i) return 0; } return f");
13assertAsmTypeFail(USE_ASM + "function f(i) { i=i|0; if (i) return 0; else return 1 } return f");
14assertAsmTypeFail(USE_ASM + "function f(i) { i=i|0; if (i) return 0; return 1.0 } return f");
15assertAsmTypeFail(USE_ASM + "function f() { if (0) return 0; 1 } return f");
16
17assertEq(asmLink(asmCompile(USE_ASM + "function f() { while (0) {} return 0} return f"))(), 0);
18assertEq(asmLink(asmCompile(USE_ASM + "function f() { for (;0;) {} return 0} return f"))(), 0);
19assertEq(asmLink(asmCompile(USE_ASM + "function f() { do {} while(0); return 0} return f"))(), 0);
20
21assertEq(asmLink(asmCompile(USE_ASM + "function f() { while (0) ; return 0} return f"))(), 0);
22assertEq(asmLink(asmCompile(USE_ASM + "function f() { for (;0;) ; return 0} return f"))(), 0);
23assertEq(asmLink(asmCompile(USE_ASM + "function f() { do ; while(0); return 0} return f"))(), 0);
24
25assertAsmTypeFail(USE_ASM + "function f(d) {d=+d; while (d) {}; return 0} return f");
26assertAsmTypeFail(USE_ASM + "function f(d) {d=+d; for (;d;) {}; return 0} return f");
27assertAsmTypeFail(USE_ASM + "function f(d) {d=+d; do {} while (d); return 0} return f");
28
29assertEq(asmLink(asmCompile(USE_ASM + "function f(j) {j=j|0; var i=0; while ((i|0) < (j|0)) i=(i+4)|0; return i|0} return f"))(6), 8);
30assertEq(asmLink(asmCompile(USE_ASM + "function f(j) {j=j|0; var i=0; for (;(i|0) < (j|0);) i=(i+4)|0; return i|0} return f"))(6), 8);
31assertEq(asmLink(asmCompile(USE_ASM + "function f(j) {j=j|0; var i=0; do { i=(i+4)|0; } while ((i|0) < (j|0)); return i|0} return f"))(6), 8);
32
33assertEq(asmLink(asmCompile(USE_ASM + "function f() { while(1) return 42; return 0 } return f"))(), 42);
34assertEq(asmLink(asmCompile(USE_ASM + "function f() { for(;1;) return 42; return 0 } return f"))(), 42);
35assertEq(asmLink(asmCompile(USE_ASM + "function f() { do return 42; while(1); return 0 } return f"))(), 42);
36
37assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while(1) { if (i) return 13; return 42 } return 0 } return f"))(), 42);
38assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(;1;) { if (i) return 13; return 42 } return 0 } return f"))(), 42);
39assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do { if (i) return 13; return 42 } while(1); return 0 } return f"))(), 42);
40
41assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while(1) { break; while(1) {} } return 42 } return f"))(), 42);
42assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(;;) { break; for(;;) {} } return 42 } return f"))(), 42);
43assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do { break; do {} while(1) {} } while(1); return 42 } return f"))(), 42);
44
45assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=1; while(1) { if (i) return 42; return 13 } return 0 } return f"))(), 42);
46assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=1; for(;1;) { if (i) return 42; return 13 } return 0 } return f"))(), 42);
47assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=1; do { if (i) return 42; return 13 } while(1); return 0 } return f"))(), 42);
48
49assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while(1) { if (i) return 13; else return 42; return 13 } return 0 } return f"))(), 42);
50assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(;;) { if (i) return 13; else return 42; return 13 } return 0 } return f"))(), 42);
51assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do { if (i) return 13; else return 42; return 13 } while(1); return 0 } return f"))(), 42);
52
53assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while((i|0) < 3) { if (i) return 42; i=(i+1)|0 } return 0 } return f"))(), 42);
54assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(;(i|0) < 3;) { if (i) return 42; i=(i+1)|0 } return 0 } return f"))(), 42);
55assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do { if (i) return 42; i=(i+1)|0 } while((i|0) < 3); return 0 } return f"))(), 42);
56
57assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while((i|0) < 3) { if (!i) i=(i+1)|0; return 42 } return 0 } return f"))(), 42);
58assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(;(i|0) < 3;) { if (!i) i=(i+1)|0; return 42 } return 0 } return f"))(), 42);
59assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do { if (!i) i=(i+1)|0; return 42 } while((i|0) < 3); return 0 } return f"))(), 42);
60
61assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=42; return i|0; while(1) {} return 0 } return f"))(), 42);
62assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=42; return i|0; for(;1;) {} return 0 } return f"))(), 42);
63assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=42; return i|0; do {} while(1); return 0 } return f"))(), 42);
64
65assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while((i|0) < 10) if ((i|0) == 4) break; else i=(i+1)|0; return i|0 } return f"))(), 4);
66assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(; (i|0) < 10;) if ((i|0) == 4) break; else i=(i+1)|0; return i|0 } return f"))(), 4);
67assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do if ((i|0) == 4) break; else i=(i+1)|0; while((i|0) < 10); return i|0 } return f"))(), 4);
68
69assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0,sum=0; while ((i=(i+1)|0)<2) { sum=(sum+1)|0; if ((i&1)==0) continue; sum=(sum+100)|0 } return sum|0 } return f"))(), 101);
70assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0,sum=0; for (;(i=(i+1)|0)<2;) { sum=(sum+1)|0; if ((i&1)==0) continue; sum=(sum+100)|0 } return sum|0 } return f"))(), 101);
71assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0,sum=0; do { sum=(sum+1)|0; if ((i&1)==0) continue; sum=(sum+100)|0 } while((i=(i+1)|0)<2); return sum|0 } return f"))(), 102);
72
73assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; x:a:y:while(1) { i=1; while(1) { i=2; break a; } i=3; } return i|0 } return f"))(), 2);
74assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; x:a:y:for(;;) { i=1; while(1) { i=2; break a; } i=3; } return i|0 } return f"))(), 2);
75assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; x:a:y:do { i=1; while(1) { i=2; break a; } i=3; } while(1); return i|0 } return f"))(), 2);
76
77assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; a:b:while((i|0) < 5) { i=(i+1)|0; while(1) continue b; } return i|0 } return f"))(), 5);
78assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; a:b:for(;(i|0) < 5;) { i=(i+1)|0; while(1) continue b; } return i|0 } return f"))(), 5);
79assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; a:b:do { i=(i+1)|0; while(1) continue b; } while((i|0) < 5); return i|0 } return f"))(), 5);
80
81assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; return 0; a:b:while((i|0) < 5) { i=(i+1)|0; while(1) continue b; } return i|0 } return f"))(), 0);
82assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; return 0; a:b:for(;(i|0) < 5;) { i=(i+1)|0; while(1) continue b; } return i|0 } return f"))(), 0);
83assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; return 0; a:b:do { i=(i+1)|0; while(1) continue b; } while((i|0) < 5); return i|0 } return f"))(), 0);
84
85assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=42; a:{ break a; i=2; } b:{ c:{ break b; i=3 } i=4 } return i|0 } return f"))(), 42);
86
87assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; a:b:for(;(i|0) < 5;i=(i+1)|0) { while(1) continue b; } return i|0 } return f"))(), 5);
88assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=42,sum=0; for(i=1;(i|0)<4;i=(i+1)|0) sum=(sum+i)|0; return sum|0 } return f"))(), 6);
89assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=42,sum=0; for(i=1;(i|0)<8;i=(i+1)|0) { if ((i&1) == 0) continue; sum=(sum+i)|0; } return sum|0 } return f"))(), 16);
90
91assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while(1) { i=(i+1)|0; if ((i|0) > 10) break; } return i|0 } return f"))(), 11);
92assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(;1;i=(i+1)|0) { if ((i|0) > 10) break; } return i|0 } return f"))(), 11);
93assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do { if ((i|0) > 10) break; i=(i+1)|0 } while(1); return i|0 } return f"))(), 11);
94
95assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; while(1){ if ((i|0)>0) break; while (1) { i=i+1|0; if ((i|0)==1) break; } } return i|0; } return f"))(), 1);
96assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; for(;;){ if ((i|0)>0) break; while (1) { i=i+1|0; if ((i|0)==1) break; } } return i|0; } return f"))(), 1);
97assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; do{ if ((i|0)>0) break; while (1) { i=i+1|0; if ((i|0)==1) break; } }while(1); return i|0; } return f"))(), 1);
98
99assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0,sum=0; while(1){ if ((i|0)>5) break; while (1) { i=i+1|0; sum=(sum+i)|0; if ((i|0)>3) break; } } return sum|0; } return f"))(), 21);
100assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0,sum=0; for(;;){ if ((i|0)>5) break; while (1) { i=i+1|0; sum=(sum+i)|0; if ((i|0)>3) break; } } return sum|0; } return f"))(), 21);
101assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0,sum=0; do{ if ((i|0)>5) break; while (1) { i=i+1|0; sum=(sum+i)|0; if ((i|0)>3) break; } }while(1); return sum|0; } return f"))(), 21);
102
103assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; while(1) { if (i) { break; } else { return i|0 } i = 1 } return i|0 } return f"))(3), 3);
104assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; for(;1;) { if (i) { break; } else { return i|0 } i = 1 } return i|0 } return f"))(3), 3);
105assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; do { if (i) { break; } else { return i|0 } i = 1 } while (0); return i|0 } return f"))(3), 3);
106
107assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; while(1) { if (i) { return i|0 } else { return i|0 } i = 1 } return i|0 } return f"))(3), 3);
108assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; for(;;) { if (i) { return i|0 } else { return i|0 } i = 1 } return i|0 } return f"))(3), 3);
109assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; do { if (i) { return i|0 } else { return i|0 } i = 1 } while (0); return i|0 } return f"))(3), 3);
110
111assertEq(asmLink(asmCompile(USE_ASM + "function f() {var j=1,i=0; while(j){ if(0) continue; j=i } return j|0 } return f"))(), 0);
112assertEq(asmLink(asmCompile(USE_ASM + "function f() {var j=1,i=0; for(;j;){ if(0) continue; j=i } return j|0 } return f"))(), 0);
113assertEq(asmLink(asmCompile(USE_ASM + "function f() {var j=1,i=0; do{ if(0) continue; j=i } while(j) return j|0 } return f"))(), 0);
114
115assertEq(asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; for(;;) { return i|0 } return 0 } return f"))(42), 42);
116assertEq(asmLink(asmCompile(USE_ASM + "function f(n) { n=n|0; var i=0,s=0; for(;;i=(i+1)|0) { if (~~i==~~n) return s|0; s=(s+i)|0 } return 0 } return f"))(8), 28);
117
118var f = asmLink(asmCompile(USE_ASM + "function f(n,m) { n=n|0;m=m|0; var i=0,sum=0; while((n|0)>(m|0) ? ((i|0)<(n|0))|0 : ((i|0)<(m|0))|0) { sum = (sum+i)|0; i=(i+1)|0 } return sum|0 } return f"));
119assertEq(f(1,5), 10);
120assertEq(f(6,5), 15);
121
122var f = asmLink(asmCompile(USE_ASM + "function f(n,m) { n=n|0;m=m|0; var i=0,sum=0; for(; (n|0)>(m|0) ? ((i|0)<(n|0))|0 : ((i|0)<(m|0))|0; i=(i+1)|0) { sum = (sum+i)|0 } return sum|0 } return f"));
123assertEq(f(1,5), 10);
124assertEq(f(6,5), 15);
125
126var f = asmLink(asmCompile(USE_ASM + "function f(n,m) { n=n|0;m=m|0; var i=0,sum=0; do { sum = (sum+i)|0; i=(i+1)|0 } while((n|0)>(m|0) ? ((i|0)<(n|0))|0 : ((i|0)<(m|0))|0); return sum|0 } return f"));
127assertEq(f(1,5), 10);
128assertEq(f(6,5), 15);
129
130assertAsmTypeFail(USE_ASM + "function f(i) { i=i|0; switch(i|0) { case 1: return 0; case 1: return 0 } return 0} return f");
131assertAsmTypeFail(USE_ASM + "function f(i) { i=i|0; switch(i|0) { case 1: return 0; case 2: return 0; case 1: return 0 } return 0} return f");
132assertAsmTypeFail(USE_ASM + "function f(i) { i=i|0; switch(1) { case 1: return 0; case 1: return 0 } return 0} return f");
133assertAsmTypeFail(USE_ASM + "function f() { var i=0; switch(i) {}; return i|0 } return f");
134assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; switch(i|0) {}; return i|0 } return f"))(), 0);
135assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; switch(i|0) { default: i=42 } return i|0 } return f"))(), 42);
136assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; switch(i|0) { default: i=42; break } return i|0 } return f"))(), 42);
137assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; switch(i|0) { case 0: i=42 } return i|0 } return f"))(), 42);
138assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; switch(i|0) { case 0: i=42; break } return i|0 } return f"))(), 42);
139assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; switch(i|0) { case 0: default: i=42 } return i|0 } return f"))(), 42);
140assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=0; switch(i|0) { case 0: default: i=42; break } return i|0 } return f"))(), 42);
141assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=1; switch(i|0) { case 0: case 2: break; default: i=42 } return i|0 } return f"))(), 42);
142assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=1; switch(i|0) { case 0: case 2: break; default: i=42; break } return i|0 } return f"))(), 42);
143assertEq(asmLink(asmCompile(USE_ASM + "function f() { return 42; switch(1) { case 1: return 13 } return 14 } return f"))(), 42);
144
145var exp = asmLink(asmCompile(USE_ASM + "var x=0; function a() { return x|0 } function b(i) { i=i|0; x=i } function c(i) { i=i|0; if (i) b(i); } return {a:a,b:b,c:c}"));
146assertEq(exp.c(10), undefined);
147assertEq(exp.a(), 10);
148
149var f = asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; switch(i|0) { case 1: i=-1; break; case 133742: i=2; break; default: i=42; break } return i|0 } return f"));
150assertEq(f(1), -1);
151assertEq(f(2), 42);
152assertEq(f(133742), 2);
153assertEq(f(133743), 42);
154
155var f = asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; switch(i|0) { case 1: i=42; break; default: i=13 } return i|0 } return f"));
156assertEq(f(-1), 13);
157assertEq(f(0), 13);
158assertEq(f(1), 42);
159
160var f = asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; switch(i|0) { case -1: i=42; break; default: i=13 } return i|0 } return f"));
161assertEq(f(-1), 42);
162assertEq(f(0), 13);
163assertEq(f(1), 13);
164assertEq(f(0xffffffff), 42);
165
166var f = asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; var sum=0; switch(i|0) { case -1: sum=(sum+1)|0; case 1: sum=(sum+1)|0; case 3: sum=(sum+1)|0; default: sum=(sum+100)|0; } return sum|0 } return f"));
167assertEq(f(-1), 103);
168assertEq(f(0), 100);
169assertEq(f(1), 102);
170assertEq(f(2), 100);
171assertEq(f(3), 101);
172
173var f = asmLink(asmCompile(USE_ASM + "function f(i) { i=i|0; var sum=0; switch(i|0) { case -1: sum=10; break; case 1: sum=11; break; case 3: sum=12; break; default: sum=13; } return sum|0 } return f"));
174assertEq(f(-1), 10);
175assertEq(f(0), 13);
176assertEq(f(1), 11);
177assertEq(f(2), 13);
178assertEq(f(3), 12);
179
180assertEq(asmLink(asmCompile(USE_ASM + "function f() { var i=8,sum=0; a:for(; (i|0)<20; i=(i+1)|0) { switch(i&3) { case 0:case 1:sum=(sum+i)|0;break;case 2:sum=(sum+100)|0;continue;default:break a} sum=(sum+10)|0; } sum=(sum+1000)|0; return sum|0 } return f"))(), 1137);
181assertEq(asmLink(asmCompile(USE_ASM + "function f() { a: do{break a;}while(0); a: do{break a;}while(0); return 42 } return f"))(), 42);
182assertEq(asmLink(asmCompile('g', USE_ASM + "function f() { g:{ return 42 } return 13 } return f"), null)(), 42);
183assertEq(asmLink(asmCompile(USE_ASM + "function f(x) {x=x|0;switch (x|0) {case 31:return 13;case 9: {x = 3;if ((x|0) <= 0) {return -1;}}}return 1;} return f"))(31), 13);
184
185var imp = { ffi:function() { throw "Wrong" } };
186assertEq(asmLink(asmCompile('glob','imp', USE_ASM + "var ffi=imp.ffi; function f() { var i=0; return (i+1)|0; return ffi(i|0)|0 } return f"), null, imp)(), 1);
187
188assertEq(asmLink(asmCompile(USE_ASM + 'function f() {var k = 1;if (1) {for(k = 1; k|0; k=k-1|0) {}} return 1}; return f'))(), 1);
189
190// Ternaries conditionals
191//
192// Basic ternaries
193var f = asmLink(asmCompile(USE_ASM + "function f() { return 0; if (1) return -1; return -2} return f"));
194assertEq(f(5), 0);
195
196var f = asmLink(asmCompile(USE_ASM + "function f(x) { x=x|0; var a=2;if(x?1:0)a=1;else a=0; return a|0 } return f"));
197assertEq(f(1), 1);
198assertEq(f(0), 0);
199
200var guard = (function() {
201    var called_ = false;
202    return {
203        called: function(){ return called_ },
204        call: function(){ called_ = true }
205    }
206})();
207
208var f = asmLink(asmCompile('glob', 'ffi', USE_ASM + "var func=ffi.func; function f(x) { x=x|0; var a=2;if(x?1:1)a=1; else {func();a=0}return a|0 } return f"), this, {func: guard.call});
209assertEq(f(1), 1);
210assertEq(f(0), 1);
211assertEq(guard.called(), false);
212
213var f = asmLink(asmCompile('glob', 'ffi', USE_ASM + "var func=ffi.func; function f(x) { x=x|0; var a=2;if(x?0:0){a=1; func()}else a=0;return a|0 } return f"), this, {func: guard.call});
214assertEq(f(1), 0);
215assertEq(f(0), 0);
216assertEq(guard.called(), false);
217
218var f = asmLink(asmCompile('glob', 'ffi', USE_ASM + "var func=ffi.func; function f(x,y) { x=x|0;y=y|0; var a=2;if(x?func()|0:y)a=1;else a=0; return a|0 } return f"), this, {func: guard.call});
219assertEq(f(0,1), 1);
220assertEq(guard.called(), false);
221
222var f = asmLink(asmCompile('glob', 'ffi', USE_ASM + "var func=ffi.func; function f(x,y) { x=x|0;y=y|0; var a=2;if(x?y:func()|0)a=1;else a=0; return a|0 } return f"), this, {func: guard.call});
223assertEq(f(1,0), 0);
224assertEq(guard.called(), false);
225
226var f = asmLink(asmCompile(USE_ASM + "function f(x,y) { x=x|0;y=y|0; var a=2;if(x?0:y)a=1;else a=0; return a|0 } return f"));
227assertEq(f(1,1), 0);
228assertEq(f(1,0), 0);
229assertEq(f(0,0), 0);
230assertEq(f(0,1), 1);
231
232var f = asmLink(asmCompile(USE_ASM + "function f(x,y) { x=x|0;y=y|0; var a=2;if(x?y:1)a=1;else a=0; return a|0 } return f"));
233assertEq(f(1,1), 1);
234assertEq(f(1,0), 0);
235assertEq(f(0,0), 1);
236assertEq(f(0,1), 1);
237
238var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2;if(x?y:z)a=1;else a=0; return a|0 } return f"));
239for (var i = 0; i < 2; ++i)
240    for (var j = 0; j < 2; ++j)
241        for (var k = 0; k < 2; ++k)
242            assertEq(f(i,j,k), ((i && j) || (!i && k))|0);
243
244// Complex ternaries
245function CheckTwoArgsTwoOptions(f) {
246    function check(x,y) {
247        return (x > 2 && y < 5) | 0;
248    }
249    for (var a = -10; a < 10; a++)
250        for (var b = -10; b < 10; b++)
251                assertEq(f(a,b), check(a,b));
252}
253
254function CheckThreeArgsTwoOptions(f) {
255    function check(x,y,z) {
256        return (x > 2 && y < 5 && z > -1) | 0;
257    }
258    for (var a = -10; a < 10; a++)
259        for (var b = -10; b < 10; b++)
260            for (var c = -10; c < 10; c++)
261                assertEq(f(a,b,c), check(a,b,c));
262}
263
264// Ternaries with && semantics
265var f = asmLink(asmCompile(USE_ASM + "function f(x,y) { x=x|0;y=y|0; var z=0; if((x|0) > 2 ? (y|0) < 5 : 0) z=1; return z|0;} return f"));
266CheckTwoArgsTwoOptions(f);
267var f = asmLink(asmCompile(USE_ASM + "function f(x,y) { x=x|0;y=y|0; var z=2; if((x|0) > 2 ? (y|0) < 5 : 0) z=1; else z=0; return z|0;} return f"));
268CheckTwoArgsTwoOptions(f);
269
270var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=0; if((x|0) > 2 ? ((y|0) < 5 ? (z|0) > -1 : 0) : 0) a=1; return a|0;} return f"));
271CheckThreeArgsTwoOptions(f);
272var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2; if((x|0) > 2 ? ((y|0) < 5 ? (z|0) > -1 : 0) : 0) a=1; else a=0; return a|0;} return f"));
273CheckThreeArgsTwoOptions(f);
274
275var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=0; if((x|0) > 2 ? (y|0) < 5 : 0) {if ((z|0) > -1) a=1}; return a|0;} return f"));
276CheckThreeArgsTwoOptions(f);
277var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2; if((x|0) > 2 ? (y|0) < 5 : 0) {if ((z|0) > -1) a=1; else a=0;} else a=0; return a|0;} return f"));
278CheckThreeArgsTwoOptions(f);
279
280var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=0; if(((x|0) == 3 ? 1 : ((x|0) > 3)) ? ((y|0) < 5 ? (z|0) > -1 : 0) : 0) a=1; return a|0;} return f"));
281CheckThreeArgsTwoOptions(f);
282var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2; if(((x|0) == 3 ? 1 : ((x|0) > 3)) ? ((y|0) < 5 ? (z|0) > -1 : 0) : 0) a=1; else a=0; return a|0;} return f"));
283CheckThreeArgsTwoOptions(f);
284
285var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=0; if((x|0) == 3 ? 1 : (x|0) > 3) {if ((y|0) < 5 ? (z|0) > -1 : 0) a=1;} return a|0;} return f"));
286CheckThreeArgsTwoOptions(f);
287var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2; if((x|0) == 3 ? 1 : (x|0) > 3) {if ((y|0) < 5 ? (z|0) > -1 : 0) a=1; else a=0;} else a=0; return a|0;} return f"));
288CheckThreeArgsTwoOptions(f);
289
290// Ternaries with || semantics
291var f = asmLink(asmCompile(USE_ASM + "function f(x,y) { x=x|0;y=y|0; var z=1; if((x|0) <= 2 ? 1 : (y|0) >= 5) z=0; return z|0;} return f"));
292CheckTwoArgsTwoOptions(f);
293var f = asmLink(asmCompile(USE_ASM + "function f(x,y) { x=x|0;y=y|0; var z=2; if((x|0) <= 2 ? 1 : (y|0) >= 5) z=0; else z=1; return z|0;} return f"));
294CheckTwoArgsTwoOptions(f);
295
296var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=1; if((x|0) <= 2 ? 1 : ((y|0) >= 5 ? 1 : (z|0) <= -1)) a=0; return a|0;} return f"));
297CheckThreeArgsTwoOptions(f);
298var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2; if((x|0) <= 2 ? 1 : ((y|0) >= 5 ? 1 : (z|0) <= -1)) a=0; else a=1; return a|0;} return f"));
299CheckThreeArgsTwoOptions(f);
300
301var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=1; if((x|0) <= 2 ? 1 : (y|0) >= 5) a=0; else if ((z|0) <= -1) a=0; return a|0;} return f"));
302CheckThreeArgsTwoOptions(f);
303var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2; if((x|0) <= 2 ? 1 : (y|0) >= 5) a=0; else if ((z|0) <= -1) a=0; else a=1; return a|0;} return f"));
304CheckThreeArgsTwoOptions(f);
305
306var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=1; if(((x|0) != 3 ? ((x|0) <= 3) : 0) ? 1 : ((y|0) >= 5 ? 1 : (z|0) <= -1)) a=0; return a|0;} return f"));
307CheckThreeArgsTwoOptions(f);
308var f = asmLink(asmCompile(USE_ASM + "function f(x,y,z) { x=x|0;y=y|0;z=z|0; var a=2; if(((x|0) != 3 ? ((x|0) <= 3) : 0) ? 1 : ((y|0) >= 5 ? 1 : (z|0) <= -1)) a=0; else a=1; return a|0;} return f"));
309CheckThreeArgsTwoOptions(f);
310
311// Massive test
312var code = '"use asm";\
313    function g(x,y) {\
314        x=x|0;\
315        y=y|0;\
316        var z = 0;\
317        if ((y|0) == 1337) {\
318            z = 1;\
319        } else if ((x|0) == 1 ? 1 : ((x|0) < 0 ? (y|0) == 1 : 0)) {\
320            z = 2;\
321        } else if ((x|0) == 2) {\
322            z = 3;\
323        } else if ((x|0) == 3 ? 1 : (x|0) == 4) {\
324            z = 4;\
325        } else if ((x|0) == 5 ? (y|0) > 5 : 0) {\
326            z = 5;\
327        } else {\
328            z = 6;\
329        }\
330        return z|0;\
331    }\
332    return g;';
333
334var m = asmLink(asmCompile(code));
335
336assertEq(m(0, 1337), 1);
337assertEq(m(0, 1338), 6);
338assertEq(m(0, 0), 6);
339assertEq(m(0, 1), 6);
340assertEq(m(0, 1336), 6);
341assertEq(m(1, 1337), 1);
342assertEq(m(2, 1337), 1);
343assertEq(m(3, 1337), 1);
344assertEq(m(4, 1337), 1);
345assertEq(m(5, 1337), 1);
346
347assertEq(m(1, 10), 2);
348assertEq(m(1, 1336), 2);
349assertEq(m(-1, 10), 6);
350assertEq(m(-1, 2), 6);
351assertEq(m(-1, -1), 6);
352assertEq(m(-1, 1), 2);
353assertEq(m(-9, 1), 2);
354
355assertEq(m(2, 1), 3);
356assertEq(m(2, 0), 3);
357assertEq(m(2, 6), 3);
358
359assertEq(m(3, 1), 4);
360assertEq(m(3, 0), 4);
361assertEq(m(3, 6), 4);
362assertEq(m(3, 3), 4);
363assertEq(m(4, 1), 4);
364assertEq(m(4, 0), 4);
365assertEq(m(4, 6), 4);
366assertEq(m(4, 3), 4);
367
368assertEq(m(5, -1), 6);
369assertEq(m(5, 4), 6);
370assertEq(m(5, 5), 6);
371assertEq(m(5, 6), 5);
372assertEq(m(5, 10), 5);
373
Full Screen

wrapper.js

Source: wrapper.js Github

copy
1var translate = require('./translate.js');
2var requireFromString = require('require-from-string');
3var https = require('https');
4var MemoryStream = require('memorystream');
5
6function setupMethods (soljson) {
7  var compileJSON = soljson.cwrap('compileJSON', 'string', ['string', 'number']);
8  var compileJSONMulti = null;
9  if ('_compileJSONMulti' in soljson) {
10    compileJSONMulti = soljson.cwrap('compileJSONMulti', 'string', ['string', 'number']);
11  }
12  var compileJSONCallback = null;
13  var compileStandard = null;
14  if (('_compileJSONCallback' in soljson) || ('_compileStandard' in soljson)) {
15    var copyString = function (str, ptr) {
16      var buffer = soljson._malloc(str.length + 1);
17      soljson.writeStringToMemory(str, buffer);
18      soljson.setValue(ptr, buffer, '*');
19    };
20    var wrapCallback = function (callback) {
21      return function (path, contents, error) {
22        var result = callback(soljson.Pointer_stringify(path));
23        if (typeof result.contents === 'string') {
24          copyString(result.contents, contents);
25        }
26        if (typeof result.error === 'string') {
27          copyString(result.error, error);
28        }
29      };
30    };
31
32    // This calls compile() with args || cb
33    var runWithReadCallback = function (readCallback, compile, args) {
34      if (readCallback === undefined) {
35        readCallback = function (path) {
36          return {
37            error: 'File import callback not supported'
38          };
39        };
40      }
41      var cb = soljson.Runtime.addFunction(wrapCallback(readCallback));
42      var output;
43      try {
44        args.push(cb);
45        output = compile.apply(undefined, args);
46      } catch (e) {
47        soljson.Runtime.removeFunction(cb);
48        throw e;
49      }
50      soljson.Runtime.removeFunction(cb);
51      return output;
52    };
53
54    var compileInternal = soljson.cwrap('compileJSONCallback', 'string', ['string', 'number', 'number']);
55    compileJSONCallback = function (input, optimize, readCallback) {
56      return runWithReadCallback(readCallback, compileInternal, [ input, optimize ]);
57    };
58    if ('_compileStandard' in soljson) {
59      var compileStandardInternal = soljson.cwrap('compileStandard', 'string', ['string', 'number']);
60      compileStandard = function (input, readCallback) {
61        return runWithReadCallback(readCallback, compileStandardInternal, [ input ]);
62      };
63    }
64  }
65
66  var compile = function (input, optimise, readCallback) {
67    var result = '';
68    if (readCallback !== undefined && compileJSONCallback !== null) {
69      result = compileJSONCallback(JSON.stringify(input), optimise, readCallback);
70    } else if (typeof input !== 'string' && compileJSONMulti !== null) {
71      result = compileJSONMulti(JSON.stringify(input), optimise);
72    } else {
73      result = compileJSON(input, optimise);
74    }
75    return JSON.parse(result);
76  };
77
78  // Expects a Standard JSON I/O but supports old compilers
79  var compileStandardWrapper = function (input, readCallback) {
80    if (compileStandard !== null) {
81      return compileStandard(input, readCallback);
82    }
83
84    function formatFatalError (message) {
85      return JSON.stringify({
86        errors: [
87          {
88            'type': 'SOLCError',
89            'component': 'solcjs',
90            'severity': 'error',
91            'message': message,
92            'formattedMessage': 'Error' + message
93          }
94        ]
95      });
96    }
97
98    input = JSON.parse(input);
99
100    if (input['language'] !== 'Solidity') {
101      return formatFatalError('Only Solidity sources are supported');
102    }
103
104    if (input['sources'] == null) {
105      return formatFatalError('No input specified');
106    }
107
108    // Bail out early
109    if ((input['sources'].length > 1) && (compileJSONMulti === null)) {
110      return formatFatalError('Multiple sources provided, but compiler only supports single input');
111    }
112
113    function isOptimizerEnabled (input) {
114      return input['settings'] && input['settings']['optimizer'] && input['settings']['optimizer']['enabled'];
115    }
116
117    function translateSources (input) {
118      var sources = {};
119      for (var source in input['sources']) {
120        if (input['sources'][source]['content'] !== null) {
121          sources[source] = input['sources'][source]['content'];
122        } else {
123          // force failure
124          return null;
125        }
126      }
127      return sources;
128    }
129
130    function translateOutput (output) {
131      output = translate.translateJsonCompilerOutput(JSON.parse(output));
132      if (output == null) {
133        return formatFatalError('Failed to process output');
134      }
135      return JSON.stringify(output);
136    }
137
138    var sources = translateSources(input);
139    if (sources === null) {
140      return formatFatalError('Failed to process sources');
141    }
142
143    // Try to wrap around old versions
144    if (compileJSONCallback !== null) {
145      return translateOutput(compileJSONCallback(JSON.stringify({ 'sources': sources }), isOptimizerEnabled(input), readCallback));
146    }
147
148    if (compileJSONMulti !== null) {
149      return translateOutput(compileJSONMulti(JSON.stringify({ 'sources': sources }), isOptimizerEnabled(input)));
150    }
151
152    // Try our luck with an ancient compiler
153    return translateOutput(compileJSON(sources[0], isOptimizerEnabled(input)));
154  };
155
156  var linkBytecode = function (bytecode, libraries) {
157    for (var libraryName in libraries) {
158      // truncate to 37 characters
159      var internalName = libraryName.slice(0, 36);
160      // prefix and suffix with __
161      var libLabel = '__' + internalName + Array(37 - internalName.length).join('_') + '__';
162
163      var hexAddress = libraries[libraryName];
164      if (hexAddress.slice(0, 2) !== '0x' || hexAddress.length > 42) {
165        throw new Error('Invalid address specified for ' + libraryName);
166      }
167      // remove 0x prefix
168      hexAddress = hexAddress.slice(2);
169      hexAddress = Array(40 - hexAddress.length + 1).join('0') + hexAddress;
170
171      while (bytecode.indexOf(libLabel) >= 0) {
172        bytecode = bytecode.replace(libLabel, hexAddress);
173      }
174    }
175
176    return bytecode;
177  };
178
179  var version = soljson.cwrap('version', 'string', []);
180
181  var license = function () {
182    // return undefined
183  };
184
185  if ('_license' in soljson) {
186    license = soljson.cwrap('license', 'string', []);
187  }
188
189  return {
190    version: version,
191    license: license,
192    compile: compile,
193    compileStandard: compileStandard,
194    compileStandardWrapper: compileStandardWrapper,
195    linkBytecode: linkBytecode,
196    supportsMulti: compileJSONMulti !== null,
197    supportsImportCallback: compileJSONCallback !== null,
198    supportsStandard: compileStandard !== null,
199    // Use the given version if available.
200    useVersion: function (versionString) {
201      return setupMethods(require('./bin/soljson-' + versionString + '.js'));
202    },
203    // Loads the compiler of the given version from the github repository
204    // instead of from the local filesystem.
205    loadRemoteVersion: function (versionString, cb) {
206      var mem = new MemoryStream(null, {readable: false});
207      var url = 'https://ethereum.github.io/solc-bin/bin/soljson-' + versionString + '.js';
208      https.get(url, function (response) {
209        if (response.statusCode !== 200) {
210          cb('Error retrieving binary: ' + response.statusMessage);
211        } else {
212          response.pipe(mem);
213          response.on('end', function () {
214            cb(null, setupMethods(requireFromString(mem.toString(), 'soljson-' + versionString + '.js')));
215          });
216        }
217      }).on('error', function (error) {
218        cb(error);
219      });
220    },
221    // Use this if you want to add wrapper functions around the pure module.
222    setupMethods: setupMethods
223  };
224}
225
226module.exports = setupMethods;
227
Full Screen

compile.js

Source: compile.js Github

copy
1
2var crjs = require('..');
3
4function compile(text, expected, test) {
5    var result = crjs.compile(text);
6    test.ok(result);
7    test.equal(result, expected);
8};
9
10exports['compile integer'] = function (test) {
11    compile('42', '42;', test);
12    compile('42\n\n', '42;', test);
13};
14
15exports['compile string'] = function (test) {
16    compile('"foo"', '"foo";', test);
17};
18
19exports['compile booleans'] = function (test) {
20    compile('false', 'false;', test);
21    compile('true', 'true;', test);
22};
23
24exports['compile nil'] = function (test) {
25    compile('nil', 'null;', test);
26};
27
28exports['compile name'] = function (test) {
29    compile('a', 'var a; a;', test);
30};
31
32exports['compile assignment'] = function (test) {
33    compile('a=1', 'var a; a = 1;', test);
34};
35
36exports['compile assignment expression'] = function (test) {
37    compile('a=1+2', 'var a; a = 1 + 2;', test);
38};
39
40exports['compile assignments'] = function (test) {
41    compile('a=1\nb=a', 'var a; var b; a = 1; b = a;', test);
42};
43
44exports['compile assignments separated by carriage return'] = function (test) {
45    compile('a=1\rb=a', 'var a; var b; a = 1; b = a;', test);
46};
47
48exports['compile assignments separated by carriage return line feed'] = function (test) {
49    compile('a=1\r\nb=a\r\n', 'var a; var b; a = 1; b = a;', test);
50};
51
52exports['compile assignments separated by semi colon'] = function (test) {
53    compile('a=1;b=a', 'var a; var b; a = 1; b = a;', test);
54};
55
56exports['compile call'] = function (test) {
57    compile('process "Hello, world"', 'process("Hello, world");', test);
58};
59
60exports['compile runtime call'] = function (test) {
61    compile('puts "Hello, world"', 'var $crysjs = require("crysjs"); var puts = $crysjs.runtime.puts; puts("Hello, world");', test);
62};
63
64exports['compile def'] = function (test) {
65    compile('def inc(a)\na+1\nend', 'function inc(a) { return a + 1; }', test);
66};
67
68exports['compile qualified call without arguments'] = function (test) {
69    compile('foo.bar', 'foo.bar();', test);
70};
71
72exports['compile arithmetic expressions'] = function (test) {
73    compile('1+2', '1 + 2;', test);
74    compile('1-2', '1 - 2;', test);
75    compile('3*2', '3 * 2;', test);
76    compile('3/2', '3 / 2;', test);
77    compile('1+2+3', '(1 + 2) + 3;', test);
78    compile('1+2*3', '1 + (2 * 3);', test);
79    compile('1/2+3', '(1 / 2) + 3;', test);
80    compile('1/(2+3)', '1 / (2 + 3);', test);
81};
82
83exports['compile module expression'] = function (test) {
84    compile('1%2', '1 % 2;', test);
85};
86
87exports['compile logical and expression'] = function (test) {
88    compile('1 && 2', '1 && 2;', test);
89};
90
91exports['compile logical or expression'] = function (test) {
92    compile('1 || 2', '1 || 2;', test);
93};
94
95exports['compile binary and expression'] = function (test) {
96    compile('1 & 2', '1 & 2;', test);
97};
98
99exports['compile binary or expression'] = function (test) {
100    compile('1 | 2', '1 | 2;', test);
101};
102
103exports['compile binary xor expression'] = function (test) {
104    compile('1 ^ 2', '1 ^ 2;', test);
105};
106
107exports['compile left shift expression'] = function (test) {
108    compile('1 << 2', '1 << 2;', test);
109};
110
111exports['compile right shift expression'] = function (test) {
112    compile('1 >> 2', '1 >> 2;', test);
113};
114
115exports['compile binary not expression'] = function (test) {
116    compile('~1', '~1;', test);
117};
118
119exports['compile power expression'] = function (test) {
120    compile('2 ** 3', 'Math.pow(2, 3);', test);
121};
122
123exports['compile equal expression'] = function (test) {
124    compile('2 == 3', '2 == 3;', test);
125};
126
127exports['compile not equal expression'] = function (test) {
128    compile('2 != 3', '2 != 3;', test);
129};
130
131exports['compile comparison expressions'] = function (test) {
132    compile('1<2', '1 < 2;', test);
133    compile('1>2', '1 > 2;', test);
134    compile('1<=2', '1 <= 2;', test);
135    compile('1>=2', '1 >= 2;', test);
136    compile('1+2<3', '(1 + 2) < 3;', test);
137    compile('1>2+3', '1 > (2 + 3);', test);
138};
139
140exports['compile while expressions'] = function (test) {
141    compile('while 1\na+1\nend', 'while (1) a + 1;', test);
142    compile('while 1\na+1\nb+2\nend', 'while (1) { a + 1; b + 2; }', test);
143    compile('while true\nputs 1\nend', 'var $crysjs = require("crysjs"); var puts = $crysjs.runtime.puts; while (true) puts(1);', test);
144};
145
146exports['compile indexed expressions'] = function (test) {
147    compile('foo[1]', 'foo[1];', test);
148    compile('foo[1,2]', 'foo[1, 2];', test);
149};
150
151exports['compile array expressions'] = function (test) {
152    compile('[1,2]', '[1, 2];', test);
153    compile('[1]', '[1];', test);
154};
155
156exports['compile keyword expression'] = function (test) {
157    compile(':foo', '":foo";', test);
158};
159
160
Full Screen

testGlobals.js

Source: testGlobals.js Github

copy
1// |jit-test| test-also-noasmjs
2load(libdir + "asm.js");
3load(libdir + "asserts.js");
4
5assertAsmTypeFail(USE_ASM + "var i; function f(){} return f");
6assertEq(asmLink(asmCompile(USE_ASM + "var i=0; function f(){} return f"))(), undefined);
7assertEq(asmLink(asmCompile(USE_ASM + "const i=0; function f(){} return f"))(), undefined);
8assertEq(asmLink(asmCompile(USE_ASM + "var i=42; function f(){ return i|0 } return f"))(), 42);
9assertEq(asmLink(asmCompile(USE_ASM + "const i=42; function f(){ return i|0 } return f"))(), 42);
10assertEq(asmLink(asmCompile(USE_ASM + "var i=4.2; function f(){ return +i } return f"))(), 4.2);
11assertEq(asmLink(asmCompile(USE_ASM + "const i=4.2; function f(){ return +i } return f"))(), 4.2);
12assertAsmTypeFail(USE_ASM + "var i=42; function f(){ return +(i+.1) } return f");
13assertAsmTypeFail(USE_ASM + "const i=42; function f(){ return +(i+.1) } return f");
14assertAsmTypeFail(USE_ASM + "var i=1.2; function f(){ return i|0 } return f");
15assertAsmTypeFail(USE_ASM + "const i=1.2; function f(){ return i|0 } return f");
16assertAsmTypeFail(USE_ASM + "var i=0; function f(e){ e=+e; i=e } return f");
17assertAsmTypeFail(USE_ASM + "var d=0.1; function f(i){ i=i|0; d=i } return f");
18assertEq(asmLink(asmCompile(USE_ASM + "var i=13; function f(j) { j=j|0; i=j; return i|0 } return f"))(42), 42);
19assertEq(asmLink(asmCompile(USE_ASM + "var d=.1; function f(e) { e=+e; d=e; return +e } return f"))(42.1), 42.1);
20assertEq(asmLink(asmCompile(USE_ASM + "var i=13; function f(i, j) { i=i|0; j=j|0; i=j; return i|0 } return f"))(42,43), 43);
21assertEq(asmLink(asmCompile(USE_ASM + "var i=13; function f(j) { j=j|0; var i=0; i=j; return i|0 } return f"))(42), 42);
22
23var f = asmLink(asmCompile(USE_ASM + "var i=13; function f(j) { j=j|0; if ((j|0) != -1) { i=j } else { return i|0 } return 0 } return f"));
24assertEq(f(-1), 13);
25assertEq(f(42), 0);
26assertEq(f(-1), 42);
27
28assertAsmTypeFail(USE_ASM + "var i=13; function f() { var j=i; return j|0 } return f");
29assertAsmTypeFail(USE_ASM + "var i=13.37; function f() { var j=i; return +j } return f");
30assertAsmTypeFail('global', USE_ASM + "var f32 = global.Math.fround; var i=f32(13.37); function f() { var j=i; return f32(j) } return f");
31
32assertEq(asmLink(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { var j=i; return +j } return f'), {Infinity:Infinity})(), Infinity);
33assertEq(asmLink(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { var j=i; return +j } return f'), {NaN:NaN})(), NaN);
34
35assertEq(asmLink(asmCompile(USE_ASM + "const i=13; function f() { var j=i; return j|0 } return f"))(), 13);
36assertEq(asmLink(asmCompile(USE_ASM + "const i=13.37; function f() { var j=i; return +j } return f"))(), 13.37);
37assertEq(asmLink(asmCompile('global', USE_ASM + "var f32 = global.Math.fround; const i=f32(13.37); function f() { var j=i; return f32(j) } return f"), this)(), Math.fround(13.37));
38
39assertAsmTypeFail(USE_ASM + "function f() { var j=i; return j|0 } return f");
40assertAsmTypeFail(USE_ASM + "function i(){} function f() { var j=i; return j|0 } return f");
41assertAsmTypeFail(USE_ASM + "function f() { var j=i; return j|0 } var i = [f]; return f");
42assertAsmTypeFail('global', USE_ASM + "var i=global.Math.fround; function f() { var j=i; return j|0 } return f");
43assertAsmTypeFail('global', 'imp', USE_ASM + "var i=imp.f; function f() { var j=i; return j|0 } return f");
44assertAsmTypeFail('global', 'imp', USE_ASM + "var i=imp.i|0; function f() { var j=i; return j|0 } return f");
45assertAsmTypeFail('global', 'imp', USE_ASM + "var i=+imp.i; function f() { var j=i; return +j } return f");
46assertAsmTypeFail('global', 'imp', USE_ASM + "const i=imp.i|0; function f() { var j=i; return j|0 } return f");
47assertAsmTypeFail('global', 'imp', USE_ASM + "const i=+imp.i; function f() { var j=i; return +j } return f");
48assertAsmTypeFail('global', 'imp', 'heap', USE_ASM + "var i=new global.Float32Array(heap); function f() { var j=i; return +j } return f");
49
50assertAsmTypeFail('global', USE_ASM + "var i=global; function f() { return i|0 } return f");
51assertAsmTypeFail('global', USE_ASM + "const i=global; function f() { return i|0 } return f");
52assertAsmTypeFail('global', USE_ASM + "var i=global|0; function f() { return i|0 } return f");
53assertAsmTypeFail('global', USE_ASM + "const i=global|0; function f() { return i|0 } return f");
54assertAsmTypeFail('global', USE_ASM + "var j=0;var i=j.i|0; function f() { return i|0 } return f");
55assertAsmTypeFail('global', USE_ASM + "var i=global.i|0; function f() { return i|0 } return f");
56assertAsmTypeFail('global', USE_ASM + "const i=global.i|0; function f() { return i|0 } return f");
57assertAsmTypeFail('global', USE_ASM + "var i=global.i|0; function f() { return i|0 } return f");
58assertAsmTypeFail('global', USE_ASM + 'var i=global.Infinity; function f() { i = 0.0 } return f');
59assertAsmLinkAlwaysFail(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), undefined);
60assertAsmLinkAlwaysFail(asmCompile('global', USE_ASM + 'const i=global.Infinity; function f() { return +i } return f'), undefined);
61assertAsmLinkAlwaysFail(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), null);
62assertAsmLinkAlwaysFail(asmCompile('global', USE_ASM + 'const i=global.Infinity; function f() { return +i } return f'), null);
63assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), 3);
64assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), {});
65assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), {Infinity:NaN});
66assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), {Infinity:-Infinity});
67assertEq(asmLink(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), {Infinity:Infinity})(), Infinity);
68assertEq(asmLink(asmCompile('global', USE_ASM + 'const i=global.Infinity; function f() { return +i } return f'), {Infinity:Infinity})(), Infinity);
69assertEq(asmLink(asmCompile('global', USE_ASM + 'var i=global.Infinity; function f() { return +i } return f'), this)(), Infinity);
70assertEq(asmLink(asmCompile('global', USE_ASM + 'const i=global.Infinity; function f() { return +i } return f'), this)(), Infinity);
71assertAsmLinkAlwaysFail(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), undefined);
72assertAsmLinkAlwaysFail(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), null);
73assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), 3);
74assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), {});
75assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), {Infinity:Infinity});
76assertAsmLinkFail(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), {Infinity:-Infinity});
77assertEq(asmLink(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), {NaN:NaN})(), NaN);
78assertEq(asmLink(asmCompile('global', USE_ASM + 'const i=global.NaN; function f() { return +i } return f'), {NaN:NaN})(), NaN);
79assertEq(asmLink(asmCompile('global', USE_ASM + 'var i=global.NaN; function f() { return +i } return f'), this)(), NaN);
80assertEq(asmLink(asmCompile('global', USE_ASM + 'const i=global.NaN; function f() { return +i } return f'), this)(), NaN);
81
82assertAsmLinkFail(asmCompile('glob','foreign','buf', USE_ASM + 'var t = new glob.Int32Array(buf); function f() {} return f'), {get Int32Array(){return Int32Array}}, null, new ArrayBuffer(4096))
83assertAsmLinkFail(asmCompile('glob','foreign','buf', USE_ASM + 'const t = new glob.Int32Array(buf); function f() {} return f'), {get Int32Array(){return Int32Array}}, null, new ArrayBuffer(4096))
84assertAsmLinkFail(asmCompile('glob','foreign','buf', USE_ASM + 'var t = new glob.Int32Array(buf); function f() {} return f'), new Proxy(this, {}), null, new ArrayBuffer(4096))
85assertAsmLinkFail(asmCompile('glob','foreign','buf', USE_ASM + 'const t = new glob.Int32Array(buf); function f() {} return f'), new Proxy(this, {}), null, new ArrayBuffer(4096))
86assertAsmLinkFail(asmCompile('glob', USE_ASM + 'var t = glob.Math.sin; function f() {} return f'), {get Math(){return Math}});
87assertAsmLinkFail(asmCompile('glob', USE_ASM + 'var t = glob.Math.sin; function f() {} return f'), new Proxy(this, {}));
88assertAsmLinkFail(asmCompile('glob', USE_ASM + 'var t = glob.Math.sin; function f() {} return f'), {Math:{get sin(){return Math.sin}}});
89assertAsmLinkFail(asmCompile('glob', USE_ASM + 'var t = glob.Math.sin; function f() {} return f'), {Math:new Proxy(Math, {})});
90assertAsmLinkFail(asmCompile('glob', USE_ASM + 'var t = glob.Infinity; function f() {} return f'), {get Infinity(){return Infinity}});
91assertAsmLinkFail(asmCompile('glob', USE_ASM + 'var t = glob.Infinity; function f() {} return f'), new Proxy(this, {}));
92assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = foreign.x|0; function f() {} return f'), null, {get x(){return 42}})
93assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = +foreign.x; function f() {} return f'), null, {get x(){return 42}})
94assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = foreign.x|0; function f() {} return f'), null, new Proxy({x:42}, {}));
95assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = +foreign.x; function f() {} return f'), null, new Proxy({x:42}, {}));
96assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = foreign.x; function f() {} return f'), null, {get x(){return function(){}}})
97assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = foreign.x; function f() {} return f'), null, new Proxy({x:function(){}}, {}));
98assertAsmTypeFail('global', 'imp', USE_ASM + "var i=imp; function f() { return i|0 } return f");
99assertAsmTypeFail('global', 'imp', USE_ASM + "var j=0;var i=j.i|0; function f() { return i|0 } return f");
100assertAsmLinkAlwaysFail(asmCompile('global','imp', USE_ASM + "var i=imp.i|0; function f() { return i|0 } return f"), null, undefined);
101assertAsmLinkAlwaysFail(asmCompile('global','imp', USE_ASM + "var i=imp.i|0; function f() { return i|0 } return f"), this, undefined);
102assertAsmLinkAlwaysFail(asmCompile('global', 'imp', USE_ASM + "var i=imp.i|0; function f() { return i|0 } return f"), null, null);
103assertAsmLinkAlwaysFail(asmCompile('global', 'imp', USE_ASM + "var i=imp.i|0; function f() { return i|0 } return f"), this, null);
104assertAsmLinkFail(asmCompile('global', 'imp', USE_ASM + "var i=imp.i|0; function f() { return i|0 } return f"), this, 42);
105assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "var i=imp.i|0; function f() { return i|0 } return f")(null, {i:42})), 42);
106assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "const i=imp.i|0; function f() { return i|0 } return f")(null, {i:42})), 42);
107assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "var i=imp.i|0; function f() { return i|0 } return f")(null, {i:1.4})), 1);
108assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "const i=imp.i|0; function f() { return i|0 } return f")(null, {i:1.4})), 1);
109assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "var i=+imp.i; function f() { return +i } return f")(null, {i:42})), 42);
110assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "const i=+imp.i; function f() { return +i } return f")(null, {i:42})), 42);
111assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "var i=+imp.i; function f() { return +i } return f")(this, {i:1.4})), 1.4);
112assertEq(asmLink(asmCompile('global', 'imp', USE_ASM + "const i=+imp.i; function f() { return +i } return f")(this, {i:1.4})), 1.4);
113assertEq(asmLink(asmCompile(USE_ASM + "var g=0; function f() { var i=42; while (1) { break; } g = i; return g|0 } return f"))(), 42);
114assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = +foreign.x; function f() {} return f'), null, {x:{valueOf:function() { return 42 }}});
115assertAsmLinkFail(asmCompile('glob','foreign', USE_ASM + 'var i = foreign.x|0; function f() {} return f'), null, {x:{valueOf:function() { return 42 }}});
116assertEq(asmLink(asmCompile('glob','foreign', USE_ASM + 'var i = foreign.x|0; function f() { return i|0} return f'), null, {x:"blah"})(), 0);
117assertEq(asmLink(asmCompile('glob','foreign', USE_ASM + 'var i = +foreign.x; function f() { return +i} return f'), null, {x:"blah"})(), NaN);
118assertEq(asmLink(asmCompile('glob','foreign', USE_ASM + 'var tof = glob.Math.fround; var i = tof(foreign.x); function f() { return +i} return f'), this, {x:"blah"})(), NaN);
119assertThrowsInstanceOf(() => asmCompile('glob','foreign',USE_ASM + 'var i = foreign.x|0; function f() { return i|0} return f')(null, {x:Symbol("blah")}), TypeError);
120assertThrowsInstanceOf(() => asmCompile('glob','foreign',USE_ASM + 'var i = +foreign.x; function f() { return +i} return f')(null, {x:Symbol("blah")}), TypeError);
121assertThrowsInstanceOf(() => asmCompile('glob','foreign',USE_ASM + 'var tof = glob.Math.fround; var i = tof(foreign.x); function f() { return +i} return f')(this, {x:Symbol("blah")}), TypeError);
122
123// Temporary workaround; this test can be removed when Emscripten is fixed and
124// the fix has propagated out to most apps:
125assertEq(asmLink(asmCompile('glob','foreign', USE_ASM + 'var i = foreign.i|0; function f() { return i|0} return f'), null, {i:function(){}})(), 0);
126assertEq(asmLink(asmCompile('glob','foreign', USE_ASM + 'var i = +foreign.i; function f() { return +i} return f'), null, {i:function(){}})(), NaN);
127assertEq(asmLink(asmCompile('glob','foreign', USE_ASM + 'var tof = glob.Math.fround; var i = tof(foreign.i); function f() { return +i} return f'), this, {i:function(){}})(), NaN);
128var module = asmCompile('glob','foreign', USE_ASM + 'var i = foreign.i|0; function f() { return i|0} return f');
129var fun = function() {}
130fun.valueOf = function() {}
131assertAsmLinkFail(module, null, {i:fun});
132var fun = function() {}
133fun.toString = function() {}
134assertAsmLinkFail(module, null, {i:fun});
135var fun = function() {}
136var origFunToString = Function.prototype.toString;
137Function.prototype.toString = function() {}
138assertAsmLinkFail(module, null, {i:fun});
139Function.prototype.toString = origFunToString;
140assertEq(asmLink(module, null, {i:fun})(), 0);
141Function.prototype.valueOf = function() {}
142assertAsmLinkFail(module, null, {i:fun});
143delete Function.prototype.valueOf;
144assertEq(asmLink(module, null, {i:fun})(), 0);
145var origObjValueOf = Object.prototype.valueOf;
146Object.prototype.valueOf = function() {}
147assertAsmLinkFail(module, null, {i:fun});
148Object.prototype.valueOf = origObjValueOf;
149assertEq(asmLink(module, null, {i:fun})(), 0);
150Object.prototype.toString = function() {}
151assertEq(asmLink(module, null, {i:fun})(), 0);
152
153var f1 = asmCompile('global', 'foreign', 'heap', USE_ASM + 'var i32 = new global.Int32Array(heap); function g() { return i32[4]|0 } return g');
154var global = this;
155var ab = new ArrayBuffer(4096);
156var p = new Proxy(global,
157                  {has:function(name) { f1(global, null, ab); return true},
158                   getOwnPropertyDescriptor:function(name) { return {configurable:true, value:Int32Array}}});
159new Int32Array(ab)[4] = 42;
160assertEq(f1(p, null, ab)(), 42);
161
162// GVN checks
163assertEq(asmLink(asmCompile(USE_ASM + "var g=0; function f() { var x = 0; g = 1; x = g; return (x+g)|0 } return f"))(), 2);
164assertEq(asmLink(asmCompile(USE_ASM + "var g=0; function f() { var x = 0; g = 1; x = g; g = 2; return (x+g)|0 } return f"))(), 3);
165assertEq(asmLink(asmCompile(USE_ASM + "var g=0; var h=0; function f() { var x = 0; g = 1; x = g; h = 3; return (x+g)|0 } return f"))(), 2);
166
Full Screen

test-numbers.js

Source: test-numbers.js Github

copy
1import assert from 'assert';
2import { compileCode } from  '../src/compiler/compiler';
3
4
5describe('Numbers', () => {
6
7  it('should compile a positive integer', () => {
8    const toCompile = '1';
9    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
10  });
11
12  it('should compile a negative integer', () => {
13    const toCompile = '-1';
14    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
15  });
16
17  it('should compile a positive float', () => {
18    const toCompile = '32.3456';
19    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
20  });
21
22  it('should compile a negative float', () => {
23    const toCompile = '-32.3456';
24    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
25  });
26
27  it('should compile an positive exponent', () => {
28    const toCompile = '123e5';
29    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
30  });
31
32  it('should compile an negative exponent', () => {
33    const toCompile = '123e-5';
34    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
35  });
36
37  it('should compile a negative number with a negative exponent', () => {
38    const toCompile = '-123e-5';
39    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
40  });
41
42  it('should compile a hexidecimal', () => {
43    const toCompile = '0xFF';
44    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
45  });
46
47  it('should compile Infinity', () => {
48    const toCompile = 'Infinity';
49    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
50  });
51
52  it('should compile NaN', () => {
53    const toCompile = 'NaN';
54    assert.equal(compileCode(toCompile).trim(), toCompile + ';');
55  });
56
57});
58
Full Screen

compiler.py

Source: compiler.py Github

copy
1import re
2
3PATT_BASE_DIR = re.compile(r'BASE_DIR\s*=\s*os.path.dirname\s*\(\s*os.path.dirname\s*\(\s*os.path.abspath\s*\(\s*__file__\s*\)\s*\)\s*\)')
4PATT_INSTALLED_APPS = re.compile(r"(?ms:INSTALLED_APPS\s.*?=\s.*?\[.*?\])")
5PATT_MIDDLEWARE = re.compile(r"(?ms:MIDDLEWARE\s.*?=\s.*?\[.*?\])")
6PATT_SECRET_KEY = re.compile(r"SECRET_KEY\s*=\s*[\'\"](.*?)[\'\"]")
7PATT_DEBUG = re.compile(r"DEBUG\s*=\s*(False|True)")
8PATT_ALLOWED_HOSTS = re.compile(r"ALLOWED_HOSTS\s*=\s*\[([\'\"]*.*?[\'\"]*)\]")
9PATT_X_FRAME_OPTIONS = re.compile(r"\nX_FRAME_OPTIONS\s*=\s*('ALLOWALL')")
10PATT_LANGUAGE_CODE = re.compile(r"LANGUAGE_CODE\s*=\s*'(.*?)'")
11PATT_TIME_ZONE = re.compile(r"TIME_ZONE\s*=\s*'(.*?)'")
12PATT_USE_I18N = re.compile(r"USE_I18N\s*=\s*(False|True)")
13PATT_USE_L10N = re.compile(r"USE_L10N\s*=\s*(False|True)")
14PATT_DATABASES = re.compile(r'(?ms:DATABASES\s*=\s*\{.*)')
15PATT_USE_TZ = re.compile(r"USE_TZ\s*=\s*(False|True)")
16PATT_CORS_ORIGIN_ALLOW_ALL = re.compile(r"CORS_ORIGIN_ALLOW_ALL\s*=\s*(False|True)")
17PATT_STATIC_URL = re.compile(r"STATIC_URL\s*=\s*[\'\"](.*?)[\'\"]")
18PATT_TEMPLATES = re.compile(r'(?ms:TEMPLATES\s*=\s*\[.*)')
19PATT_ROOT_URLCONF = re.compile(r"ROOT_URLCONF\s*=\s*[\'\"](.*?)[\'\"]")
20
21PATT_CHARS = re.compile(r'^[a-zA-Z_]*$')
22PATT_CHARS_REVERSED = re.compile(r'[^a-zA-Z_]+')
23PATT_DIGITS_WHOLE = re.compile(r'^[1-9][0-9]*$')
24PATT_DIGITS_REVERSED = re.compile(r'[^0-9]+')
25PATT_CHARSNUMBER = re.compile(r'^[a-zA-Z0-9]*$')
26PATT_REPLACE = re.compile(r'[$][{](.*?)[}]') # 模板定位替换语法
27PATT_TITLE_NAME = re.compile(r'admin.site.site_title\s*=\s*[\"\'](.*?)[\"\']')
28PATT_HEADER_NAME = re.compile(r'admin.site.site_header\s*=\s*[\"\'](.*?)[\"\']')
29PATT_URLPATTERNS = re.compile(r'(?ms:urlpatterns\s*=\s*\[.*)')
30PATT_MODEL = re.compile(r'class\s+(.+?)\(\s*[a-zA-Z0-9]*?[.]*?Model\s*\):') # 定位模型类
31PATT_CAPTURE_URLSPATH_ARGS = re.compile(r'<(.+?)>') # 捕捉路由参数信息
32PATT_FUNC_ARGS = re.compile(r'def\s+.+?\((.*?)\)')
33PATT_COMMENT = re.compile(r'(\s*#.*?$)') # 注释
34PATT_REGISTER = re.compile(r'admin.site.register\s*\(\s*(.+?)\s*\)')
35PATT_INCLUDE = re.compile(r'include\s*\((.*)\)')
36
Full Screen

dellos6.py

Source: dellos6.py Github

copy
1#
2# (c) 2015 Peter Sprygada, <[email protected]>
3#
4# Copyright (c) 2016 Dell Inc.
5#
6# This code is part of Ansible, but is an independent component.
7# This particular file snippet, and this file snippet only, is BSD licensed.
8# Modules you write using this snippet, which is embedded dynamically by Ansible
9# still belong to the author of the module, and may assign their own license
10# to the complete work.
11#
12# Redistribution and use in source and binary forms, with or without modification,
13# are permitted provided that the following conditions are met:
14#
15#    * Redistributions of source code must retain the above copyright
16#      notice, this list of conditions and the following disclaimer.
17#    * Redistributions in binary form must reproduce the above copyright notice,
18#      this list of conditions and the following disclaimer in the documentation
19#      and/or other materials provided with the distribution.
20#
21# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
22# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
24# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
26# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
29# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30#
31
32import re
33
34from ansible.module_utils.shell import CliBase
35from ansible.module_utils.network import Command, register_transport, to_list
36from ansible.module_utils.netcfg import NetworkConfig, ConfigLine, ignore_line, DEFAULT_COMMENT_TOKENS
37
38
39def get_config(module):
40    contents = module.params['config']
41
42    if not contents:
43        contents = module.config.get_config()
44        module.params['config'] = contents
45
46    return Dellos6NetworkConfig(indent=0, contents=contents[0])
47
48
49def get_sublevel_config(running_config, module):
50    contents = list()
51    current_config_contents = list()
52    sublevel_config = Dellos6NetworkConfig(indent=0)
53
54    obj = running_config.get_object(module.params['parents'])
55    if obj:
56        contents = obj.children
57
58    for c in contents:
59        if isinstance(c, ConfigLine):
60            current_config_contents.append(c.raw)
61    sublevel_config.add(current_config_contents, module.params['parents'])
62
63    return sublevel_config
64
65
66def os6_parse(lines, indent=None, comment_tokens=None):
67    sublevel_cmds = [
68        re.compile(r'^vlan.*$'),
69        re.compile(r'^stack.*$'),
70        re.compile(r'^interface.*$'),
71        re.compile(r'line (console|telnet|ssh).*$'),
72        re.compile(r'ip ssh !(server).*$'),
73        re.compile(r'ip (dhcp|vrf).*$'),
74        re.compile(r'(ip|mac|management|arp) access-list.*$'),
75        re.compile(r'ipv6 (dhcp|router).*$'),
76        re.compile(r'mail-server.*$'),
77        re.compile(r'vpc domain.*$'),
78        re.compile(r'router.*$'),
79        re.compile(r'route-map.*$'),
80        re.compile(r'policy-map.*$'),
81        re.compile(r'class-map match-all.*$'),
82        re.compile(r'captive-portal.*$'),
83        re.compile(r'admin-profile.*$'),
84        re.compile(r'link-dependency group.*$'),
85        re.compile(r'banner motd.*$'),
86        re.compile(r'openflow.*$'),
87        re.compile(r'support-assist.*$'),
88        re.compile(r'(radius-server|tacacs-server) host.*$')]
89
90    childline = re.compile(r'^exit$')
91
92    config = list()
93    inSubLevel = False
94    parent = None
95    children = list()
96    subcommandcount = 0
97
98    for line in str(lines).split('\n'):
99        text = str(re.sub(r'([{};])', '', line)).strip()
100
101        cfg = ConfigLine(text)
102        cfg.raw = line
103
104        if not text or ignore_line(text, comment_tokens):
105            parent = None
106            children = list()
107            inSubLevel = False
108            continue
109
110        if inSubLevel is False:
111            for pr in sublevel_cmds:
112                if pr.match(line):
113                    parent = cfg
114                    config.append(parent)
115                    inSubLevel = True
116                    continue
117            if parent is None:
118                config.append(cfg)
119
120        # handle sub level commands
121        elif inSubLevel and childline.match(line):
122            parent.children = children
123            inSubLevel = False
124            children = list()
125            parent = None
126
127        # handle top level commands
128        elif inSubLevel:
129            children.append(cfg)
130            cfg.parents = [parent]
131            config.append(cfg)
132
133        else:  # global level
134            config.append(cfg)
135
136    return config
137
138
139class Dellos6NetworkConfig(NetworkConfig):
140
141    def load(self, contents):
142        self._config = os6_parse(contents, self.indent, DEFAULT_COMMENT_TOKENS)
143
144
145class Cli(CliBase):
146
147    NET_PASSWD_RE = re.compile(r"[\r\n]?password:\s?$", re.I)
148
149    CLI_PROMPTS_RE = [
150        re.compile(r"[\r\n]?[\w+\-\.:\/\[\]]+(?:\([^\)]+\)){,3}(?:>|#) ?$"),
151        re.compile(r"\[\w+\@[\w\-\.]+(?: [^\]])\] ?[>#\$] ?$")
152    ]
153
154    CLI_ERRORS_RE = [
155        re.compile(r"% ?Error"),
156        re.compile(r"% ?Bad secret"),
157        re.compile(r"invalid input", re.I),
158        re.compile(r"(?:incomplete|ambiguous) command", re.I),
159        re.compile(r"connection timed out", re.I),
160        re.compile(r"[^\r\n]+ not found", re.I),
161        re.compile(r"'[^']' +returned error code: ?\d+")]
162
163
164    def connect(self, params, **kwargs):
165        super(Cli, self).connect(params, kickstart=False, **kwargs)
166
167
168    def authorize(self, params, **kwargs):
169        passwd = params['auth_pass']
170        self.run_commands(
171            Command('enable', prompt=self.NET_PASSWD_RE, response=passwd)
172        )
173        self.run_commands('terminal length 0')
174
175
176    def configure(self, commands, **kwargs):
177        cmds = ['configure terminal']
178        cmds.extend(to_list(commands))
179        cmds.append('end')
180        responses = self.execute(cmds)
181        responses.pop(0)
182        return responses
183
184
185    def get_config(self, **kwargs):
186        return self.execute(['show running-config'])
187
188
189    def load_config(self, commands, **kwargs):
190        return self.configure(commands)
191
192
193    def save_config(self):
194        self.execute(['copy running-config startup-config'])
195
196
197Cli = register_transport('cli', default=True)(Cli)
198
Full Screen

install_lib.py

Source: install_lib.py Github

copy
1"""distutils.command.install_lib
2
3Implements the Distutils 'install_lib' command
4(install all Python modules)."""
5
6__revision__ = "$Id$"
7
8import os
9import sys
10
11from distutils.core import Command
12from distutils.errors import DistutilsOptionError
13
14
15# Extension for Python source files.
16if hasattr(os, 'extsep'):
17    PYTHON_SOURCE_EXTENSION = os.extsep + "py"
18else:
19    PYTHON_SOURCE_EXTENSION = ".py"
20
21class install_lib(Command):
22
23    description = "install all Python modules (extensions and pure Python)"
24
25    # The byte-compilation options are a tad confusing.  Here are the
26    # possible scenarios:
27    #   1) no compilation at all (--no-compile --no-optimize)
28    #   2) compile .pyc only (--compile --no-optimize; default)
29    #   3) compile .pyc and "level 1" .pyo (--compile --optimize)
30    #   4) compile "level 1" .pyo only (--no-compile --optimize)
31    #   5) compile .pyc and "level 2" .pyo (--compile --optimize-more)
32    #   6) compile "level 2" .pyo only (--no-compile --optimize-more)
33    #
34    # The UI for this is two option, 'compile' and 'optimize'.
35    # 'compile' is strictly boolean, and only decides whether to
36    # generate .pyc files.  'optimize' is three-way (0, 1, or 2), and
37    # decides both whether to generate .pyo files and what level of
38    # optimization to use.
39
40    user_options = [
41        ('install-dir=', 'd', "directory to install to"),
42        ('build-dir=','b', "build directory (where to install from)"),
43        ('force', 'f', "force installation (overwrite existing files)"),
44        ('compile', 'c', "compile .py to .pyc [default]"),
45        ('no-compile', None, "don't compile .py files"),
46        ('optimize=', 'O',
47         "also compile with optimization: -O1 for \"python -O\", "
48         "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
49        ('skip-build', None, "skip the build steps"),
50        ]
51
52    boolean_options = ['force', 'compile', 'skip-build']
53    negative_opt = {'no-compile' : 'compile'}
54
55    def initialize_options(self):
56        # let the 'install' command dictate our installation directory
57        self.install_dir = None
58        self.build_dir = None
59        self.force = 0
60        self.compile = None
61        self.optimize = None
62        self.skip_build = None
63
64    def finalize_options(self):
65        # Get all the information we need to install pure Python modules
66        # from the umbrella 'install' command -- build (source) directory,
67        # install (target) directory, and whether to compile .py files.
68        self.set_undefined_options('install',
69                                   ('build_lib', 'build_dir'),
70                                   ('install_lib', 'install_dir'),
71                                   ('force', 'force'),
72                                   ('compile', 'compile'),
73                                   ('optimize', 'optimize'),
74                                   ('skip_build', 'skip_build'),
75                                  )
76
77        if self.compile is None:
78            self.compile = 1
79        if self.optimize is None:
80            self.optimize = 0
81
82        if not isinstance(self.optimize, int):
83            try:
84                self.optimize = int(self.optimize)
85                if self.optimize not in (0, 1, 2):
86                    raise AssertionError
87            except (ValueError, AssertionError):
88                raise DistutilsOptionError, "optimize must be 0, 1, or 2"
89
90    def run(self):
91        # Make sure we have built everything we need first
92        self.build()
93
94        # Install everything: simply dump the entire contents of the build
95        # directory to the installation directory (that's the beauty of
96        # having a build directory!)
97        outfiles = self.install()
98
99        # (Optionally) compile .py to .pyc
100        if outfiles is not None and self.distribution.has_pure_modules():
101            self.byte_compile(outfiles)
102
103    # -- Top-level worker functions ------------------------------------
104    # (called from 'run()')
105
106    def build(self):
107        if not self.skip_build:
108            if self.distribution.has_pure_modules():
109                self.run_command('build_py')
110            if self.distribution.has_ext_modules():
111                self.run_command('build_ext')
112
113    def install(self):
114        if os.path.isdir(self.build_dir):
115            outfiles = self.copy_tree(self.build_dir, self.install_dir)
116        else:
117            self.warn("'%s' does not exist -- no Python modules to install" %
118                      self.build_dir)
119            return
120        return outfiles
121
122    def byte_compile(self, files):
123        if sys.dont_write_bytecode:
124            self.warn('byte-compiling is disabled, skipping.')
125            return
126
127        from distutils.util import byte_compile
128
129        # Get the "--root" directory supplied to the "install" command,
130        # and use it as a prefix to strip off the purported filename
131        # encoded in bytecode files.  This is far from complete, but it
132        # should at least generate usable bytecode in RPM distributions.
133        install_root = self.get_finalized_command('install').root
134
135        if self.compile:
136            byte_compile(files, optimize=0,
137                         force=self.force, prefix=install_root,
138                         dry_run=self.dry_run)
139        if self.optimize > 0:
140            byte_compile(files, optimize=self.optimize,
141                         force=self.force, prefix=install_root,
142                         verbose=self.verbose, dry_run=self.dry_run)
143
144
145    # -- Utility methods -----------------------------------------------
146
147    def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):
148        if not has_any:
149            return []
150
151        build_cmd = self.get_finalized_command(build_cmd)
152        build_files = build_cmd.get_outputs()
153        build_dir = getattr(build_cmd, cmd_option)
154
155        prefix_len = len(build_dir) + len(os.sep)
156        outputs = []
157        for file in build_files:
158            outputs.append(os.path.join(output_dir, file[prefix_len:]))
159
160        return outputs
161
162    def _bytecode_filenames(self, py_filenames):
163        bytecode_files = []
164        for py_file in py_filenames:
165            # Since build_py handles package data installation, the
166            # list of outputs can contain more than just .py files.
167            # Make sure we only report bytecode for the .py files.
168            ext = os.path.splitext(os.path.normcase(py_file))[1]
169            if ext != PYTHON_SOURCE_EXTENSION:
170                continue
171            if self.compile:
172                bytecode_files.append(py_file + "c")
173            if self.optimize > 0:
174                bytecode_files.append(py_file + "o")
175
176        return bytecode_files
177
178
179    # -- External interface --------------------------------------------
180    # (called by outsiders)
181
182    def get_outputs(self):
183        """Return the list of files that would be installed if this command
184        were actually run.  Not affected by the "dry-run" flag or whether
185        modules have actually been built yet.
186        """
187        pure_outputs = \
188            self._mutate_outputs(self.distribution.has_pure_modules(),
189                                 'build_py', 'build_lib',
190                                 self.install_dir)
191        if self.compile:
192            bytecode_outputs = self._bytecode_filenames(pure_outputs)
193        else:
194            bytecode_outputs = []
195
196        ext_outputs = \
197            self._mutate_outputs(self.distribution.has_ext_modules(),
198                                 'build_ext', 'build_lib',
199                                 self.install_dir)
200
201        return pure_outputs + bytecode_outputs + ext_outputs
202
203    def get_inputs(self):
204        """Get the list of files that are input to this command, ie. the
205        files that get installed as they are named in the build tree.
206        The files in this list correspond one-to-one to the output
207        filenames returned by 'get_outputs()'.
208        """
209        inputs = []
210
211        if self.distribution.has_pure_modules():
212            build_py = self.get_finalized_command('build_py')
213            inputs.extend(build_py.get_outputs())
214
215        if self.distribution.has_ext_modules():
216            build_ext = self.get_finalized_command('build_ext')
217            inputs.extend(build_ext.get_outputs())
218
219        return inputs
220
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)