/
core.js
2236 lines (1787 loc) · 57.8 KB
/
core.js
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
'use strict';
const op = {};
exports.op = op;
const os = process.browser ? null : require('os');
const Hash = require('./hash.js');
const CodeRef = require('./code-ref.js');
const Ctx = require('./ctx.js');
const NQPInt = require('./nqp-int.js');
const NQPNum = require('./nqp-num.js');
const NQPStr = require('./nqp-str.js');
const NQPException = require('./nqp-exception.js');
const reprs = require('./reprs.js');
const hll = require('./hll.js');
const NQPObject = require('./nqp-object.js');
const constants = require('./constants.js');
const containerSpecs = require('./container-specs.js');
const Null = require('./null.js');
const null_s = require('./null_s.js');
const BOOT = require('./BOOT.js');
const sixmodel = require('./sixmodel.js');
const Capture = require('./capture.js');
const shortid = require('shortid');
const stripMarks = require('./strip-marks.js');
const codecs = require('./codecs.js');
const graphemeRegexp = require('./graphemes.js').regexp;
const foldCase = require('fold-case');
const xregexp = require('xregexp');
const graphemes = require('./graphemes.js');
const unicodeCollationAlgorithm = require('unicode-collation-algorithm');
const unicodeData = require('nqp-unicode-data');
const resolveSourceMap = process.browser ? require('./resolve-sourcemap-browser.js') : require('./resolve-sourcemap.js');
const path = process.browser ? null : require('path');
const globalContext = require('./global-context.js');
const nullStr = require('./null_s.js');
exports.CodeRef = CodeRef;
op.isinvokable = function(obj) {
return (obj instanceof CodeRef || (obj.$$STable && obj.$$STable.invocationSpec) ? 1 : 0);
};
op.escape = function(str) {
return str
.replace(/\\/g, '\\\\')
.replace(/\x1B/g, '\\e')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\f/g, '\\f')
.replace(/[\b]/g, '\\b')
.replace(/"/g, '\\"');
};
const uniData = require('./unicode-data.js');
op.unipropcode = function(name) {
const mangled = name.toLowerCase().replace(/_/g, '');
return uniData.propcodes[mangled];
};
op.getuniprop_str = function(codePoint, propCode) {
/* TODO - load and use real data */
if (propCode === 84) {
return codePoint == 780 ? '230' : '0';
}
const got = uniData.props[propCode][codePoint];
return got === undefined ? 'NaN' : got;
};
const numericValueProp = op.unipropcode('Numeric_Value');
const numericTypeData = unicodeData.propTrie('NumericType');
const numericTypePropId = unicodeData.propId('Numeric_Type');
function radixHelper(radix, str, zpos, flags) {
const lowercase = 'a-' + String.fromCharCode('a'.charCodeAt(0) + radix - 11);
const uppercase = 'A-' + String.fromCharCode('A'.charCodeAt(0) + radix - 11);
const uppercaseTitle = '\uFF21-' + String.fromCodePoint(0xFF21 + radix - 11);
const lowercaseTitle = '\uFF41-' + String.fromCodePoint(0xFF41 + radix - 11);
const letters = radix >= 11 ? lowercase + uppercase + uppercaseTitle + lowercaseTitle : '';
const digitClass = '[\\pN' + letters + ']';
const minus = flags & 0x02 ? '(?:-?|\\+?)' : '';
const regex = xregexp(
'^' + minus + digitClass + '(?:_' + digitClass + '|' + digitClass + ')*');
const search = str.slice(zpos).match(regex);
if (search == null) {
return null;
}
let number = search[0].replace(/_/g, '').replace(/^\+/, '');
const notSimpleDigit = new RegExp('[^0-' + Math.min(radix - 1, 9) + letters + '+-]', 'g');
let error;
number = number.replace(notSimpleDigit, function(match, offset, string) {
const code = match.codePointAt(0);
const propValueId = numericTypeData.get(code);
// TODO: avoid this lookup
const valueName = unicodeData.propValues(numericTypePropId)[propValueId-1][1];
if (valueName !== 'Decimal') error = offset;
const value = op.getuniprop_str(match.codePointAt(0), numericValueProp);
const digit = parseInt(value);
if (digit >= radix) {
if (error === undefined) error = offset;
}
return digit.toString();
});
if (radix >= 11) {
number = number.replace(new RegExp('['+uppercaseTitle+']', 'g'), function(match, offset, string) {
return String.fromCharCode('A'.charCodeAt(0) + match.codePointAt(0) - 0xFF21);
});
number = number.replace(new RegExp('['+lowercaseTitle+']', 'g'), function(match, offset, string) {
return String.fromCharCode('A'.charCodeAt(0) + match.codePointAt(0) - 0xFF41);
});
}
if (error === 0) return null;
if (error !== undefined) {
number = number.substr(0, error);
}
if (flags & 0x04) number = number.replace(/0+$/, '');
if (flags & 0x01 && number != '') number = '-' + number;
const power = number[0] == '-' ? number.length - 1 : number.length;
return {power: power, offset: zpos + (error == undefined ? search[0].length : error), number: number};
}
exports.radixHelper = radixHelper;
op.radix = function(currentHLL, radix, str, zpos, flags) {
const extracted = radixHelper(radix, str, zpos, flags);
if (extracted == null) {
return hll.slurpyArray(currentHLL, [new NQPInt(0), new NQPInt(1), new NQPInt(-1)]);
}
const pow = Math.pow(radix, extracted.power);
// TODO: use hll int type
return hll.slurpyArray(currentHLL, [new NQPInt(parseInt(extracted.number, radix)), new NQPInt(pow), new NQPInt(extracted.offset)]);
};
op.setdebugtypename = function(type, debugName) {
type.$$STable.debugName = debugName;
return type;
};
exports.hash = function() {
return new Hash();
};
const nativeArgs = require('./native-args.js');
const NativeIntArg = nativeArgs.NativeIntArg;
const NativeUIntArg = nativeArgs.NativeUIntArg;
const NativeNumArg = nativeArgs.NativeNumArg;
const NativeStrArg = nativeArgs.NativeStrArg;
const NativeNumRet = nativeArgs.NativeNumRet;
const intToObj = exports.intToObj = function(currentHLL, i) {
const type = currentHLL.get('int_box');
if (!type) {
return new NQPInt(i);
} else {
const repr = type.$$STable.REPR;
const obj = repr.allocate(type.$$STable);
obj.$$setInt(i);
return obj;
}
};
exports.int64ToObj = function(currentHLL, i) {
const type = currentHLL.get('int_box');
if (!type) {
throw new NQPException(`Can't box 64 bit integer: HLL doesn't have int_box`);
} else {
const repr = type.$$STable.REPR;
const obj = repr.allocate(type.$$STable);
obj.$$setInt64(i);
return obj;
}
};
const numToObj = exports.numToObj = function(currentHLL, n) {
const type = currentHLL.get('num_box');
if (!type) {
return new NQPNum(n);
} else {
const repr = type.$$STable.REPR;
const obj = repr.allocate(type.$$STable);
obj.$$setNum(n);
return obj;
}
};
const strToObj = exports.strToObj = function(currentHLL, s) {
const type = currentHLL.get('str_box');
if (!type) {
return new NQPStr(s);
} else {
const repr = type.$$STable.REPR;
const obj = repr.allocate(type.$$STable);
obj.$$setStr(s);
return obj;
}
};
const arg = exports.arg = function(currentHLL, arg) {
if (arg instanceof NativeIntArg) {
return intToObj(currentHLL, arg.value);
} else if (arg instanceof NativeUIntArg) { // TODO: should work only for bignums
return intToObj(currentHLL, arg.value);
} else if (arg instanceof NativeNumArg) {
return numToObj(currentHLL, arg.value);
} else if (arg instanceof NativeStrArg) {
return strToObj(currentHLL, arg.value);
} else {
return arg;
}
};
exports.slurpyPos = function(currentHLL, args, from) {
const count = args.length - from;
const unpacked = new Array(count >= 0 ? count : 0);
for (let i=from; i < args.length; i++) {
unpacked[i-from] = arg(currentHLL, args[i]);
}
return hll.slurpyArray(currentHLL, unpacked);
};
exports.slurpyNamed = function(currentHLL, named, skip) {
const hash = new Hash();
for (const key in named) {
if (!skip[key]) {
hash.content.set(key, arg(currentHLL, named[key]));
}
}
return hash;
};
exports.unwrapNamed = function(named) {
if (!named instanceof Hash) console.log('expecting a hash here');
return named.$$toObject();
};
exports.named = function(parts) {
const all = {};
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
for (const key in part) {
all[key] = part[key];
}
}
return all;
};
exports.op.ishash = function(obj) {
return obj instanceof Hash || (obj.$$STable && obj.$$STable.REPR instanceof reprs.VMHash) ? 1 : 0;
};
op.create = function(obj) {
return obj.$$STable.REPR.allocate(obj.$$STable);
};
op.bootarray = function() {
return BOOT.Array;
};
op.defined = function(obj) {
// TODO - handle more things that aren't defined
if (obj === Null || obj.$$typeObject) {
return 0;
}
return 1;
};
op.setinvokespec = function(obj, classHandle, attrName, invocationHandler) {
obj.$$STable.setinvokespec(classHandle, attrName, invocationHandler);
return obj;
};
// Stub
op.setboolspec = function(obj, mode, method) {
obj.$$STable.setboolspec(mode, method);
return obj;
};
op.savecapture = function(args) {
return new Capture(args[1], Array.prototype.slice.call(args, 2));
};
op.captureposelems = function(capture) {
return capture.pos.length;
};
op.captureposarg = function(currentHLL, capture, i) {
return arg(currentHLL, capture.pos[i]);
};
op.captureposarg_i = function(capture, i) {
return op.unbox_i(capture.pos[i]);
};
op.captureposarg_s = function(capture, i) {
return op.unbox_s(capture.pos[i]);
};
op.captureposarg_n = function(capture, i) {
return op.unbox_n(capture.pos[i]);
};
op.capturehasnameds = function(capture) {
return (!capture.named || Object.keys(capture.named).length == 0) ? 0 : 1;
};
op.captureexistsnamed = function(capture, arg) {
return (capture.named && capture.named.hasOwnProperty(arg)) ? 1 : 0;
};
op.capturenamedshash = function(currentHLL, capture) {
const hash = new Hash();
for (const key in capture.named) {
hash.content.set(key, arg(currentHLL, capture.named[key]));
}
return hash;
};
op.setcodeobj = function(codeRef, codeObj) {
codeRef.codeObj = codeObj;
return codeRef;
};
op.getcodeobj = function(codeRef) {
const codeObj = codeRef.codeObj;
return (codeObj === undefined ? Null : codeObj);
};
op.settypecache = function(obj, cache) {
obj.$$STable.typeCheckCache = cache.array;
if (obj.$$STable.$$SC !== undefined) obj.$$STable.scwb();
return obj;
};
op.settypecheckmode = function(obj, mode) {
const TYPE_CHECK_CACHE_FLAG_MASK = 3;
obj.$$STable.modeFlags = mode | (obj.$$STable.modeFlags & TYPE_CHECK_CACHE_FLAG_MASK);
return obj;
};
op.setmethcache = function(obj, cache) {
if (!cache instanceof Hash) {
console.log('we expect a hash here');
}
obj.$$STable.setMethodCache(cache.content);
if (obj.$$STable.$$SC !== undefined) obj.$$STable.scwb();
return obj;
};
op.setmethcacheauth = function(obj, isAuth) {
if (isAuth) {
obj.$$STable.modeFlags |= constants.METHOD_CACHE_AUTHORITATIVE;
} else {
obj.$$STable.modeFlags &= ~constants.METHOD_CACHE_AUTHORITATIVE;
}
if (obj.$$STable.$$SC !== undefined) obj.$$STable.scwb();
return obj;
};
op.reprname = function(obj) {
if (obj.$$STable) {
return obj.$$STable.REPR.name;
} else if (obj instanceof Capture) {
return 'MVMCallCapture';
} else if (obj instanceof NQPInt) {
return 'P6int';
} else if (obj instanceof NQPStr) {
return 'P6str';
} else if (obj instanceof NQPNum) {
return 'P6num';
} else {
console.log(obj);
throw new Error('unsupported thing passed to reprname');
}
};
op.newtype = op.newmixintype = function(how, repr) {
if (!reprs[repr]) {
throw 'Unknown REPR: ' + repr;
}
const REPR = new reprs[repr]();
REPR.name = repr;
return REPR.typeObjectFor(how);
};
op.findmethod = /*async*/ function(ctx, obj, name) {
const method = /*await*/ sixmodel.findMethod(ctx, obj, name);
if (method === Null) {
throw new NQPException(`Cannot find method '${name}' on object of type '${obj.$$STable.debugName}'`);
}
return method;
};
op.tryfindmethod = function(ctx, obj, name) {
return sixmodel.findMethod(ctx, obj, name);
};
op.getcodename = function(code) {
return code.name;
};
op.setcodename = function(code, name) {
code.name = name;
return code;
};
op.rebless = function(obj, newType) {
obj.$$STable.REPR.changeType(obj, newType);
if (obj.$$SC !== undefined) obj.$$scwb();
return obj;
};
op.composetype = function(obj, reprinfo) {
obj.$$STable.REPR.compose(obj.$$STable, reprinfo);
};
let whereCounter = 0;
op.where = function(obj) {
if (obj.$$STable || obj instanceof CodeRef || obj === Null || obj instanceof NQPInt) { // HACK
if (!obj._WHERE) {
obj._WHERE = ++whereCounter;
}
return obj._WHERE;
} else {
throw 'WHERE/objectid on this type of thing unimplemented';
}
};
op.objectid = op.where;
/* HACK - take the current HLL settings into regard */
const sha1 = require('sha1');
op.sha1 = function(text) {
return sha1(text).toUpperCase();
};
op.curlexpad = function(get, set) {
return new CurLexpad(get, set);
};
op.setcontspec = function(type, specType, conf) {
if (containerSpecs[specType]) {
type.$$STable.containerSpec = new containerSpecs[specType](type.$$STable);
type.$$STable.containerSpec.configure(conf);
} else {
throw 'NYI cont spec: ' + specType;
}
};
op.iscont = function(cont) {
return cont.$$iscont ? cont.$$iscont() : 0;
};
op.iscont_i = function(cont) {
if (cont.$$typeObject) return 0;
if (cont.$$iscont_i) return cont.$$iscont_i();
return 0;
};
op.iscont_n = function(cont) {
if (cont.$$typeObject) return 0;
if (cont.$$iscont_n) return cont.$$iscont_n();
return 0;
};
op.iscont_s = function(cont) {
if (cont.$$typeObject) return 0;
if (cont.$$iscont_s) {
return cont.$$iscont_s();
}
return 0;
};
op.isrwcont = function(cont) {
return cont.$$isrwcont ? cont.$$isrwcont() : 0;
};
op.box_n = function(n, type) {
const repr = type.$$STable.REPR;
const obj = repr.allocate(type.$$STable);
obj.$$setNum(n);
return obj;
};
op.unbox_n = function(obj) {
return obj.$$getNum();
};
op.box_s = function(value, type) {
const repr = type.$$STable.REPR;
const obj = repr.allocate(type.$$STable);
obj.$$setStr(value);
return obj;
};
op.unbox_s = function(obj) {
return obj.$$getStr();
};
op.box_i = function(i, type) {
const repr = type.$$STable.REPR;
const obj = repr.allocate(type.$$STable);
obj.$$setInt(i);
return obj;
};
op.unbox_i = function(obj) {
return obj.$$getInt();
};
op.setelems = function(obj, elems) {
obj.$$setelems(elems);
return obj;
};
op.markcodestatic = function(code) {
code.isStatic = true;
return code;
};
op.markcodestub = function(code) {
code.isCompilerStub = true;
return code;
};
op.freshcoderef = function(code) {
const fresh = code.$$clone();
fresh.staticCode = fresh;
return fresh;
};
op.pushcompsc = function(sc) {
globalContext.context.compilingSCs.push(sc);
return sc;
};
op.popcompsc = function(sc) {
return globalContext.context.compilingSCs.pop();
};
op.scwbenable = function() {
return --globalContext.context.scwbDisableDepth;
};
op.scwbdisable = function() {
return ++globalContext.context.scwbDisableDepth;
};
globalContext.initialize(context => context.compilerRegistry = new Map());
op.bindcomp = function(language, compiler) {
globalContext.context.compilerRegistry.set(language, compiler);
return compiler;
};
class WrappedFunction extends NQPObject {
constructor(func) {
super();
this.func = func;
}
/*async*/ $$apply(args) {
const converted = [];
for (let i = 2; i < args.length; i++) {
converted.push(/*await*/ argToJSWithCtx(args[0], args[i]));
}
return fromJSToReturnValue(args[0], this.func.apply(null, converted));
}
$$call(args) {
return this.$$apply(arguments);
}
};
function fromJSToReturnValue(ctx, obj) {
return fromJS(ctx.$$getHLL(), obj, true, false);
}
exports.fromJSToReturnValue = fromJSToReturnValue;
function fromJSToArgument(obj) {
return fromJS(hll.getHLL('perl6'), obj, false, true);
}
function fromJSToObject(ctx, obj) {
return fromJS(hll.getHLL('perl6'), obj, false, false);
}
function fromJS(HLL, obj, isReturnValue, isArgument) {
if (typeof obj === 'function') {
return new WrappedFunction(obj);
} else if (obj === undefined || obj === null) {
return HLL.get('null_value');
} else if (obj === true) {
return HLL.get('true_value');
} else if (obj === false) {
return HLL.get('false_value');
} else if (typeof obj === 'number') {
if (isReturnValue) {
return new NativeNumRet(obj);
} else if (isArgument) {
return new NativeNumArg(obj);
} else {
const type = HLL.get('int_box');
const boxed = type.$$STable.REPR.allocate(type.$$STable);
boxed.$$setInt(obj);
return boxed;
}
} else if (typeof obj === 'string') {
if (isReturnValue) {
return obj;
} else if (isArgument) {
return new NativeStrArg(obj);
} else {
const type = HLL.get('str_box');
const boxed = type.$$STable.REPR.allocate(type.$$STable);
boxed.$$setStr(obj);
return boxed;
}
} else if (obj.$$decont) {
return obj;
} else if (obj instanceof EvalResult) {
return obj;
} else {
const type = HLL.get('js_box');
const wrapped = type.$$STable.REPR.allocate(type.$$STable);
wrapped.$$jsObject = obj;
return wrapped;
}
}
function argToJSWithCtx(ctx, obj) {
if (obj instanceof NativeIntArg || obj instanceof NativeUIntArg) {
return obj.value;
} else if (obj instanceof NativeNumArg) {
return obj.value;
} else if (obj instanceof NativeStrArg) {
return obj.value;
} else {
return toJSWithCtx(ctx, obj);
}
}
function returnValueToJSWithCtx(ctx, obj) {
if (obj instanceof NativeNumRet) {
return obj.value;
} else if (obj instanceof NativeNumArg) {
return obj.value;
} else if (typeof obj === 'string') {
return obj;
} else {
return toJSWithCtx(ctx, obj);
}
}
function toJSWithCtx(ctx, obj) {
const HLL = ctx.$$getHLL();
if (HLL.get('str_box') && obj.$$istype(ctx, HLL.get('str_box'))) {
return obj.$$getStr();
} else if (HLL.get('num_box') && obj.$$istype(ctx, HLL.get('num_box'))) {
return obj.$$getNum();
} else if (HLL.get('js_box') && obj.$$istype(ctx, HLL.get('js_box'))) {
return obj.$$jsObject;
} else if (op.isinvokable(obj)) {
return function() {
const converted = [null, {}];
for (let i = 0; i < arguments.length; i++) {
converted.push(fromJSToArgument(arguments[i]));
}
return returnValueToJSWithCtx(ctx, obj.$$apply(converted));
};
} else if (obj.$$STable === BOOT.StrArray.$$STable) {
return obj.array;
} else {
throw new NQPException(`Can't pass object to js`);
}
}
exports.toJSWithCtx = toJSWithCtx;
const nqp = require('./runtime.js');
const vm = process.browser ? null : require('vm');
const sourceMaps = {};
const evaledP6Sources = {};
const evaledP6Filenames = {};
const SourceMapGenerator = require('source-map').SourceMapGenerator;
const SourceMapConsumer = require('source-map').SourceMapConsumer;
const SourceNode = require('source-map').SourceNode;
const charProps = require('char-props');
function applyLineDirectives(file, line, directives) {
if (directives) {
for (let i = directives.length - 1; i >= 0; i--) {
if (line > directives[i].originalLine) {
return {
line: line - directives[i].originalLine + directives[i].line - 1,
file: directives[i].file,
};
}
}
}
return {file: file, line: line};
}
function processCompLineDirectives(ctx, compLineDirectives) {
if (compLineDirectives === undefined) return undefined;
return compLineDirectives.array.map(directive => ({
originalLine: nqp.toInt(directive.array[0], ctx),
file: nqp.toStr(directive.array[2], ctx),
line: nqp.toInt(directive.array[1], ctx),
}));
}
function createSourceMap(js, p6, mapping, jsFile, p6File, lineDirectives) {
const generator = new SourceMapGenerator({file: jsFile});
const jsProps = charProps(js);
const p6Props = charProps(p6);
const stack = [];
let lastGenerated = -1;
for (let i = 0; i < mapping.length; i += 2) {
const originalOffset = mapping[i];
const generatedOffset = mapping[i+1];
function addRange() {
const {file: originalFile, line: originalLine} = applyLineDirectives(p6File, p6Props.lineAt(stack[stack.length - 1])+1, lineDirectives);
const originalColumn = p6Props.columnAt(stack[stack.length - 1]);
const lineFrom = jsProps.lineAt(lastGenerated)+1;
const columnFrom = jsProps.columnAt(lastGenerated);
const lineTo = jsProps.lineAt(generatedOffset)+1;
generator.addMapping({
generated: {
line: lineFrom,
column: columnFrom,
},
original: {
line: originalLine,
column: originalColumn,
},
source: originalFile,
});
for (let between = lineFrom + 1; between <= lineTo; between++) {
generator.addMapping({
generated: {
line: between,
column: 0,
},
original: {
line: originalLine,
column: originalColumn,
},
source: originalFile,
});
}
}
if (originalOffset === -1) {
if (lastGenerated !== generatedOffset) {
addRange();
}
stack.pop();
} else {
if (lastGenerated !== generatedOffset) {
if (stack.length) {
addRange();
}
}
stack.push(originalOffset);
}
lastGenerated = generatedOffset;
}
return generator.toString();
}
class BuildSourceMap extends NQPObject {
/*async*/ $$call(ctx, NAMED, js, p6, mapping, jsFile, p6File, compLineDirectives, sourcemapFile) {
js = /*await*/ nqp.arg_s(ctx, js);
p6 = /*await*/ nqp.arg_s(ctx, p6);
jsFile = /*await*/ nqp.arg_s(ctx, jsFile);
mapping = mapping.array;
p6File = /*await*/ nqp.arg_s(ctx, p6File);
compLineDirectives = processCompLineDirectives(ctx, compLineDirectives);
sourcemapFile = /*await*/ nqp.arg_s(ctx, sourcemapFile);
const ret = new Hash();
ret.content.set('content', new NQPStr(createSourceMap(js, p6, mapping, path.relative(path.dirname(sourcemapFile), jsFile), p6File, compLineDirectives)));
ret.content.set('url', new NQPStr(path.relative(path.dirname(jsFile), sourcemapFile)));
return ret;
}
}
exports.createSourceMap = createSourceMap;
exports.buildSourceMap = new BuildSourceMap();
class JavaScriptCompiler extends NQPObject {
$$mangleCode(code) {
if ('/*async*/' !== '/*asy' + 'nc*/') {
return code.replace(/\/\*async\*\//g, '/*async*/').replace(/\/\*await\*\//g, '/*await*/');
} else {
return code;
}
}
/*async*/ p6$eval(ctx, _NAMED, self, code) {
if (!(_NAMED !== null && _NAMED.hasOwnProperty('mapping'))) {
const codeStr = this.$$mangleCode(/*await*/ nqp.arg_s(ctx, code));
return fromJSToReturnValue(ctx, /*await*/ eval('(function() {' + codeStr + '})()'));
}
const fakeFilename = 'nqpEval' + shortid.generate();
const codeStr = this.$$mangleCode(/*await*/ nqp.toStr(code, ctx));
// TODO - get rid of the node.js specific way
// TODO - think about the LOAD_BYTECODE_FROM_MODULE HACK
const preamble = 'var nqp = global.nqp; var module = global.nqpModule;var require = global.nqpRequire;';
if (!process.browser) {
global.nqp = nqp;
}
if (_NAMED !== null && _NAMED.hasOwnProperty('mapping')) {
sourceMaps[fakeFilename] = /*await*/ new SourceMapConsumer(
createSourceMap(
codeStr,
/*await*/ nqp.toStr(_NAMED['p6-source'], ctx),
_NAMED.mapping.array,
fakeFilename,
/*await*/ nqp.toStr(_NAMED.file, ctx),
processCompLineDirectives(ctx, _NAMED.comp_line_directives)));
const node = SourceNode.fromStringWithSourceMap(codeStr, sourceMaps[fakeFilename]);
// HACK
sourceMaps[fakeFilename] = /*await*/ new SourceMapConsumer(node.toStringWithSourceMap({file: fakeFilename}).map.toString());
}
if ('p6-source' in _NAMED) {
evaledP6Sources[fakeFilename] = nqp.toStr(_NAMED['p6-source'], ctx);
evaledP6Filenames[fakeFilename] = nqp.toStr(_NAMED.file, ctx);
}
if (process.browser) {
const sourceURL = '\n//@ sourceURL=' + fakeFilename;
return fromJSToReturnValue(ctx, /*await*/ eval('(function() {' + codeStr + '})()' + sourceURL));
}
const compiled = vm.compileFunction(preamble + codeStr, [], {filename: fakeFilename});
global.nqpModule = module;
global.__filename = fakeFilename;
const oldNqpRequire = global.nqpRequire;
global.nqpRequire = function(path) {
return require(path);
};
const ret = fromJSToReturnValue(ctx, compiled());
global.nqpRequire = oldNqpRequire;
return ret;
}
p6$compile(ctx, _NAMED, self, code) {
const codeStr = nqp.arg_s(ctx, code);
const compiled = process.browser
? eval('(function() {' + codeStr + '})')
: vm.compileFunction(codeStr);
const codeRef = new CodeRef();
codeRef.$$call = function(ctx, _NAMED) {
return fromJSToReturnValue(ctx, compiled());
};
return codeRef;
}
};
globalContext.initialize(context => context.compilerRegistry.set('JavaScript', new JavaScriptCompiler()));
class JSBackendStub extends NQPObject {
p6$name(ctx, named) {
return new NQPStr('js');
}
};
class NQPStub extends NQPObject {
constructor() {
super();
this.$$backend = new JSBackendStub();
}
p6$backend(ctx, named) {
return this.$$backend;
}
};
globalContext.initialize(context => context.compilerRegistry.set('nqp', new NQPStub()));
// Needed for standalone compiled Perl 6 script to work
class FakePerl6 extends NQPObject {
config() {
return new Hash();
}
language_version() {
return 'v6.d';
}
}
FakePerl6.prototype['p6$cli-options'] = function() {
return new Hash();
};
class FakePerl6HOW extends NQPObject {
add_method() {
return Null;
}
}
FakePerl6.prototype.$$STable = {};
FakePerl6.prototype.$$STable.HOW = new FakePerl6HOW;
const fakePerl6 = new FakePerl6();
op.getcomp = function(language) {
const compilerRegistry = globalContext.context.compilerRegistry;
if (language === 'perl6' && !compilerRegistry.has(language)) {
return fakePerl6;
}