-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflixw.java
More file actions
6237 lines (5902 loc) · 339 KB
/
Copy pathflixw.java
File metadata and controls
6237 lines (5902 loc) · 339 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
// flixw stage 0 -- repository-local Flix compiler bootstrap.
//
// GENERATED IN A PROJECT; DO NOT EDIT THERE. The copy under a project's .flixw/ is
// written by `flixw install` and replaced by `flixw wrapper --upgrade`, and
// `flixw validate` prints its SHA-256 so an altered one is visible against the published
// release. This file, in the flixw repository, is where it is actually written.
//
// Invoked by the ./flixw shim as: java .flixw/flixw.java <args>
// or, once self-compiled, as: java -cp <cache>/stage0/<hash> flixw <args>
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.time.Duration;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Stage 0 of the flixw bootstrap: one file, no dependencies, Java 21.
*
* <p>It owns project discovery, lock parsing, drift detection, version validation, Java
* selection, compiler acquisition, unconditional digest verification, compiler-first verb
* dispatch, the wrapper's own verbs, and the process launch. The two shims that reach it,
* {@code flixw} and {@code flixw.cmd}, own exactly one decision each -- which {@code java}
* -- plus one cache lookup, because logic in a shim has to be written twice and cannot be
* unit-tested.
*
* <p>The stock Flix compiler is never modified, patched, or linked against. It is fetched
* by URL, verified against a SHA-256 committed in {@code .flixw/lock.toml}, and executed
* as an opaque process. The digest is recomputed on every invocation: there is no install
* stamp and no flag that skips it.
*
* <p>These docs are published from the flixw repository and cover every member, private
* ones included, because the internals are what a reader has to trust before letting this
* file download and run a compiler. {@code docs/CONTRACT.md} is the description of what
* ships and what is promised; this is how it is done.
*
* @see <a href="https://wstein.github.io/flixw/">flixw documentation</a>
*/
public final class flixw {
static final String WRAPPER_VERSION = "0.31.3";
static final String WRAPPER_DIR = ".flixw";
static final int MIN_JAVA = 21;
/**
* The oldest javac that can compile this file, which is a different number from the
* floor above and answers a different question. MIN_JAVA is what the *compiler* needs;
* this is what *stage 0* needs, and between the two lies the range where flixw runs,
* says the pinned Flix will not, and can fetch a JDK that will. Below it flixw cannot
* speak at all -- which is why the no-java diagnostic does not offer to install one.
* `tests/lint.sh` compiles this file with --release SOURCE_FLOOR so the number cannot
* quietly drift when a newer language feature is used.
*/
static final int SOURCE_FLOOR = 16;
/**
* The interval flixw is tested on. Above the ceiling is a warning, not an error.
*
* The number means the suite has actually been run there, so it moves when that is
* done and not when a JDK is released: `.github/workflows/ci.yaml` runs the whole
* suite on the ceiling as well as on MIN_JAVA, which is what keeps the claim true
* rather than aspirational.
*/
static final int TESTED_CEILING = 26;
/**
* Bounds for the two child processes stage 0 runs for information rather than for
* work. Both are generous: exceeding one means the child is wedged, not slow.
*/
static final Duration PROBE_TIMEOUT = Duration.ofSeconds(20);
static final Duration HELP_TIMEOUT = Duration.ofSeconds(30);
static final int HELP_CAP = 1 << 20;
static final List<String> WRAPPER_VERBS =
List.of("pin", "info", "doctor", "validate", "help", "plugin", "task", "examples", "local");
/**
* Fallback verb set, observed in Flix 0.75.1 and 0.75.2. Used when `flix --help`
* cannot be captured or parsed. Its only job is to answer "does the pinned compiler
* already implement one of WRAPPER_VERBS" -- a question whose answer changes at most
* once a year, and never silently. Being one release stale here costs nothing;
* failing here would brick every project pinned to a compiler flixw has not seen.
*/
static final List<String> BUILTIN_VERBS = List.of(
"init", "check", "build", "build-jar", "build-fatjar", "build-pkg", "clean",
"doc", "format", "run", "test", "repl", "lsp", "lsp-vscode", "release",
"outdated", "eff-check", "eff-lock");
// ---- diagnostics -----------------------------------------------------
static final class Fail extends RuntimeException {
private static final long serialVersionUID = 1L;
final String code; final int exit;
Fail(String code, int exit, String msg) { super(msg); this.code = code; this.exit = exit; }
}
static Fail fail(String code, int exit, String msg) { return new Fail(code, exit, msg); }
static Fail w001(String m) { return fail("FLIXW001", 80, m); }
static Fail w002(String m) { return fail("FLIXW002", 81, m); }
static Fail w003(String m) { return fail("FLIXW003", 82, m); }
static Fail w004(String m) { return fail("FLIXW004", 83, m); }
static Fail w005(String m) { return fail("FLIXW005", 84, m); }
static Fail w006(String m) { return fail("FLIXW006", 85, m); }
static Fail w007(String m) { return fail("FLIXW007", 86, m); }
static Fail w008(String m) { return fail("FLIXW008", 87, m); }
static Fail w009(String m) { return fail("FLIXW009", 88, m); }
/** FLIXW010 and FLIXW011 are advisory: they are printed, they never set exit status. */
static void w010(String m) { System.err.println("FLIXW010: " + m); }
static void w011(String m) { System.err.println("FLIXW011: " + m); }
static String env(String k) {
String v = System.getenv(k);
return (v == null || v.isBlank()) ? null : v;
}
static boolean trace() { return env("FLIXW_TRACE") != null; }
static long T0 = System.nanoTime();
static void tr(String s) {
if (trace()) System.err.printf("flixw[%6.1fms] %s%n", (System.nanoTime() - T0) / 1e6, s);
}
// ---- version grammar --------------------------------------------------
static final Pattern SEMVERISH = Pattern.compile(
"[0-9]+\\.[0-9]+\\.[0-9]+(?:-[0-9A-Za-z](?:[0-9A-Za-z.-]*[0-9A-Za-z])?)?"
+ "(?:\\+[0-9A-Za-z](?:[0-9A-Za-z.-]*[0-9A-Za-z])?)?");
static String validateVersion(String v, String where) {
if (v == null) throw w002(where + ": no version");
for (char c : v.toCharArray())
if (Character.isWhitespace(c) || c == '/' || c == '\\')
throw w002(where + ": illegal character in version " + q(v));
if (v.contains("..")) throw w002(where + ": '..' in version " + q(v));
// Only when stripping the tag prefix would actually leave a version. `pin` accepts
// that form outright, so anything reaching here still spelled with a leading `v` is
// either the manifest -- Flix's field, which takes x.x.x alone -- or not a version
// at all, and telling someone to strip a `v` from `vNext` names the wrong problem.
if (v.startsWith("v") && SEMVERISH.matcher(v.substring(1)).matches())
throw w002(where + ": strip the leading 'v' from " + q(v));
if (!SEMVERISH.matcher(v).matches())
throw w002(where + ": " + q(v) + " is not an exact version"
+ "\n ranges, wildcards and empty suffixes are not accepted");
return v;
}
/**
* Accepts the release tag where a version is expected: {@code v0.75.2} means
* {@code 0.75.2}.
*
* GitHub shows the tag, not the version. The releases page, the tag list, the archive
* links and the asset URLs all read {@code v0.75.2}, so copying from where the versions
* actually are gets you the tag every time -- and flixw itself builds {@code "v" +
* version} to construct that URL, so it already holds that the two name one release.
* Refusing the form flixw prints into its own URLs made the user do a normalization the
* wrapper was doing anyway.
*
* Only ahead of a digit, so {@code vNext} is still a bad version rather than the
* version {@code Next}, and the diagnostic keeps naming the real problem.
*
* Deliberately not applied to {@code [package].flix}: that field is Flix's, and Flix
* accepts {@code x.x.x} alone. Tolerating a tag there would let flixw read a manifest
* that Flix itself rejects, which is a worse outcome than the error it replaces.
*/
static String stripTagPrefix(String v) {
return v.length() > 1 && v.charAt(0) == 'v' && Character.isDigit(v.charAt(1))
? v.substring(1) : v;
}
/**
* The single normalization used for release tags, cache coordinates, and every
* version comparison. SemVer build metadata identifies a build, not a release, so
* it is accepted in the manifest and stripped everywhere it would name an artifact.
* Defining this once is what stops `flix = "0.75.2+build.4"` from producing a drift
* error that `./flixw pin` cannot repair.
*/
static String canonical(String v) { int i = v.indexOf('+'); return i < 0 ? v : v.substring(0, i); }
/**
* The `x.x.x` that `[package].flix` is allowed to hold.
*
* That field is Flix's, not flixw's, and Flix rejects anything else outright --
* "This toml file has a Flix version number of the wrong length" for a version
* carrying build metadata. It also accepts 99.99.99 against a 0.75.2 compiler, so it
* reads as a coarse floor rather than a pin.
*
* The exact version therefore lives in the lock, which is flixw's own file and can say
* `0.75.2+fork.wstein.260807.1` without breaking anything. Drift compares the two at
* this precision, because that is all the manifest is able to express.
*/
static String triple(String v) {
Matcher m = Pattern.compile("^([0-9]+\\.[0-9]+\\.[0-9]+)").matcher(v);
return m.find() ? m.group(1) : v;
}
static String q(String s) { return "'" + s + "'"; }
/** IOException.getMessage() is often bare the path; name the failure too. */
static String why(Exception e) {
String m = e.getMessage();
return e.getClass().getSimpleName() + (m == null ? "" : ": " + m);
}
/**
* Redacts credentials from a URL-shaped value before it is printed.
*
* `doctor` output exists to be pasted into bug reports, and a proxy URL is the one
* environment value that routinely carries a password. Host and port are what a reader
* needs; user-info and query string never are. Values that are not URLs at all -- a
* NO_PROXY host list, say -- have no '@' and pass through untouched.
*/
static String redact(String v) {
String s = v.replaceAll("(?i)((?:[a-z][a-z0-9+.-]*://)?)[^/@\\s,]*@", "$1***@");
int i = s.indexOf('?');
return i < 0 ? s : s.substring(0, i) + "?***";
}
/** The same, for JVM option strings, which can carry -Dhttps.proxyPassword=secret. */
static String redactOpts(String v) {
return redact(v).replaceAll(
"(?i)(-D[^=\\s]*(?:pass|secret|token|credential)[^=\\s]*=)\\S+", "$1***");
}
// ---- the lock schema --------------------------------------------------
/**
* The lock format's major version, which is not the wrapper's. It changes only when a
* lock this stage 0 writes would stop being readable under the rules below; adding an
* optional key is not such a change, and does not move it.
*/
static final String LOCK_SCHEMA_VERSION = "v1";
/** Where the generated documentation and the JSON Schema are published. */
static final String PAGES_BASE = "https://wstein.github.io/flixw/";
/**
* The URL written into every generated lock as a `#:schema` directive, and the `$id`
* of the schema itself. Taplo and Even Better TOML read that directive, so an editor
* validates the lock with no per-project configuration.
*/
static final String LOCK_SCHEMA_URL =
PAGES_BASE + "schema/lock-" + LOCK_SCHEMA_VERSION + ".schema.json";
/** GitHub's own limits on the two path segments; a fork may live anywhere within them. */
static final String REPO_PATTERN = "[A-Za-z0-9._-]{1,64}/[A-Za-z0-9._-]{1,100}";
/** A feature release or an exact one, and nothing else -- no ranges, no vendor. */
static final String JAVA_PIN_PATTERN = "[0-9]+(\\.[0-9]+)*";
/**
* One key in lock.toml: the table it lives in, whether that table may omit it, the
* shape its value must have, and the sentence a diagnostic uses to describe it.
*
* The lock's shape was previously stated in three places -- {@link #lockText} wrote it,
* {@link #readLock} read it, and the documentation described it -- with nothing keeping
* them in step, and a published JSON Schema would have been a fourth. So it is stated
* once here, and the writer, the reader and the schema are all derived from this list.
*
* {@code pattern} is deliberately written in the intersection of Java's regex dialect
* and ECMA-262's: it is compiled by {@code String.matches} on every run, and by
* whatever JSON Schema validator reads the published file. It carries no anchors,
* because Java implies them and JSON Schema does not.
*/
record LockField(String table, String key, boolean required, String pattern, String what) {
/** How a diagnostic names this key: `[compiler] sha256`, or a bare key at the root. */
String name() { return table.isEmpty() ? key : "[" + table + "] " + key; }
}
/**
* Every key a lock may hold, in the order a generated lock writes them.
*
* {@code required} means required when the table it sits in is present, which is why
* `[java] version` is optional: a project that does not care which JDK runs the
* compiler omits the table entirely, and an empty one means the same thing.
*/
static final List<LockField> LOCK_SCHEMA = List.of(
new LockField("", "wrapperVersion", false, SEMVERISH.pattern(),
"the flixw release that last wrote this lock"),
new LockField("compiler", "repo", false, REPO_PATTERN,
"the owner/repository the compiler was fetched from"),
new LockField("compiler", "version", true, SEMVERISH.pattern(),
"the exact compiler version: x.y.z, optionally with a prerelease and build metadata"),
new LockField("compiler", "url", true, "https://[^\\s]+",
"the https URL the compiler JAR is downloaded from"),
new LockField("compiler", "sha256", true, "[0-9a-f]{64}",
"the SHA-256 of that JAR: 64 lowercase hex digits"),
new LockField("compiler", "reported_version", false, SEMVERISH.pattern(),
"the version that JAR reports of itself, captured when it was pinned"),
new LockField("java", "version", false, JAVA_PIN_PATTERN,
"the Java that runs the compiler: a feature release (21) or an exact one (21.0.12)"));
/** The tables the schema knows about, deduplicated, in lock order. The root is "". */
static List<String> lockTables() {
List<String> out = new ArrayList<>();
for (LockField f : LOCK_SCHEMA) if (!out.contains(f.table())) out.add(f.table());
return out;
}
/**
* The published JSON Schema for lock.toml, rendered from {@link #LOCK_SCHEMA}.
*
* Generated rather than hand-written for the reason the shims are compared byte for
* byte: a schema describing a lock this wrapper no longer writes is worse than no
* schema at all, because an editor presents it as authority. `tests/lint.sh` diffs
* this against the copy in `docs/schema/`, so the published file cannot drift from the
* code that writes the file it describes.
*
* Hand-rolled rather than serialised by a library, because stage 0 has no
* dependencies. The only values interpolated are ours, and {@link #jsonString} escapes
* them anyway -- the patterns are full of backslashes.
*/
static String lockSchemaJson() {
StringBuilder b = new StringBuilder();
b.append("{\n");
b.append(" \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n");
b.append(" \"$id\": ").append(jsonString(LOCK_SCHEMA_URL)).append(",\n");
b.append(" \"title\": \"flixw lock.toml\",\n");
b.append(" \"description\": ").append(jsonString(
"The pin written by `./flixw pin`: the repository, exact version, distribution"
+ " URL and SHA-256 of the Flix compiler a project runs. Generated and verified by"
+ " flixw; committed, and not edited by hand.")).append(",\n");
b.append(" \"type\": \"object\",\n");
b.append(" \"additionalProperties\": false,\n");
List<String> tables = lockTables();
List<String> rootRequired = new ArrayList<>();
for (String t : tables)
if (!t.isEmpty() && lockFields(t).stream().anyMatch(LockField::required))
rootRequired.add(t);
b.append(" \"required\": ").append(jsonArray(rootRequired)).append(",\n");
b.append(" \"properties\": {\n");
List<String> props = new ArrayList<>();
for (String t : tables) {
if (t.isEmpty()) { for (LockField f : lockFields(t)) props.add(fieldJson(f, " ")); }
else props.add(tableJson(t, " "));
}
// [plugins.<name>] is a dynamic table -- one sub-table per plugin, each the same
// shape -- which LOCK_SCHEMA's fixed table-and-key model has no way to describe,
// so it is hand-appended here rather than rendered from it.
props.add(pluginsTableJson(" "));
b.append(String.join(",\n", props)).append("\n");
b.append(" }\n");
b.append("}\n");
return b.toString();
}
/** The fields declared for one table, in lock order. */
static List<LockField> lockFields(String table) {
List<LockField> out = new ArrayList<>();
for (LockField f : LOCK_SCHEMA) if (f.table().equals(table)) out.add(f);
return out;
}
static String fieldJson(LockField f, String indent) {
return indent + jsonString(f.key()) + ": {\n"
+ indent + " \"type\": \"string\",\n"
+ indent + " \"description\": " + jsonString(f.what()) + ",\n"
+ indent + " \"pattern\": " + jsonString("^" + f.pattern() + "$") + "\n"
+ indent + "}";
}
static String tableJson(String table, String indent) {
List<LockField> fields = lockFields(table);
List<String> required = new ArrayList<>();
for (LockField f : fields) if (f.required()) required.add(f.key());
List<String> props = new ArrayList<>();
for (LockField f : fields) props.add(fieldJson(f, indent + " "));
// An empty "required" is legal and says nothing; [java] has no mandatory key
// because an empty table means exactly what an absent one does.
return indent + jsonString(table) + ": {\n"
+ indent + " \"type\": \"object\",\n"
+ indent + " \"additionalProperties\": false,\n"
+ (required.isEmpty() ? ""
: indent + " \"required\": " + jsonArray(required) + ",\n")
+ indent + " \"properties\": {\n"
+ String.join(",\n", props) + "\n"
+ indent + " }\n"
+ indent + "}";
}
/**
* {@code [plugins.<name>]} for every name at once: an object whose keys are arbitrary
* (plugin names) but whose values all share one shape, which JSON Schema expresses
* with {@code additionalProperties} as a sub-schema rather than {@code properties}.
*/
static String pluginsTableJson(String indent) {
String i2 = indent + " ", i3 = i2 + " ", i4 = i3 + " ", i5 = i4 + " ";
return indent + "\"plugins\": {\n"
+ indent + " \"type\": \"object\",\n"
+ indent + " \"description\": " + jsonString(
"Plugins this project declares -- installed by `flixw plugin install`,"
+ " which writes this table; never a fetch instruction on its own.") + ",\n"
// A name is a single path segment: it reaches <cache>/plugins/<name>/ before
// anything else about the entry is even read, so the schema constrains it as
// strictly as stage 0's own validPluginName() does. additionalProperties
// alone would bound only the *value* shape, not which keys are allowed, and
// would silently accept a plugin name a conforming editor should flag.
+ indent + " \"patternProperties\": {\n"
+ i2 + jsonString("^" + PLUGIN_NAME_PATTERN + "$") + ": {\n"
+ i3 + "\"type\": \"object\",\n"
+ i3 + "\"additionalProperties\": false,\n"
+ i3 + "\"required\": [\"version\", \"sha256\"],\n"
+ i3 + "\"properties\": {\n"
+ i4 + "\"version\": {\n"
+ i5 + "\"type\": \"string\",\n"
+ i5 + "\"description\": \"the plugin version last installed\",\n"
+ i5 + "\"pattern\": " + jsonString("^" + SEMVERISH.pattern() + "$") + "\n"
+ i4 + "},\n"
+ i4 + "\"sha256\": {\n"
+ i5 + "\"type\": \"string\",\n"
+ i5 + "\"description\": \"the SHA-256 of the installed artifact:"
+ " 64 lowercase hex digits\",\n"
+ i5 + "\"pattern\": \"^[0-9a-f]{64}$\"\n"
+ i4 + "},\n"
+ i4 + "\"source\": {\n"
+ i5 + "\"type\": \"string\",\n"
+ i5 + "\"description\": \"where this plugin came from;"
+ " informational, never fetched from automatically\"\n"
+ i4 + "},\n"
+ i4 + "\"description\": {\n"
+ i5 + "\"type\": \"string\",\n"
+ i5 + "\"description\": \"what the plugin is for, as it declared itself"
+ " in its jar manifest at install time; shown by `flixw help`\"\n"
+ i4 + "},\n"
+ i4 + "\"command\": {\n"
+ i5 + "\"type\": \"string\",\n"
+ i5 + "\"description\": \"the bare verb this plugin answers, as it declared"
+ " in its jar manifest; the compiler and the wrapper both win over"
+ " it, and it is recorded here so the claim is reviewable\",\n"
+ i5 + "\"pattern\": " + jsonString("^" + PLUGIN_NAME_PATTERN + "$") + "\n"
+ i4 + "}\n"
+ i3 + "}\n"
+ i2 + "}\n"
+ indent + " },\n"
+ indent + " \"additionalProperties\": false\n"
+ indent + "}";
}
static String jsonArray(List<String> items) {
List<String> quoted = new ArrayList<>();
for (String s : items) quoted.add(jsonString(s));
return quoted.isEmpty() ? "[]" : "[" + String.join(", ", quoted) + "]";
}
/** JSON string literal. Only the escapes RFC 8259 requires; every value here is ASCII. */
static String jsonString(String s) {
StringBuilder b = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"' -> b.append("\\\"");
case '\\' -> b.append("\\\\");
case '\n' -> b.append("\\n");
case '\r' -> b.append("\\r");
case '\t' -> b.append("\\t");
default -> {
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
else b.append(c);
}
}
}
return b.append('"').toString();
}
// ---- lock and manifest ------------------------------------------------
record Lock(String version, String url, String sha256, String repo, String java,
String reportedVersion, Map<String, PluginDep> plugins) {}
/**
* A plugin dependency the project declares: not a fetch instruction, only a record of
* what {@code flixw plugin install} verified when someone last ran it. {@code source}
* is informational, the way a fork's {@code repo} field already is -- {@code pin}
* never reads it to download anything.
*/
record PluginDep(String version, String sha256, String source, String description,
String command) {}
/**
* One `key = value` occurrence, the table it was found in, and the line it sits on.
* `value` is the raw right-hand side; `multiline` marks a `"""` or `'''` opener, whose
* body this scanner deliberately does not reassemble -- no key flixw reads is one.
*/
record TomlEntry(int line, String table, String key, String value, boolean multiline) {}
/** Every scalar entry in a document, plus every table header, in file order. */
record TomlScan(List<TomlEntry> entries, List<String> tables) {}
/**
* The single TOML line scanner in stage 0.
*
* This is not a TOML parser and does not try to be one -- stage 0 has no dependencies
* by design. It is deliberately table-aware, comment-aware and multi-line-string-aware,
* because the alternative that a plain regex gives you is reading `flix = "..."` out of
* some unrelated table, or out of the body of a description string.
*
* There is exactly one of these because there used to be two: `pin`'s rewrite carried a
* second copy that had never learned about multi-line strings, so a `flix = "9.9.9"`
* inside a `"""` description was correctly invisible to the lookup and yet rewritable
* by pin. Any divergence here means the version flixw reads is not the one it writes,
* so the two readers share a scanner rather than a convention.
*
* Lines are split on \n alone, never on \r?\n: `pin` rejoins with \n to rewrite a
* single line in place, and a split that swallowed the \r would quietly convert a CRLF
* manifest to LF. The trailing \r survives into the raw line and is removed by trim().
*/
static TomlScan tomlScan(String text, String where) {
List<TomlEntry> entries = new ArrayList<>();
List<String> tables = new ArrayList<>();
String current = "";
String mlDelim = null;
int arrayDepth = 0;
String[] lines = text.split("\n", -1);
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
// Inside a value that spans lines as an array, nothing is a key. A line-based
// reader took an authors entry holding `flix = "9.9.9"` for an assignment, and
// an unbalanced quote in one made the whole manifest unreadable -- a legal file
// this wrapper simply refused to work with. Depth counts brackets outside
// quotes, so a bracket inside a string stays text.
if (arrayDepth > 0) {
arrayDepth += bracketDelta(line);
continue;
}
if (mlDelim != null) { // inside """ or ''': find the close
int e = line.indexOf(mlDelim);
if (e < 0) continue;
line = line.substring(e + 3); // three chars either way
mlDelim = null;
}
String t = stripComment(line).trim();
if (t.isEmpty()) continue;
if (t.startsWith("[[")) {
// Fail closed: only a well-formed array-of-tables header counts as
// one, rather than anything that merely opens with two brackets.
if (!t.endsWith("]]"))
throw w002(where + ": malformed array-of-tables header " + q(t));
current = "\u0000array";
continue;
}
if (t.startsWith("[")) {
int close = t.indexOf(']');
if (close < 0) throw w002(where + ": unterminated table header " + q(t));
// Trailing text used to be dropped, so `[package] junk` read as
// `[package]`. A header the scanner cannot account for entirely is
// one it has no business guessing at.
if (!t.substring(close + 1).isBlank())
throw w002(where + ": trailing text after table header " + q(t));
current = String.join(".", splitKey(t.substring(1, close), where));
tables.add(current);
continue;
}
int eq = t.indexOf('=');
if (eq < 0) continue;
// A dotted key is a table path, and TOML lets it be written with spaces around
// the dots and with any segment quoted -- `package . flix`, `package."flix"`
// and `"package".flix` all mean [package].flix. Matching the raw text meant
// only the tightest spelling was seen, so a manifest could state a floor this
// scanner did not read: the check passed, and an older compiler ran.
List<String> path = splitKey(t.substring(0, eq), where);
String k = path.get(path.size() - 1);
String tbl = current;
if (path.size() > 1) {
String prefix = String.join(".", path.subList(0, path.size() - 1));
tbl = current.isEmpty() ? prefix : current + "." + prefix;
}
String v = t.substring(eq + 1).trim();
String delim = v.startsWith("\"\"\"") ? "\"\"\"" : v.startsWith("'''") ? "'''" : null;
if (delim != null && !v.substring(3).contains(delim)) mlDelim = delim;
else if (delim == null) arrayDepth = Math.max(0, bracketDelta(v));
entries.add(new TomlEntry(i, tbl, k, v, delim != null));
}
return new TomlScan(entries, tables);
}
/**
* True when an entry is `table.key`. Dotted keys are resolved to their table by
* {@link #tomlScan}, so both spellings arrive here already in the same shape.
*/
static boolean isKey(TomlEntry e, String table, String key) {
return e.table().equals(table) && e.key().equals(key);
}
/**
* Splits a key into its segments, respecting quotes, then unquotes and trims each one.
* `a.b` is two segments; `"a.b"` is one. Fails closed: an unterminated quote or an
* empty segment is a manifest this scanner will not guess at.
*/
static List<String> splitKey(String raw, String where) {
List<String> parts = new ArrayList<>();
StringBuilder cur = new StringBuilder();
char quote = 0;
for (int i = 0; i < raw.length(); i++) {
char c = raw.charAt(i);
if (quote != 0) { cur.append(c); if (c == quote) quote = 0; }
else if (c == '"' || c == '\'') { quote = c; cur.append(c); }
else if (c == '.') { parts.add(cur.toString()); cur.setLength(0); }
else cur.append(c);
}
if (quote != 0) throw w002(where + ": unterminated quoted key " + q(raw.trim()));
parts.add(cur.toString());
List<String> out = new ArrayList<>();
for (String part : parts) {
String seg = unquote(part.trim());
if (seg.isEmpty()) throw w002(where + ": empty key segment in " + q(raw.trim()));
out.add(seg);
}
return out;
}
/**
* Reads one key from one TOML table. Anything it cannot classify inside the table it
* was asked about is rejected rather than guessed at. Duplicate tables and duplicate
* keys are ambiguous, so they fail rather than resolve.
*
* Accepts the key inside [table] and as a dotted key at the root (`package.flix`).
*/
static String tomlLookup(String text, String table, String key, String where) {
TomlScan scan = tomlScan(text, where);
String value = null;
int hits = 0;
for (TomlEntry e : scan.entries()) {
if (!isKey(e, table, key)) continue;
if (e.multiline()) throw w002(where + ": " + q(key) + " must be a single-line string");
hits++;
String v = e.value();
if (v.length() < 2 || v.charAt(0) != v.charAt(v.length() - 1)
|| (v.charAt(0) != '"' && v.charAt(0) != '\''))
throw w002(where + ": " + q(key) + " must be a quoted string, got " + q(v));
value = v.substring(1, v.length() - 1);
}
int tables = 0;
for (String t : scan.tables()) if (t.equals(table)) tables++;
if (tables > 1) throw w002(where + ": duplicate [" + table + "] table");
if (hits > 1) throw w002(where + ": duplicate " + q(key) + " key in [" + table + "]");
return value;
}
/**
* How much this line opens or closes an inline array, counting only brackets outside
* quotes. Used to skip a value that spans lines; it never goes below zero, because a
* stray closing bracket is not this scanner's business to diagnose.
*/
static int bracketDelta(String line) {
String t = stripComment(line);
int depth = 0;
boolean sq = false, dq = false;
for (int i = 0; i < t.length(); i++) {
char c = t.charAt(i);
if (c == '\'' && !dq) sq = !sq;
else if (c == '"' && !sq) dq = !dq;
else if (!sq && !dq) {
if (c == '[') depth++;
else if (c == ']') depth--;
}
}
return depth;
}
/** Strips a trailing comment, ignoring '#' inside quotes. */
static String stripComment(String line) {
boolean s = false, d = false;
for (int i = 0; i < line.length(); i++) {
char c = line.charAt(i);
if (c == '\'' && !d) s = !s;
else if (c == '"' && !s) d = !d;
else if (c == '#' && !s && !d) return line.substring(0, i);
}
return line;
}
static String unquote(String s) {
if (s.length() >= 2 && (s.charAt(0) == '"' || s.charAt(0) == '\'')
&& s.charAt(s.length() - 1) == s.charAt(0)) return s.substring(1, s.length() - 1);
return s;
}
/**
* A quoted TOML value, fully unescaped -- unlike {@link #unquote}, which every
* existing caller uses for a version, URL or digest, none of which can legally
* contain a backslash, so stripping the outer quotes has always been the whole job.
* A task's command string is arbitrary shell syntax, where `\"` and embedded quotes
* are the ordinary case, so this processes TOML's basic-string escapes for real. A
* single-quoted (literal) string has none to process by definition -- exactly the
* TOML feature that lets a task avoid this entirely by not using `"..."`.
*/
static String unquoteToml(String v, String where) {
if (v.length() < 2 || v.charAt(0) != v.charAt(v.length() - 1)
|| (v.charAt(0) != '"' && v.charAt(0) != '\''))
throw w002(where + ": " + q(v) + " must be a quoted string");
String inner = v.substring(1, v.length() - 1);
if (v.charAt(0) == '\'') return inner; // literal string: no escapes
StringBuilder b = new StringBuilder();
for (int i = 0; i < inner.length(); i++) {
char c = inner.charAt(i);
if (c != '\\') { b.append(c); continue; }
if (i + 1 >= inner.length()) throw w002(where + ": trailing backslash in " + q(v));
char n = inner.charAt(++i);
switch (n) {
case '"' -> b.append('"');
case '\\' -> b.append('\\');
case 'b' -> b.append('\b');
case 't' -> b.append('\t');
case 'n' -> b.append('\n');
case 'f' -> b.append('\f');
case 'r' -> b.append('\r');
// The lowercase and uppercase Unicode escapes differ only in digit count;
// malformed hex and an out-of-range or surrogate-half code point are both
// "not a valid escape" here rather than an uncaught NumberFormatException
// or IllegalArgumentException -- a hand-edited tasks.toml or lock.toml is
// exactly where that kind of typo shows up, and it must answer with
// FLIXW002, not a stack trace. (Spelled out rather than written literally,
// because the sequence backslash-u is itself a Java source escape.)
case 'u', 'U' -> {
int len = n == 'u' ? 4 : 8;
if (i + len >= inner.length())
throw w002(where + ": incomplete \\" + n + " escape in " + q(v));
String hex = inner.substring(i + 1, i + 1 + len);
try {
int cp = Integer.parseInt(hex, 16);
if (!Character.isValidCodePoint(cp) || (cp >= 0xD800 && cp <= 0xDFFF))
throw new NumberFormatException();
b.appendCodePoint(cp);
} catch (NumberFormatException e) {
throw w002(where + ": \\" + n + hex
+ " is not a valid Unicode code point in " + q(v));
}
i += len;
}
default -> throw w002(where + ": invalid escape " + q("\\" + n) + " in " + q(v));
}
}
return b.toString();
}
static Path lockPath(Path root) { return root.resolve(WRAPPER_DIR).resolve("lock.toml"); }
static Path tasksPath(Path root) { return root.resolve(WRAPPER_DIR).resolve("tasks.toml"); }
/**
* `.flixw/tasks.toml`: npm-`scripts`-style name-to-shell-string pairs, hand-edited and
* committed like `lock.toml` itself, but never generated or rewritten by `pin` or
* `doctor --fix` -- unlike the lock, this file is the human's to write, so it carries
* no `#:schema` directive and no "generated" header. Flat by design: a table would
* invite grouping that a shell string running through `sh -c`/`cmd /c` gets no benefit
* from, and it is one fewer thing {@link #tomlScan}'s callers here have to check for.
*/
static Map<String, String> readTasks(Path root) {
Path f = tasksPath(root);
if (!Files.isRegularFile(f)) return Map.of();
String text;
try { text = Files.readString(f, StandardCharsets.UTF_8); }
catch (IOException e) { throw w002("cannot read " + f + ": " + why(e)); }
String w = f.toString();
Map<String, String> out = new LinkedHashMap<>();
for (TomlEntry e : tomlScan(text, w).entries()) {
if (!e.table().isEmpty())
throw w002(w + ": [" + e.table() + "] -- tasks.toml holds only"
+ " name = \"command\" pairs, no tables");
if (e.multiline())
throw w002(w + ": " + q(e.key()) + " must be a single-line string");
out.put(e.key(), unquoteToml(e.value(), w));
}
return out;
}
static Lock readLock(Path lockFile) {
String text;
try { text = Files.readString(lockFile, StandardCharsets.UTF_8); }
catch (IOException e) {
throw w002("cannot read " + lockFile + ": " + why(e)
+ "\n run: ./flixw pin <version>");
}
String w = lockFile.toString();
Map<String, String> got = readLockFields(text, w);
noteUnknownLockKeys(text, w, got.get("wrapperVersion"));
String u = got.get("compiler.url");
String j = got.get("java.version");
// What a pattern cannot say. The schema has already accepted both values as
// well-formed; these are the checks that need more than their shape -- that the
// URL names a host and does not climb out of its path, and that the java pin is
// one the compiler can actually run under.
validateUrl(u, w);
if (j != null) validateJavaPin(j, w);
// repo is absent in locks written before forks were supported, and means the stock
// repository. java is absent whenever a project does not care which JDK it gets.
return new Lock(got.get("compiler.version"), u, got.get("compiler.sha256"),
got.get("compiler.repo"), j, got.get("compiler.reported_version"),
readPlugins(text, w));
}
/**
* {@code [plugins.<name>]} tables, keyed by name -- a dynamic set `LOCK_SCHEMA`'s
* fixed-table-and-key model cannot describe, so it is read directly from
* {@link #tomlScan} rather than through {@link #readLockFields}. Each declared
* plugin needs `version` and `sha256`; `source` is optional and never used to fetch
* anything, only shown to a reader deciding what to install.
*/
static Map<String, PluginDep> readPlugins(String text, String where) {
Map<String, String> version = new LinkedHashMap<>(), sha = new LinkedHashMap<>(),
source = new LinkedHashMap<>(), description = new LinkedHashMap<>(),
command = new LinkedHashMap<>();
Set<String> seenKeys = new LinkedHashSet<>();
Set<String> knownKeys = Set.of("version", "sha256", "source", "description",
"command");
for (TomlEntry e : tomlScan(text, where).entries()) {
if (!e.table().startsWith("plugins.")) continue;
String name = e.table().substring("plugins.".length());
// Fails closed, the same way an invalid sha256 or version does below: a lock
// is exactly as attacker-controlled as anything else committed to a repo, and
// a plugin name reaches a filesystem path in resolvePlugin/pluginDir.
if (!validPluginName(name))
throw w002(where + ": [plugins." + name + "] is not a valid plugin name"
+ " -- lowercase letters, digits and hyphens, starting with a letter");
// An unrecognized key inside a known table is advisory everywhere else in this
// file (unknownLockKeys / FLIXW011) -- a lock a newer flixw wrote is the
// ordinary way to meet one. Skipped *before* unquoting, so a future key
// holding a non-string value (an integer, a bare array) is exactly as
// survivable as a future key holding a string: neither is ever parsed here.
if (!knownKeys.contains(e.key())) continue;
if (!seenKeys.add(name + "." + e.key()))
throw w002(where + ": duplicate " + q(e.key()) + " key in [plugins." + name + "]");
if (e.multiline())
throw w002(where + ": [plugins." + name + "] " + q(e.key())
+ " must be a single-line string");
String v = unquoteToml(e.value(), where);
switch (e.key()) {
case "version" -> version.put(name, v);
case "sha256" -> sha.put(name, v);
case "source" -> source.put(name, v);
case "description" -> description.put(name, v);
case "command" -> command.put(name, v);
}
}
Map<String, PluginDep> out = new LinkedHashMap<>();
Set<String> names = new LinkedHashSet<>();
names.addAll(version.keySet());
names.addAll(sha.keySet());
for (String name : names) {
String v = version.get(name);
if (v == null)
throw w002(where + ": [plugins." + name + "] is missing version");
if (!SEMVERISH.matcher(v).matches())
throw w002(where + ": [plugins." + name + "] version is " + q(v)
+ "\n expected x.y.z, optionally with a prerelease and"
+ " build metadata");
String d = sha.get(name);
if (d == null)
throw w002(where + ": [plugins." + name + "] is missing sha256");
if (!d.matches("[0-9a-f]{64}"))
throw w002(where + ": [plugins." + name + "] sha256 is " + q(d)
+ "\n expected 64 lowercase hex digits");
out.put(name, new PluginDep(v, d, source.get(name),
description.getOrDefault(name, ""),
command.getOrDefault(name, "")));
}
return out;
}
/**
* Reads every key {@link #LOCK_SCHEMA} declares, keyed as `table.key` with the root
* table's keys unprefixed. Absent optional keys are simply not in the map.
*
* Presence and shape are both checked here, from the same list the published JSON
* Schema is rendered from, so a lock an editor flags is a lock flixw refuses -- and
* the diagnostic can say what the key is *for* rather than quoting a regex at someone.
*/
static Map<String, String> readLockFields(String text, String where) {
Map<String, String> got = new LinkedHashMap<>();
for (LockField f : LOCK_SCHEMA) {
String v = tomlLookup(text, f.table(), f.key(), where);
if (v == null) {
if (!f.required()) continue;
throw w002(where + ": missing " + f.name() + " -- " + f.what()
+ "\n run: ./flixw pin <version>");
}
if (!v.matches(f.pattern()))
throw w002(where + ": " + f.name() + " is " + q(v)
+ "\n expected " + f.what()
+ "\n run: ./flixw pin <version>");
got.put(f.table().isEmpty() ? f.key() : f.table() + "." + f.key(), v);
}
return got;
}
/**
* Keys the schema does not describe, reported once and never fatally.
*
* Advisory because the ordinary way to meet one is a lock written by a newer flixw,
* and refusing to run would make such a project unbuildable by every collaborator who
* had not upgraded yet -- the lock is committed, so that is most of them. Silence is
* the wrong answer too: a mistyped key is otherwise invisible, and the value someone
* believed they had set is simply never read.
*
* A lock that says it was written by a newer flixw gets no note at all, because there
* the unknown key is expected and the message would be wrong as well as noisy.
*/
static void noteUnknownLockKeys(String text, String where, String wroteIt) {
// A run reads the lock more than once by design -- `doctor` reads it, then reads
// it again to decide whether to rewrite it -- and an advisory said twice reads as
// two problems. Once per file per run is what "reported once" means.
if (!NOTED_LOCKS.add(where)) return;
if (wroteIt != null && !olderOrSame(wroteIt, WRAPPER_VERSION)) return;
List<String> unknown = unknownLockKeys(text, where);
if (unknown.isEmpty()) return;
w011(where + ": " + String.join(", ", unknown)
+ (unknown.size() == 1 ? " is not a key flixw reads, and is ignored"
: " are not keys flixw reads, and are ignored")
+ "\n the keys a lock may hold: " + LOCK_SCHEMA_URL);
}
/** Locks already reported on, so a second read in the same run stays quiet. */
static final Set<String> NOTED_LOCKS = new LinkedHashSet<>();
/**
* Every key in the file that {@link #LOCK_SCHEMA} does not describe, named the way a
* diagnostic names it, in file order and without repeats.
*
* Separate from the note because `doctor --fix` asks the same question for the
* opposite reason: it regenerates the lock from the values it read, which would
* *delete* any key it did not read.
*/
static List<String> unknownLockKeys(String text, String where) {
List<String> unknown = new ArrayList<>();
for (TomlEntry e : tomlScan(text, where).entries()) {
// [plugins.<name>] is a dynamic table LOCK_SCHEMA cannot enumerate by name;
// readPlugins() is the authority on which of its keys it actually reads.
boolean known = e.table().startsWith("plugins.")
&& List.of("version", "sha256", "source", "description", "command")
.contains(e.key());
if (!known)
for (LockField f : LOCK_SCHEMA)
if (isKey(e, f.table(), f.key())) { known = true; break; }
String name = e.table().isEmpty() ? e.key() : "[" + e.table() + "] " + e.key();
if (!known && !unknown.contains(name)) unknown.add(name);
}
return unknown;
}
/**
* The manifest is the human authority; disagreement stops us before the network. A
* manifest that exists but cannot be read is an error, not an absent declaration --
* swallowing it would silently disable drift detection and let the compiler run.
*/
static String manifestVersion(Path manifest) {
if (!Files.isRegularFile(manifest)) return null;
String text;
try { text = Files.readString(manifest, StandardCharsets.UTF_8); }
catch (IOException e) { throw w002("cannot read " + manifest + ": " + why(e)); }
String declared = tomlLookup(text, "package", "flix", manifest.toString());
return declared == null ? null : validateVersion(declared, manifest.toString());
}
// ---- cache ------------------------------------------------------------
static boolean isWindows() {
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).startsWith("windows");
}
static boolean isMac() {
return System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("mac");
}
static Path cacheHome() {
String o = env("FLIX_CACHE_HOME");
if (o != null) return Paths.get(o).toAbsolutePath();
String home = System.getProperty("user.home");
if (isWindows()) {
String local = env("LOCALAPPDATA");
return Paths.get(local != null ? local : home).resolve("flixw");
}
if (isMac()) return Paths.get(home, "Library", "Caches", "flixw");
String xdg = env("XDG_CACHE_HOME");
return (xdg != null ? Paths.get(xdg) : Paths.get(home, ".cache")).resolve("flixw");
}
static String sha256(Path file) {
try (InputStream in = Files.newInputStream(file)) {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] buf = new byte[1 << 16];