-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflixw.java
More file actions
4480 lines (4209 loc) · 237 KB
/
Copy pathflixw.java
File metadata and controls
4480 lines (4209 loc) · 237 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.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.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.time.Duration;
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.24.1";
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");
/**
* 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("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, " "));
}
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 + "}";
}
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) {}
/**
* 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;
}
static Path lockPath(Path root) { return root.resolve(WRAPPER_DIR).resolve("lock.toml"); }
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);
}
/**
* 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()) {
boolean known = false;
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];
for (int n; (n = in.read(buf)) > 0; ) md.update(buf, 0, n);
return String.format("%064x", new BigInteger(1, md.digest()));
} catch (Exception e) {
throw w007("cannot hash " + file + ": " + e.getMessage());
}
}
static String sha256(byte[] b) {
try {
return String.format("%064x",
new BigInteger(1, MessageDigest.getInstance("SHA-256").digest(b)));
} catch (Exception e) { throw w007("cannot hash: " + e.getMessage()); }
}
/** Where the stock compiler comes from when nothing says otherwise. */
static final String UPSTREAM_REPO = "flix/flix";
/**
* One usage line for `pin`, because four diagnostics quote it and the fourth was
* already a release behind the first the last time one was written out by hand.
*/
static final String PIN_USAGE =
"usage: ./flixw pin [<owner>/<repo>] [<version>] [--java <version>]"
+ "\n or: ./flixw pin --refresh (rewrite the lock in this release's shape)";
/** One release asset: what to fetch, and what the publisher says it hashes to. */
record Asset(String name, String url) {}
static String checkRepo(String repo, String where) {
if (!repo.matches(REPO_PATTERN))
throw w002(where + ": " + q(repo) + " is not an owner/repository");
return repo;
}
/** A release tag in a URL path. Only '+' needs it; the rest of a version is path-safe. */
static String encodeTag(String tag) { return tag.replace("+", "%2B"); }
/**
* Resolves the compiler artifact for one repository and version, without asking an
* API anything.
*
* The GitHub API answered this in one call and threw in a digest, and it was the
* wrong tool: unauthenticated it allows sixty requests an hour across everything on
* the machine, so `pin` failed with HTTP 403 for a tag that plainly existed, and the
* error blamed the tag. Release *downloads* carry no such limit, so the asset name --
* the only thing that was ever unknown -- is found by asking for the file itself.
*
* Upstream is a single constructed URL, as before. A fork is probed against the two
* conventions in the wild, {@code flix-<version>.jar} and `flix.jar`, with a HEAD each; the
* download that follows is still exactly one acquisition attempt for one artifact.
*/
static Asset resolveRelease(String repo, String version) {
if (repo.equals(UPSTREAM_REPO)) {
String u = "https://github.com/" + UPSTREAM_REPO + "/releases/download/v"
+ canonical(version) + "/flix.jar";
return new Asset("flix.jar", u);
}
String base = "https://github.com/" + repo + "/releases/download/"
+ encodeTag("v" + version) + "/";
List<String> tried = new ArrayList<>();
for (String name : List.of("flix-" + version + ".jar", "flix.jar")) {
String u = base + encodeTag(name);
tried.add(u);
if (assetExists(u)) {
validateUrl(u, repo + " release v" + version);
return new Asset(name, u);
}
}
throw w005("no compiler jar found in " + repo + " release " + q("v" + version)
+ "\n tried " + String.join("\n ", tried)
+ "\n the version must match the tag exactly, build metadata included");
}
/**
* The one HTTP client, pinned to HTTP/1.1.
*
* Every request flixw makes is a single one-shot HEAD or GET, so HTTP/2 buys nothing
* here -- there are no concurrent streams to multiplex onto one connection -- and it
* costs a failure mode that only shows up as a red CI run. When a server sends GOAWAY
* while a stream is being opened, the JDK client raises `request not processed by
* peer`; because acquisition is one attempt with no retry loop, that lands on the user
* as a failed download and, through the missing lock, as fifteen further failures.
* That is a real observation, not a theoretical one: it took out the whole windows
* smoke job on ccba32b while ubuntu and macos passed the same commit.
*
* Pinning 1.1 deletes the race rather than retrying around it, which is the trade this
* project already makes everywhere else -- a retry would have to be bounded, logged
* and explained, and would still leave the request that *was* processed ambiguous.
*/
static HttpClient httpClient() {
return HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(30)).build();
}
/** Does this release asset exist? A HEAD, so the download itself stays a single attempt. */
static boolean assetExists(String url) {
HttpClient client = httpClient();
HttpRequest req = HttpRequest.newBuilder(URI.create(url))
.method("HEAD", HttpRequest.BodyPublishers.noBody())
.timeout(Duration.ofSeconds(60))
.header("User-Agent", "flixw/" + WRAPPER_VERSION).build();
try {
HttpResponse<Void> res = client.send(req, HttpResponse.BodyHandlers.discarding());
return res.statusCode() == 200 && "https".equals(res.uri().getScheme());
} catch (IOException e) {
return false;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
/** What one `pin` command line asks for; `parsePin` is the only thing that builds it. */
record Pin(String repo, String version, String java, boolean clearJava, boolean refresh) {}
/**
* {@code ./flixw pin [<owner>/<repo>] [<version>] [--java <version>]}, or
* {@code ./flixw pin --refresh}.
*
* The two are told apart by the slash, which a version can never contain -- the
* grammar rejects it -- so the order does not matter and neither does a flag. An
* omitted repository means the one already in the lock, so re-pinning a project that
* tracks a fork stays on that fork: rebuilding the upstream URL every time silently
* moved such a project back to stock, and because both are honestly version 0.75.2,
* nothing about it looked wrong.
*/
static Pin parsePin(List<String> args, Lock existing) {
String repo = null, version = null, java = null, clearJava = null;
boolean repoGiven = false, refresh = false;
for (int i = 0; i < args.size(); i++) {
String a = args.get(i);
if (a.equals("--java")) {
if (java != null || clearJava != null) throw w009("pin: two --java values given");
if (i + 1 >= args.size())
throw w002("pin: --java needs a version\n for example:"
+ " ./flixw pin --java " + MIN_JAVA + " (or --java none)");
String v = args.get(++i);
if (v.equals("none")) clearJava = "yes"; else { validateJavaPin(v, "pin"); java = v; }
} else if (a.equals("--refresh")) {
refresh = true;
} else if (a.startsWith("--")) {
throw w008("pin: unknown option " + q(a) + "\n " + PIN_USAGE);
} else if (a.contains("/")) {
if (repo != null) throw w009("pin: two repositories given");
repo = checkRepo(a, "pin");
repoGiven = true;
} else {
if (version != null) throw w009("pin: two versions given");
version = a;
}
}
if (refresh) {
// --refresh rewrites the lock from the lock. Everything else on this line
// changes what the lock says, and doing one of the two silently is how a
// repair loses the pin it was asked to preserve.
if (version != null || repoGiven || java != null || clearJava != null)
throw w008("pin: --refresh takes no other arguments -- it rewrites the lock"
+ " in the shape flixw " + WRAPPER_VERSION + " writes,"
+ "\n from the values already in it, without moving the pin"
+ "\n " + PIN_USAGE);
if (existing == null)
throw w002("pin: --refresh needs a lock that parses"
+ "\n run: ./flixw pin <version>");
return new Pin(null, null, null, false, true);
}
// A compiler version is required unless this is only a Java pin, in which case
// the compiler stays exactly as it was -- rewriting the lock is not repinning it.
if (version == null && java == null && clearJava == null)
throw w002("pin: no version\n " + PIN_USAGE);
// Naming a repository without a version was accepted and then quietly dropped: a
// --java-only pin rewrites one line and does not re-resolve the compiler, so the
// repository had nowhere to go. Changing where the compiler comes from means
// fetching it, which means saying which version to fetch.
if (version == null && repoGiven)
throw w002("pin: a repository needs a version -- changing it means fetching"
+ " that compiler\n for example: ./flixw pin " + repo
+ " <version> --java " + (java == null ? MIN_JAVA + "" : java));
if (version == null && existing == null)
throw w002("pin: --java needs an existing lock, or a compiler version to write"
+ " one\n for example: ./flixw pin 0.75.2 --java " + MIN_JAVA);
// Normalized before validation, so the lock records the version rather than the tag
// it was typed as, and two spellings of one release cannot produce two locks.
if (version != null) version = validateVersion(stripTagPrefix(version), "pin");
if (repo == null) repo = existing != null && existing.repo() != null
? existing.repo() : UPSTREAM_REPO;
return new Pin(repo, version, java, clearJava != null, false);
}
// ---- acquisition ------------------------------------------------------
/** True when a path names something inside the cache flixw fills with pinned compilers. */
static boolean insideCompilerCache(Path jar) {
return jar.normalize().startsWith(cacheHome().resolve("compilers").normalize());
}
/**
* Says so when {@code FLIX_JAR} names a compiler out of flixw's own cache.
*
* A mismatch between the override and the lock is the *ordinary* case -- the override
* exists to run a jar you built yourself, which is not the pinned one and is not meant
* to be -- so it is reported where state is printed, and not on every run.
*
* Pointing it inside {@code <cache>/compilers/} is different, and is always a mistake.
* Those names are content-addressed, {@code flix-<version>-<sha256>.jar}, so **the path
* changes every time the project is re-pinned**. An override set once to whatever
* `info` reported that day goes on naming the superseded artifact afterwards, and the
* project quietly builds with the compiler it used to pin. Nothing else in flixw could
* catch it: the digest guard is switched off by the override, and the version check
* passes because two builds of one release share a canonical version.
*
* Matching the lock is a mistake too, only a harmless one: it names the jar flixw would
* have chosen anyway, and it will stop doing that at the next pin.
*/
static void reportOverrideGap(Lock lock, Path jar) {
if (lock == null || !insideCompilerCache(jar)) return;
String got = sha256(jar);
if (got.equals(lock.sha256()))
w010("FLIX_JAR names flixw's own cache entry for the pinned compiler."
+ "\n That is the jar flixw would have used anyway, and the name"
+ " changes at the next pin."
+ "\n run: unset FLIX_JAR");
else
w010("FLIX_JAR names a compiler from flixw's cache that is NOT the pinned one."
+ "\n override " + got.substring(0, 16) + "... lock pins "
+ lock.sha256().substring(0, 16) + "..."
+ "\n Cache names carry the digest, so this path is an earlier pin"
+ " left behind by a re-pin."
+ "\n run: unset FLIX_JAR (or ./flixw pin <that version> to make"
+ " it the pin)");
}
static Path compilerPath(Lock lock) {
return cacheHome().resolve("compilers")
.resolve("flix-" + canonical(lock.version()) + "-" + lock.sha256() + ".jar");
}
/**
* Validated on every run, not only when a download happens: a warm cache would
* otherwise hide a malformed mirror setting until the day it is actually needed.