-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrepl.js
More file actions
1957 lines (1639 loc) · 64.1 KB
/
repl.js
File metadata and controls
1957 lines (1639 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This is the generic REPL. It provides functionality common to all of
// Replete's REPLs, which have a common interface. This is the general shape
// of a REPL:
// +----------------+
// | |
// | You |
// | |
// +--+-------------+
// | ^
// | |
// message evaluation
// | |
// v |
// +--------------------------------+------------------+ +----------------+
// | | | |
// | REPL |<-->| Capabilities |
// | | | |
// +--------+-----------------------------------+------+ +----------------+
// | ^ ^ ^ |
// | | | | |
// | | | | |
// eval report out err imports
// | | | | (via HTTP)
// | | | | |
// | | | | |
// v | | | v
// +-----------------+--------+--------+-----------------+
// | |
// | Padawan |
// | |
// +-----------------------------------------------------+
// A REPL instance is an object with the following methods:
// start()
// Starts the REPL, returning a Promise that resolves once it is safe
// to call 'send'.
// send(message, on_result)
// Evaluates the source code of the 'message' in every connected
// padawan. A Promise is returned, which rejects if there was a problem
// communicating with any of the padawans.
// The 'on_result' function is called with each padawan's result. If
// evaluation succeeded, the first parameter is a string representation
// of the evaluated value. Otherwise the first parameter is undefined
// and the second parameter is a string representation of the
// exception.
// Usually a REPL has exactly one padawan, but this interface permits a
// REPL to evaluate source in multiple padawans concurrently.
// stop()
// Stops the REPL. It returns a Promise that resolves once the system
// resources in use by the REPL have been released.
// Discussed below are several expectations that a programmer might reasonably
// have of a JavaScript REPL.
// +--------------+
// | Redefinition |
// +--------------+
// In a REPL, source code is evaluated over and over again in the same scope.
// The first time
// let greeting = "Hello";
// is evaluated there is no problem. However, subsequent evaluations will throw
// an exception because the 'greeting' identifier is already declared, and an
// identifier may not be declared twice.
// To avoid such exceptions, Replete transforms declarations into assignments
// prior to evaluation:
// greeting = "Hello";
// +------------+
// | Continuity |
// +------------+
// Another expectation we have of the REPL is that the value of each variable is
// preserved for future evaluations. If we now evaluated
// greeting + ", World!";
// we would expect "Hello, World!", not "undefined, World!" or an exception. We
// should be able to modify the 'greeting' variable like
// greeting = "Goodbye";
// and overwrite the old value. It should be possible to update a variable in a
// future turn, like
// setTimeout(function () {
// greeting = "Goodbye";
// });
// Likewise, we should be able to redeclare top-level functions.
// The naive approach is to write to a global variable of the same name, but
// doing so can overwrite actual global variables, making them permanently
// unavailable to future evaluations. For example, a script declaring the
// variable
// const console = 1;
// would overwrite the global 'console' variable, preventing any future calls
// to 'globalThis.console.log'.
// Replete takes a more sophisticated approach. A variable named '$scope' is
// defined, which is an object holding the value of every declared identifier.
// Declarations are replaced with assignments, and the whole script is
// evaluated in this artificial scope.
// $scope.greeting; // "Hello"
// with ($scope) {
// greeting = "Goodbye";
// }
// $scope.greeting; // "Goodbye"
// Additionally, it should be possible to reference the values from previous
// evaluations, for example to drill down into a deeply nested value. Replete
// makes this possible by storing the result of the previous evaluation in a
// variable named '$value'.
// +------------+
// | Separation |
// +------------+
// It is usually desirable to maintain a separate scope per file. This means
// that identifiers declared in one module can not interfere with the
// evaluation of another:
// module_a.js:
// const console = false;
// module_b.js:
// console.log("Hello, World!");
// In Replete, many $scope objects can coexist within the one padawan. For each
// evaluation, a scope is chosen by name.
// Whilst declarations are kept separate, it should be noted that each scope
// shares the same global object. If total isolation is desired, multiple
// REPLs (each with a single scope) can be used instead.
// +---------+
// | Modules |
// +---------+
// Usually, an application is made up of modules. And usually, a module is
// composed of other modules. JavaScript has an 'import' statement, used to
// acquire the interface of another module. Replete supports the evaluation
// of 'import' statements, making it possible to evaluate modules (and even
// whole applications) in the REPL.
// At the heart of each padawan is the global 'eval' function. eval, being
// immediate in nature, does not support the import statement.
// SyntaxError: Cannot use import statement outside a module
// When evaluating a fragment of source code, Replete removes from it any import
// or export statements, leaving a bare script that can be passed to eval. The
// requisite modules are instead imported via the import() function, and the
// importations placed within the scope of the script as it is eval'd.
// The source code of each imported module is provided to the padawan via HTTP.
// A URL is passed to the import() function, generating a request to an HTTP
// server controlled by Replete. This means Replete can modify the source code
// of modules as required.
// +-----------+
// | Freshness |
// +-----------+
// When an 'import' statement is evaluated, it is reasonable to expect that the
// freshest version of the module be used, rather than a stale version from the
// cache. Frustratingly, JavaScript runtimes cache each module for the lifetime
// of the application. If modules were always immutable and pure, such a
// draconian measure would not have been necessary. Alas, modules are permitted
// to hold state. Such modules are little better than mutable global
// variables.
// The only way to defeat the module cache is to vary the specifier passed to
// import(). But this means that a module's specifier must vary not only when
// its own source changes, but when the source of any of its descendants
// change! This is illustrated in the following scenario.
// source -> a.js -> b.js // source imports a.js, which imports b.js
// After evaluating the source, a.js and b.js are cached. Changes to these files
// are not reflected in future evaluations.
// Replete's solution is to include a version in the specifier, varying the
// version whenever the module or its descendants are modified. In this way,
// the module cache is used to obtain a performance benefit without the
// staleness.
// +-------+
// | Speed |
// +-------+
// Evaluation should be instantaneous, or close to it. That is the best possible
// feedback loop, greatly improving the programmer's productivity and sense of
// wellbeing. Replete tries to satisfy the expectations of both speed and
// freshness, but it is not pretty because they conflict.
// Usually, the vast majority of evaluation time is spent importing modules.
// Consider the following module tree:
// source -> a.js -> b.js -> c.js
// The padawan will perform between zero and three network roundtrips whilst
// evaluating the source, depending on the state of the module cache. The
// module tree is traversed from top to bottom.
// Within the Replete process, however, the module tree is traversed from bottom
// to top. This is because a module's specifier depends on its descendants, as
// explained in the Freshness section above. Worse, whole subtrees are
// traversed for each module requested. The amount of duplicated work grows
// exponentially as the module tree deepens.
// a
// / \ If it took Replete 1 unit of work to read, parse and transform
// b1 b2 a single module, then importing module 'a' would cost a
// / \ / \ whopping 17 units of work, rather than the expected 7.
// c1 c2 c3 c4
// Replete mitigates this explosion by caching its most expensive operations. I
// am on the lookout for a better solution.
// +------------+
// | Strictness |
// +------------+
// ES5 introduced "strict mode", an opt-in feature that repaired some of
// JavaScript's flaws. Within an ES6 module, strict mode is no longer opt-in.
// It is the default mode of execution. Because Replete is an evaluator for
// modules, it evaluates all JavaScript in strict mode.
// +--------------+
// | Traceability |
// +--------------+
// When evaluation fails due to an exception, its stack trace may contain useful
// debugging information, such as line numbers and function names. Replete
// attempts to preserve the integrity of both of these.
// +-------------+
// | Eventuality |
// +-------------+
// JavaScript's 'await' keyword magically suspends execution whilst a Promise is
// fulfilled. REPL support for 'await' at the top level makes ad hoc scripting
// a bit more convenient, but is tricky to implement because 'eval' throws when
// it encounters a top-level 'await'.
// The only way to evaluate source containing 'await' is to wrap the source in
// an async function and call it, then wait for the returned Promise to
// resolve. The difficulty here is that we lose eval's intrinsic ability to
// return its trailing value. We emulate this behavior by assigning every
// value-producing statement to an '$await' variable and returning it.
// Thus, source like
// let response;
// if (do_fetch) {
// response = await fetch("https://site.com");
// await response.json();
// } else {
// console.log("Skipping.");
// }
// becomes
// (async function () {
// let $await;
// let response;
// if (do_fetch) {
// $await = response = await fetch("https://site.com");
// $await = await response.json();
// } else {
// $await = console.log("Skipping.");
// }
// return $await;
// }());
// +-----------+
// | Wholeness |
// +-----------+
// A module should be able to demonstrate its own correctness. To do so, parts
// of it can be written as an executable program. It is poor form, however,
// for module to exhibit side effects when imported by another module and so
// some mechanism must be used to conditionally enable some of the module's
// functionality.
// To this end, Replete replaces each occurrence of 'import.meta.main' with
// 'true' prior to evaluation.
// Thus
// if (import.meta.main) {
// console.log(check_thing());
// }
// becomes
// if (true) {
// console.log(check_thing());
// }
// The 'import.meta.main' property is informally standardized as part of
// WinterCG, and is supported by at least two runtimes.
/*jslint web, global */
import {parse} from "acorn";
import {simple, recursive} from "acorn-walk";
const rx_relative_path = /^\.\.?\//;
function fill(template, substitutions) {
// The 'fill' function prepares a script template for execution. As an example,
// all instances of <the_force> found in the 'template' will be replaced with
// 'substitutions.the_force'.
return template.replace(/<([^<>]*)>/g, function (original, filling) {
return substitutions[filling] ?? original;
});
}
function alter_string(string, alterations) {
// The 'alter_string' function applies an array of substitutions to a string.
// The ranges of the alterations must be disjoint. The 'alterations' parameter
// is an array of arrays like [range, replacement] where the range is an object
// like {start, end}.
alterations = alterations.slice().sort(
function compare(a, b) {
return a[0].start - b[0].start || a[0].end - b[0].end;
}
);
let end = 0;
return alterations.map(
function ([range, replacement]) {
const chunk = string.slice(end, range.start) + replacement;
end = range.end;
return chunk;
}
).concat(
string.slice(end)
).join(
""
);
}
function test_alter_string() {
const altered = alter_string("..234.6.8.", [
[{start: 6, end: 7}, ""],
[{start: 6, end: 6}, "six"],
[{start: 8, end: 9}, "eight"],
[{start: 2, end: 5}, "twothreefour"]
]);
if (altered !== "..twothreefour.six.eight.") {
throw new Error("FAIL");
}
}
function parse_module(source) {
return parse(source, {ecmaVersion: "latest", sourceType: "module"});
}
function analyze_module(tree) {
// The 'analyze_module' function statically analyzes a module to find any
// imports, exports, and dynamic specifiers. The 'tree' parameter is the
// module's parsed source code.
// An analysis object is returned, containing the following properties:
// imports
// An array of objects representing the parsed import statements. Each
// object contains the following properties:
// node
// The import statement node.
// import "./fridge.js";
// -> {
// node: {
// start: 0,
// end: 21,
// source: {
// start: 7,
// end: 20,
// value: "./fridge.js",
// }
// },
// ...
// }
// default
// The name of the default import, if any.
// import fruit from "./apple.js";
// -> {default: "fruit", ...}
// names
// If the statement imports named members, this is an object
// containing a property for each member. The key is the name
// of the member, and the value is the alias.
// import {
// red,
// green as blue
// } from "./pink.js";
// -> {
// names: {
// red: "red",
// green: "blue"
// },
// ...
// }
// If the statement imports every member as a single
// identifier, this property is instead a string.
// import * as creatures from "./animals.js";
// -> {names: "creatures", ...}
// If the statement does not import any named members, this
// property is omitted.
// exports
// An array of export statement nodes.
// export default 1 + 2;
// export {rake};
// export * from "./dig.js";
// -> [
// {
// type: "ExportDefaultDeclaration",
// start: 0,
// end: 21,
// declaration: {start: 15, end: 20}
// },
// {
// type: "ExportNamedDeclaration",
// start: 22,
// end: 36
// },
// {
// type: "ExportAllDeclaration,
// start: 37,
// end: 62
// }
// ]
// dynamics
// An array whose elements represent occurrences of the following
// forms:
// import("<specifier>")
// import.meta.resolve("<specifier>")
// new URL("<specifier>", import.meta.url)
// Each element is an object with a "value" property, containing the
// <specifier>, and "module" and "script" properties, both of which
// are ranges indicating an area of the source to be replaced by a
// string literal containing the resolved specifier.
// If the source is to be imported as a module, use the "module" range.
// If the source is to be evaluated as a script, replace the "script"
// property.
// The caller can use this information to rewrite the above forms
// into
// import("/path/to/my_module.js")
// "/path/to/my_module.js"
// new URL("/path/to/my_module.js", import.meta.url)
// once the specifiers have been resolved.
// mains
// An array of 'import.meta.main' nodes.
let imports = [];
let exports = [];
let dynamics = [];
let mains = [];
// Walk the whole tree, examining every statement and expression. This is
// necessary because 'import.meta' can appear basically anywhere.
simple(tree, {
ImportDeclaration(node) {
let the_import = {node};
node.specifiers.forEach(function (specifier_node) {
const {type, local, imported} = specifier_node;
if (type === "ImportDefaultSpecifier") {
the_import.default = local.name;
}
if (type === "ImportSpecifier") {
if (the_import.names === undefined) {
the_import.names = {};
}
the_import.names[imported.name] = local.name;
}
if (type === "ImportNamespaceSpecifier") {
the_import.names = local.name;
}
});
imports.push(the_import);
},
ExportDefaultDeclaration(node) {
exports.push(node);
},
ExportNamedDeclaration(node) {
exports.push(node);
},
ExportAllDeclaration(node) {
exports.push(node);
},
ImportExpression(node) {
if (typeof node.source.value === "string") {
// Found import("<specifier>").
dynamics.push({
value: node.source.value,
module: node.source,
script: node.source
});
}
},
CallExpression(node) {
if (
node.callee.type === "MemberExpression"
&& node.callee.object.type === "MetaProperty"
&& node.callee.property.name === "resolve"
&& node.arguments.length === 1
&& typeof node.arguments[0].value === "string"
) {
// Found import.meta.resolve("<specifier>").
dynamics.push({
value: node.arguments[0].value,
module: node,
script: node
});
}
},
MemberExpression(node) {
if (
node.object.type === "MetaProperty"
&& node.object.meta.name === "import"
&& node.object.property.name === "meta"
&& node.property.name === "main"
) {
// Found import.meta.main.
mains.push(node);
}
},
NewExpression(node) {
if (
node.callee.name === "URL"
&& node.arguments.length === 2
&& node.arguments[0].type === "Literal"
&& typeof node.arguments[0].value === "string"
&& rx_relative_path.test(node.arguments[0].value)
&& node.arguments[1].type === "MemberExpression"
&& node.arguments[1].object.type === "MetaProperty"
&& node.arguments[1].property.name === "url"
) {
// Found new URL("<specifier>", import.meta.url).
// This form should be removed once the import.meta.resolve form is widely
// supported, then we can dispense with the "module" and "script" properties
// below.
dynamics.push({
value: node.arguments[0].value,
// The import.meta.url is permitted in a module, but not in a script. It is
// required as a second parameter to URL when the specifier resolves to an
// absolute path, rather than a fully qualified URL.
module: node.arguments[0],
script: {
start: node.arguments[0].start,
end: node.arguments[1].end
}
});
}
}
});
return {imports, exports, dynamics, mains};
}
function run_analyzer(analyzer, source) {
return [
analyzer(parse_module(source)),
function range({start, end}) {
return source.slice(start, end);
}
];
}
function test_analyze_module() {
const [analysis, range] = run_analyzer(analyze_module, `
import a, {b as B} from "./a.js";
import c, * as d from "./d.js";
const h = import("./h.js");
const i = import.meta.resolve("./i.js");
const j = new URL("./j.js", import.meta.url);
const k = import.meta.main;
export {h as H};
export default i;
export * from "./k.js";
export {m} from "./m.js";
`);
const [import_a, import_c] = analysis.imports;
const [dynamic_h, dynamic_i, dynamic_j] = analysis.dynamics;
const [export_h, export_i] = analysis.exports;
const [main_k] = analysis.mains;
if (
analysis.imports.length !== 2
|| import_a.default !== "a"
|| import_a.names.b !== "B"
|| !range(import_a.node).startsWith("import")
|| !range(import_a.node).endsWith(";")
|| import_c.default !== "c"
|| import_c.names !== "d"
|| analysis.dynamics.length !== 3
|| dynamic_h.value !== "./h.js"
|| range(dynamic_h.module) !== "\"./h.js\""
|| range(dynamic_h.script) !== "\"./h.js\""
|| analysis.mains.length !== 1
|| range(main_k) !== "import.meta.main"
|| dynamic_i.value !== "./i.js"
|| range(dynamic_i.module) !== "import.meta.resolve(\"./i.js\")"
|| range(dynamic_i.script) !== "import.meta.resolve(\"./i.js\")"
|| dynamic_j.value !== "./j.js"
|| range(dynamic_j.module) !== "\"./j.js\""
|| range(dynamic_j.script) !== "\"./j.js\", import.meta.url"
|| analysis.exports.length !== 4
|| !range(export_h).startsWith("export")
|| !range(export_h).endsWith(";")
|| range(export_i.declaration) !== "i"
) {
throw new Error("FAIL");
}
}
function analyze_top(tree) {
// The 'analyze_top' function statically analyzes the top-level scope of a
// module to find any await expressions or expression statements.
// An analysis object is returned, containing the following properties:
// values
// An array of top-level value-producing statement nodes. The evaluated
// value is always the last of these to be executed.
// wait
// Whether the module contains any top-level await expressions. Just
// one of these is sufficient to prevent immediate evaluation.
let values = [];
let wait = false;
// Walk the top level only, skipping the contents of function bodies.
recursive(tree, undefined, {
Function() {
return;
},
ExpressionStatement(node, _, c) {
values.push(node);
c(node.expression);
},
VariableDeclaration(variable_node, _, c) {
// Variable declarations become expression statements once transformed into
// assignments.
variable_node.declarations.forEach(function (declarator_node) {
if (declarator_node.init) {
values.push(declarator_node.init);
}
c(declarator_node);
});
},
AwaitExpression() {
wait = true;
},
ForOfStatement(node, _, c) {
if (node.await === true) {
wait = true;
}
c(node.body);
}
});
return {values, wait};
}
function test_analyze_top_immediate() {
const [analysis, range] = run_analyzer(analyze_top, `
if (a) {
b(async c => await d);
} else {
e;
}
f;
const [g] = [h];
`);
if (
analysis.wait !== false
|| analysis.values.length !== 4
|| range(analysis.values[0]) !== "b(async c => await d);"
|| range(analysis.values[1]) !== "e;"
|| range(analysis.values[2]) !== "f;"
|| range(analysis.values[3]) !== "[h]"
) {
throw new Error("FAIL");
}
}
function test_analyze_top_eventual() {
const [analysis, range] = run_analyzer(analyze_top, `
if (a) {
b(await c);
} else {
d;
}
function e() {
f();
}
g;
let h = i;
let j = await k;
`);
if (
analysis.wait !== true
|| analysis.values.length !== 5
|| range(analysis.values[0]) !== "b(await c);"
|| range(analysis.values[1]) !== "d;"
|| range(analysis.values[2]) !== "g;"
|| range(analysis.values[3]) !== "i"
|| range(analysis.values[4]) !== "await k"
) {
throw new Error("FAIL");
}
}
function test_analyze_top_eventual_default() {
const [analysis, range] = run_analyzer(analyze_top, `
let [a = await b] = c;
`);
if (
analysis.wait !== true
|| analysis.values.length !== 1
|| range(analysis.values[0]) !== "c"
) {
throw new Error("FAIL");
}
}
function all_specifiers(module_analysis) {
// Return any import and dynamic specifier strings mentioned in the analysis.
return [
...module_analysis.imports.map(function (the_import) {
return the_import.node.source.value;
}),
...module_analysis.dynamics.map(function (the_dynamic) {
return the_dynamic.value;
}),
...module_analysis.exports.filter(function (the_export) {
return the_export.source;
}).map(function (the_export) {
return the_export.source.value;
})
];
}
function blanks(source, range) {
// Return some blanks lines to append to a replacement, so that it matches the
// number of lines of the original text. This is sometimes necessary to
// maintain line numbering.
return "\n".repeat(
source.slice(range.start, range.end).split("\n").length - 1
);
}
const script_template = `
// Ensure that the global $scopes variable is available. It contains scope
// objects that persist the state of identifiers across evaluations.
// The only reliable way to store values is to attach them to the global object.
// We get a reference to the global object via 'this' because it is a strategy
// that works in every runtime, so long as this script is evaluated in
// non-strict mode.
if (this.$scopes === undefined) {
this.$scopes = Object.create(null);
}
if ($scopes[<scope_name_string>] === undefined) {
$scopes[<scope_name_string>] = Object.create(null);
$scopes[<scope_name_string>].$default = undefined;
$scopes[<scope_name_string>].$value = undefined;
}
// Retrieve the named scope. We use a var because it can be redeclared without
// raising an exception, unlike a const.
var $scope = $scopes[<scope_name_string>];
// Check that the imported modules exported the requested identifiers.
<imports_array_literal>.forEach(function ([import_nr, specifier, name]) {
if (!Object.hasOwn($imports[import_nr], name)) {
throw new Error(
"Module " + specifier + " does not export '" + name + "'."
);
}
});
// Populate the scope with the script's declared identifiers. Every identifier,
// including those from previous evaluations, are simulated as local variables.
// This means that scripts are free to shadow global variables, without risk of
// interfering with the global object.
Object.assign($scope, <identifiers_object_literal>);
// The 'with' statement has a bad reputation, and is not even allowed in strict
// mode. However, I can not think of a way to avoid using it here. It allows us
// to use the scope object as an actual scope. It has the other advantage that
// variable assignments taking place in future turns correctly update the
// corresponding properties on the scope object.
// If the scope object had a prototype, properties on the prototype chain of the
// scope object (such as toString) could be dredged up and misinterpreted as
// identifiers. To avoid this hazard, the scope object was made without a
// prototype.
with ($scope) {
$value = (function () {
// Evaluate the payload script in strict mode. We enforce strict mode because
// the payload script originates from a module, and modules are always run in
// strict mode.
"use strict";
return eval(<payload_script_string>);
}());
}
`;
function make_imports_array_literal(imports) {
let elements = [];
imports.forEach(function (the_import, import_nr) {
if (the_import.default !== undefined) {
elements.push([import_nr, the_import.node.source.value, "default"]);
}
if (typeof the_import.names === "object") {
Object.keys(the_import.names).forEach(function (name) {
elements.push([
import_nr,
the_import.node.source.value,
the_import.names[name]
]);
});
}
});
return JSON.stringify(elements);
}
function make_identifiers_object_literal(variables, imports) {
const members = [];
// Variables are initialized to undefined.
variables.forEach(function (name) {
members.push(name + ": undefined");
});
// The values of the importations are extracted from the $imports array, which
// is assumed to have been declared in an outer scope.
imports.forEach(function (the_import, import_nr) {
if (the_import.default !== undefined) {
members.push(
the_import.default
+ ": $imports[" + import_nr + "].default"
);
}
if (typeof the_import.names === "string") {
members.push(the_import.names + ": $imports[" + import_nr + "]");
}
if (typeof the_import.names === "object") {
Object.keys(the_import.names).forEach(function (name) {
members.push(
the_import.names[name]
+ ": $imports[" + import_nr + "]." + name
);
});
}
});
return "{" + members.join(", ") + "}";
}
function pattern_name(node) {
return (
node.type === "AssignmentPattern"
? node.left.name // let [a = 42] = ...
: node.name // let [a] = ...
);
}
function replize(
source,
tree,
module_analysis,
top_analysis,
dynamic_specifiers,
scope = ""
) {
// The 'eval' function can not handle import or export statements. The 'replize'
// function transforms 'source' such that it is safe to eval, wrapping it in a
// harness to give it the REPL behavior described at the top of this file. It
// takes the following parameters:
// source
// A string containing the module's source code.
// tree
// The module's source as a parsed tree.
// module_analysis
// An object returned by the 'analyze_module' function.
// top_analysis
// An object returned by the 'analyze_top' function.
// dynamic_specifiers
// An array containing the dynamic specifiers to be injected.
// scope
// The name of the scope to use for evaluation. If the scope does not
// exist, it is created.
// The resulting script contains a free variable, $imports, that is expected to
// be an array containing the imported module objects.
// Another free variable, $default, is assigned the default exportation, if
// there is one.
// ORIGINAL | REWRITTEN
// |
// import frog from "./frog.js" |
// export default 1 + 1; | $default = 1 + 1;
// export {frog}; |
// export * from "./lizard.js"; |
// Notice how the import and export statements are stripped from the resulting
// script.
let alterations = [];
let variables = [];
// Transform imports:
// - Import statements are removed.
// - The argument passed to import() is replaced with a string literal.
// - Each call to import.meta.resolve is replaced with a string literal.
// - All references to import.meta.main are replaced with 'true'.
module_analysis.imports.forEach(function ({node}) {
return alterations.push([node, blanks(source, node)]);
});
module_analysis.dynamics.forEach(function (dynamic, dynamic_nr) {
return alterations.push([
dynamic.script,