@fraczak/k 7.0.2 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/DOCS/FILE_FORMATS.md +238 -15
  3. package/DOCS/POLYMORPHIC_IR.md +104 -0
  4. package/JOURNAL.md +288 -0
  5. package/README.md +10 -2
  6. package/access-table.mjs +343 -0
  7. package/backend-api.mjs +18 -0
  8. package/backends/llvm/README.md +20 -21
  9. package/backends/llvm/bin/k-llvm-build.mjs +105 -32
  10. package/backends/llvm/bin/k-llvm-compile.mjs +63 -24
  11. package/backends/llvm/bin/k-llvm.mjs +292 -0
  12. package/backends/llvm/runtime/krt.c +8 -0
  13. package/backends/llvm/runtime/krt.h +1 -0
  14. package/backends/llvm/src/cli.mjs +95 -17
  15. package/backends/llvm/src/executable.mjs +128 -11
  16. package/backends/llvm/src/kvm2llvm.mjs +10 -5
  17. package/backends/llvm/src/llvm.mjs +121 -9
  18. package/backends/llvm/tests/integration.sh +11 -11
  19. package/backends/llvm/{bin → tests}/k-llvm-run.mjs +48 -22
  20. package/backends/llvm/tests/perf-support.mjs +24 -3
  21. package/backends/llvm/tests/test-llvm.mjs +22 -1
  22. package/backends/wasm/bin/k-wasm-compile.mjs +46 -20
  23. package/backends/wasm/bin/k-wasm-run.mjs +61 -20
  24. package/backends/wasm/bin/k-wasm.mjs +47 -13
  25. package/backends/wasm/src/cli.mjs +141 -19
  26. package/backends/wasm/src/wasm.mjs +130 -23
  27. package/browser/repl-browser.mjs +16 -5
  28. package/codecs/k-parse.mjs +29 -8
  29. package/codecs/k-print.mjs +22 -6
  30. package/codecs/runtime/codec-sdk.mjs +8 -4
  31. package/codecs/show.mjs +20 -6
  32. package/k.mjs +56 -16
  33. package/kir.mjs +58 -19
  34. package/kvm.mjs +49 -12
  35. package/objects/compile.mjs +37 -23
  36. package/objects/decompile.mjs +40 -10
  37. package/objects/extract-aliases.mjs +44 -14
  38. package/objects/inspect.mjs +19 -14
  39. package/objects/validate.mjs +18 -11
  40. package/package.json +10 -3
  41. package/pkir.mjs +772 -0
  42. package/repl.mjs +36 -18
  43. package/scripts/build-repl-html.mjs +14 -2
  44. package/scripts/perf-ieee.mjs +264 -13
  45. package/scripts/perf-int.mjs +315 -22
  46. package/scripts/perf-multiplication.mjs +58 -7
  47. package/scripts/perf-poly.mjs +306 -24
  48. package/scripts/run-tests.mjs +3 -0
  49. package/tests/test-access-table.mjs +213 -0
  50. package/tests/test-pkir.mjs +530 -0
  51. package/tests/test-polymorphic-tdd.mjs +196 -0
  52. package/tests/test-repl-html.mjs +15 -2
  53. package/tests/test-repl.mjs +30 -1
  54. package/backends/llvm/bin/k-llvm-jit.mjs +0 -160
package/codecs/show.mjs CHANGED
@@ -6,13 +6,27 @@ import { isMainEntrypoint } from "./runtime/cli-entry.mjs";
6
6
  import { decodeWire } from "./runtime/prefix-codec.mjs";
7
7
  import { propertyListToFilter, valueToK } from "./runtime/show-value.mjs";
8
8
 
9
+ function helpText() {
10
+ const prog = argv[1] || "show.mjs";
11
+ return [
12
+ "Pass a binary wire stream through unchanged on stdout while",
13
+ "printing the decoded value and filter to stderr.",
14
+ "",
15
+ `Usage: ${prog} [wire-file]`,
16
+ "",
17
+ "Arguments:",
18
+ " wire-file Input binary wire file (default: stdin).",
19
+ "",
20
+ "Options:",
21
+ " -h, --help Show this help.",
22
+ "",
23
+ "Examples:",
24
+ ` echo '"hello"' | k-parse | ${prog} | k-print`
25
+ ].join("\n");
26
+ }
27
+
9
28
  function usage(stream = console.error) {
10
- stream(`Usage: ${argv[1]} [wire-file]`);
11
- stream(" Pass the wire stream through unchanged on stdout.");
12
- stream(" Print the decoded value and filter to stderr.");
13
- stream("");
14
- stream("Options:");
15
- stream(" -h, --help Show this help.");
29
+ stream(helpText());
16
30
  }
17
31
 
18
32
  function readAll(stream) {
package/k.mjs CHANGED
@@ -4,27 +4,58 @@
4
4
  import fs from "node:fs";
5
5
  import { argv, stdin, exit, stdout } from "node:process";
6
6
  import k from "./index.mjs";
7
- import { decodeWire, encodeToWire } from "./codecs/runtime/prefix-codec.mjs";
8
- import { decodeObject, objectToFunction, loadLibrary } from "./object.mjs";
9
-
10
- const prog = argv[1];
7
+ import {
8
+ decodeWire,
9
+ encodeToWire
10
+ } from "./codecs/runtime/prefix-codec.mjs";
11
+ import {
12
+ compileLibrary,
13
+ decodeObject,
14
+ objectToFunction,
15
+ loadLibrary
16
+ } from "./object.mjs";
11
17
 
12
18
  let kScript, inputStream;
13
19
 
14
- function usage() {
15
- console.error(`Usage: ${prog} [ --lib lib-file ] [ --export spec ]... ( k-expr | file ) [ input-file ]`);
16
- console.error(` E.g., echo '["zebara","ela"]' | k-parse --input-type '$x=<{} zebara, {} ela>; $v={x 0, x 1}; $v' | ${prog} '{.1 0}'`);
17
- console.error("Options:");
18
- console.error(" --lib file Load one .klib dependency before compiling.");
19
- console.error(" --export spec Export a library alias into scope. 'name' or 'libname:localname'. May be repeated.");
20
- console.error(" -h, --help Show this help.");
20
+ function helpText() {
21
+ const prog = argv[1] || "k.mjs";
22
+ return [
23
+ "Compile and execute a k expression or file over a binary",
24
+ "pattern+value wire stream using the JavaScript interpreter.",
25
+ "",
26
+ `Usage: ${prog} [options]`,
27
+ " ( source-snippet | input-file ) [ input-wire-file ]",
28
+ "",
29
+ "Arguments:",
30
+ " source-snippet Inline k source snippet.",
31
+ " input-file Source .k, .ko, or .klib file.",
32
+ " input-wire-file Optional binary wire input (default: stdin).",
33
+ "",
34
+ "Options:",
35
+ " --lib file Load one .klib or .k library before compiling.",
36
+ " --export spec Export library alias into scope. Repeatable.",
37
+ " spec is 'name' or 'libname:localname'.",
38
+ " -h, --help Show this help.",
39
+ "",
40
+ "Examples:",
41
+ ` echo '"abc"' | k-parse | ${prog} '{.1 0}' | k-print`,
42
+ ` echo '{"x":1,"y":2}' | k-json --parse | \\`,
43
+ ` ${prog} --lib Examples/poly.k --export concat \\`,
44
+ ` 's={()xs,()ys}concat; s' | k-json --print`
45
+ ].join("\n");
46
+ }
47
+
48
+ function usage(stream = console.error) {
49
+ stream(helpText());
21
50
  }
22
51
 
23
52
  function isFile(filePath) {
24
53
  try {
25
54
  return fs.statSync(filePath).isFile();
26
55
  } catch (error) {
27
- if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return false;
56
+ if (error?.code === "ENOENT" || error?.code === "ENOTDIR") {
57
+ return false;
58
+ }
28
59
  throw error;
29
60
  }
30
61
  }
@@ -41,7 +72,7 @@ function compileFile(filePath, libraries, preamble) {
41
72
  ({ kScript, inputStream } = ((args) => {
42
73
  try {
43
74
  if (args.includes("-h") || args.includes("--help")) {
44
- usage();
75
+ usage(console.log);
45
76
  return exit(0);
46
77
  }
47
78
 
@@ -53,9 +84,18 @@ function compileFile(filePath, libraries, preamble) {
53
84
  args.shift();
54
85
  const libPath = args.shift();
55
86
  if (!libPath) throw new Error("--lib requires a file argument");
56
- if (libraries.length > 0) throw new Error("--lib may be specified at most once");
57
- const libBuffer = fs.readFileSync(libPath);
58
- libraries.push(loadLibrary(decodeObject(libBuffer)));
87
+ if (libraries.length > 0) {
88
+ throw new Error("--lib may be specified at most once");
89
+ }
90
+ if (libPath.endsWith(".k")) {
91
+ const raw = fs.readFileSync(libPath, "utf8");
92
+ libraries.push(
93
+ loadLibrary(compileLibrary(raw, { source: libPath }))
94
+ );
95
+ } else {
96
+ const libBuffer = fs.readFileSync(libPath);
97
+ libraries.push(loadLibrary(decodeObject(libBuffer)));
98
+ }
59
99
  } else if (args[0] === "--export") {
60
100
  args.shift();
61
101
  const spec = args.shift();
package/kir.mjs CHANGED
@@ -601,20 +601,27 @@ export default {
601
601
  };
602
602
 
603
603
  function helpText() {
604
+ const prog = argv[1] || "kir.mjs";
604
605
  return [
605
606
  "Export the KIR-P JSON view from a k .ko or .klib object.",
606
607
  "",
607
- `Usage: ${argv[1]} [options] [object-file]`,
608
+ `Usage: ${prog} [options] [object-file]`,
608
609
  "",
609
610
  "Arguments:",
610
- " object-file Input .ko or .klib file. Reads from stdin when omitted.",
611
+ " object-file Input .ko or .klib file (default: stdin).",
611
612
  "",
612
613
  "Options:",
614
+ " -o, --output path Specify output file path explicitly.",
613
615
  " --retype rel Export retyped KIR-P for relation rel.",
614
- " --input-pattern json Input pattern property-list JSON, or a file containing it.",
615
- " -h, --help Show this help.",
616
+ " --input-pattern json Input pattern JSON or file for spec.",
617
+ " -h, --help Show this help.",
616
618
  "",
617
- "KIR-P is an inspection/export view; retyping also emits KIR-P."
619
+ "KIR-P is an inspection/export view; retyping also emits KIR-P.",
620
+ "",
621
+ "Examples:",
622
+ ` ${prog} program.ko`,
623
+ ` ${prog} program.ko -o program.kir.json`,
624
+ ` ${prog} --retype main --input-pattern pattern.json program.ko`
618
625
  ].join("\n");
619
626
  }
620
627
 
@@ -643,32 +650,64 @@ async function main() {
643
650
 
644
651
  let retypeRelation = null;
645
652
  let inputPatternArg = null;
646
- while (args.length > 0 && args[0].startsWith("--")) {
647
- const option = args.shift();
648
- if (option === "--retype") {
653
+ let explicitOutput = null;
654
+ const remainingArgs = [];
655
+ while (args.length > 0) {
656
+ const arg = args[0];
657
+ if (arg === "-o" || arg === "--output") {
658
+ args.shift();
659
+ explicitOutput = args.shift();
660
+ if (!explicitOutput) {
661
+ throw new Error("-o/--output requires a file argument");
662
+ }
663
+ } else if (arg === "--retype") {
664
+ args.shift();
649
665
  retypeRelation = args.shift();
650
666
  if (!retypeRelation) throw new Error("--retype requires a relation name");
651
- } else if (option === "--input-pattern") {
667
+ } else if (arg === "--input-pattern") {
668
+ args.shift();
652
669
  inputPatternArg = args.shift();
653
- if (!inputPatternArg) throw new Error("--input-pattern requires JSON or a file path");
670
+ if (!inputPatternArg) {
671
+ throw new Error("--input-pattern requires JSON or a file path");
672
+ }
673
+ } else if (arg.startsWith("-")) {
674
+ throw new Error(`Unknown option: ${arg}`);
654
675
  } else {
655
- throw new Error(`Unknown option: ${option}`);
676
+ remainingArgs.push(args.shift());
656
677
  }
657
678
  }
658
679
 
659
- const inputPath = args.shift() || null;
660
- if (args.length > 0) {
661
- throw new Error(`Unexpected argument: ${args[0]}`);
680
+ const inputPath = remainingArgs.shift() || null;
681
+ if (remainingArgs.length > 0) {
682
+ throw new Error(`Unexpected argument: ${remainingArgs[0]}`);
662
683
  }
663
684
 
664
- const buffer = inputPath == null ? await readStdinBytes() : fs.readFileSync(inputPath);
685
+ const buffer = inputPath == null
686
+ ? await readStdinBytes()
687
+ : fs.readFileSync(inputPath);
665
688
  const object = decodeObject(buffer);
689
+ let outputData;
666
690
  if (retypeRelation != null) {
667
- if (inputPatternArg == null) throw new Error("--retype requires --input-pattern");
668
- const inputPatternText = fs.existsSync(inputPatternArg) ? fs.readFileSync(inputPatternArg, "utf8") : inputPatternArg;
669
- stdout.write(JSON.stringify(retypeObjectRelation(object, retypeRelation, JSON.parse(inputPatternText)), null, 2) + "\n");
691
+ if (inputPatternArg == null) {
692
+ throw new Error("--retype requires --input-pattern");
693
+ }
694
+ const inputPatternText = fs.existsSync(inputPatternArg)
695
+ ? fs.readFileSync(inputPatternArg, "utf8")
696
+ : inputPatternArg;
697
+ outputData = retypeObjectRelation(
698
+ object,
699
+ retypeRelation,
700
+ JSON.parse(inputPatternText)
701
+ );
702
+ } else {
703
+ outputData = objectToKIRP(object);
704
+ }
705
+
706
+ const json = JSON.stringify(outputData, null, 2) + "\n";
707
+ if (explicitOutput) {
708
+ fs.writeFileSync(explicitOutput, json, "utf8");
670
709
  } else {
671
- stdout.write(JSON.stringify(objectToKIRP(object), null, 2) + "\n");
710
+ stdout.write(json);
672
711
  }
673
712
  }
674
713
 
package/kvm.mjs CHANGED
@@ -9,7 +9,12 @@ import {
9
9
  } from "./run.mjs";
10
10
  import { decodeWire, encodeToWire } from "./codecs/runtime/prefix-codec.mjs";
11
11
  import { intersectPropertyListPatterns } from "./codecs/runtime/codec.mjs";
12
- import { compileObjectBuffer, decodeObject, loadLibrary } from "./object.mjs";
12
+ import {
13
+ compileLibrary,
14
+ compileObjectBuffer,
15
+ decodeObject,
16
+ loadLibrary
17
+ } from "./object.mjs";
13
18
  import codes from "./codes.mjs";
14
19
  import { isMainEntrypoint } from "./codecs/runtime/cli-entry.mjs";
15
20
  import { isIntrinsic, unsupportedIntrinsic } from "./intrinsics.mjs";
@@ -964,20 +969,43 @@ export default {
964
969
  specializeKVM
965
970
  };
966
971
 
967
- function usage() {
972
+ function helpText() {
968
973
  const prog = argv[1] || "kvm.mjs";
969
- console.error(`Usage: node ${prog} [ options ] ( k-expr | input-file ) [ input-file ]`);
970
- console.error("Options:");
971
- console.error(" --lib file Load one .klib dependency before compiling.");
972
- console.error(" --export spec Export a library alias into scope. 'name' or 'libname:localname'. May be repeated.");
973
- console.error(" --envelope-free Run the interpreter in envelope-free mode.");
974
- console.error(" -h, --help Show this help.");
974
+ return [
975
+ "Execute a k expression or file via the kVM bytecode interpreter",
976
+ "over a binary pattern+value wire stream.",
977
+ "",
978
+ `Usage: ${prog} [options]`,
979
+ " ( source-snippet | input-file ) [ input-wire-file ]",
980
+ "",
981
+ "Arguments:",
982
+ " source-snippet Inline k source snippet.",
983
+ " input-file Source .k, .ko, or .klib file.",
984
+ " input-wire-file Optional binary wire input (default: stdin).",
985
+ "",
986
+ "Options:",
987
+ " --lib file Load one .klib or .k library before compiling.",
988
+ " --export spec Export library alias into scope. Repeatable.",
989
+ " spec is 'name' or 'libname:localname'.",
990
+ " --envelope-free Run the interpreter in envelope-free mode.",
991
+ " -h, --help Show this help.",
992
+ "",
993
+ "Examples:",
994
+ ` echo '"abc"' | k-parse | ${prog} '{.1 0}' | k-print`,
995
+ ` echo '{"x":1,"y":2}' | k-json --parse | \\`,
996
+ ` ${prog} --lib Examples/poly.k --export concat \\`,
997
+ ` 's={()xs,()ys}concat; s' | k-json --print`
998
+ ].join("\n");
999
+ }
1000
+
1001
+ function usage(stream = console.error) {
1002
+ stream(helpText());
975
1003
  }
976
1004
 
977
1005
  async function main() {
978
1006
  const args = argv.slice(2);
979
1007
  if (args.includes("-h") || args.includes("--help")) {
980
- usage();
1008
+ usage(console.log);
981
1009
  return exit(0);
982
1010
  }
983
1011
 
@@ -994,9 +1022,18 @@ async function main() {
994
1022
  args.shift();
995
1023
  const libPath = args.shift();
996
1024
  if (!libPath) throw new Error("--lib requires a file argument");
997
- if (libraries.length > 0) throw new Error("--lib may be specified at most once");
998
- const libBuffer = fs.readFileSync(libPath);
999
- libraries.push(loadLibrary(decodeObject(libBuffer)));
1025
+ if (libraries.length > 0) {
1026
+ throw new Error("--lib may be specified at most once");
1027
+ }
1028
+ if (libPath.endsWith(".k")) {
1029
+ const raw = fs.readFileSync(libPath, "utf8");
1030
+ libraries.push(
1031
+ loadLibrary(compileLibrary(raw, { source: libPath }))
1032
+ );
1033
+ } else {
1034
+ const libBuffer = fs.readFileSync(libPath);
1035
+ libraries.push(loadLibrary(decodeObject(libBuffer)));
1036
+ }
1000
1037
  } else if (args[0] === "--export") {
1001
1038
  args.shift();
1002
1039
  const spec = args.shift();
@@ -13,38 +13,43 @@ import {
13
13
  import { objectToKVMArtifact } from "../kvm.mjs";
14
14
 
15
15
  function helpText() {
16
+ const prog = argv[1] || "compile.mjs";
16
17
  return [
17
- "Compile a k source, .ko, or .klib into .ko, .klib, or .kvm output.",
18
- "Output format is inferred from the output file extension, or from --format.",
18
+ "Compile k source, .ko, or .klib into .ko, .klib, or .kvm output.",
19
+ "Output format is inferred from the output extension or --format.",
19
20
  "",
20
- `Usage: ${argv[1]} [options] [source-snippet | input-file [output-file]]`,
21
+ `Usage: ${prog} [options]`,
22
+ " [source-snippet | input-file [output-file]]",
21
23
  "",
22
24
  "Arguments:",
23
- " source-snippet Inline k source, in the same style as k.mjs.",
24
- " input-file Source .k, .ko, or .klib file. Reads UTF-8 source from stdin when omitted.",
25
- " output-file Output path (.ko, .klib, or .kvm). Writes to stdout when omitted.",
25
+ " source-snippet Inline k source, in the same style as k.mjs.",
26
+ " input-file Source .k, .ko, or .klib file.",
27
+ " Reads UTF-8 source from stdin when omitted.",
28
+ " output-file Output path (.ko, .klib, or .kvm).",
29
+ " Writes to stdout when omitted.",
26
30
  "",
27
31
  "Options:",
28
- " --lib file Load one .klib or .k library dependency before compiling.",
29
- " --export spec Export a library alias into the source scope. May be repeated.",
30
- " spec is 'name' or 'libname:localname'.",
31
- " --format fmt Output format: ko, klib, or kvm. Overrides extension detection.",
32
- " -h, --help Show this help.",
32
+ " -o, --output path Specify output file path explicitly.",
33
+ " --format fmt Output format: ko, klib, or kvm.",
34
+ " Overrides extension detection.",
35
+ " --lib file Load one .klib or .k library before compiling.",
36
+ " --export spec Export library alias into scope. Repeatable.",
37
+ " spec is 'name' or 'libname:localname'.",
38
+ " -h, --help Show this help.",
33
39
  "",
34
- "Existing input paths are read as files. A non-existing input with .k, .ko,",
35
- "or .klib extension is reported as a missing file; otherwise it is compiled",
36
- "as inline k source.",
40
+ "Existing input paths are read as files. A non-existing input with",
41
+ ".k, .ko, or .klib extension is reported as missing; otherwise it is",
42
+ "compiled as inline k source.",
37
43
  "",
38
44
  ".kvm is a polymorphic kVM template artifact (layer: KVM-P).",
39
45
  "A .klib input can only be copied to .klib output.",
40
46
  "",
41
47
  "Examples:",
42
- ` ${argv[1]} 'x = |x; x x'`,
43
- ` ${argv[1]} program.k program.ko`,
44
- ` ${argv[1]} program.k program.klib`,
45
- ` ${argv[1]} program.k program.kvm`,
46
- ` ${argv[1]} --lib Examples/arithmetics.k --export plus:+ --export succ --export int '{succ int x,int y}+' a.kvm`,
47
- ` ${argv[1]} --lib core.klib --export add --export mul:times program.k program.ko`
48
+ ` ${prog} 'x = |x; x x'`,
49
+ ` ${prog} program.k -o program.ko`,
50
+ ` ${prog} program.k program.klib`,
51
+ ` ${prog} program.k program.kvm`,
52
+ ` ${prog} --lib core.klib --export add program.k program.ko`
48
53
  ].join("\n");
49
54
  }
50
55
 
@@ -144,6 +149,7 @@ try {
144
149
 
145
150
  const libraries = [];
146
151
  let format = null;
152
+ let explicitOutput = null;
147
153
  const exports = [];
148
154
 
149
155
  while (args.length > 0) {
@@ -151,7 +157,13 @@ try {
151
157
  args.shift();
152
158
  break;
153
159
  }
154
- if (args[0] === "--lib") {
160
+ if (args[0] === "-o" || args[0] === "--output") {
161
+ args.shift();
162
+ explicitOutput = args.shift();
163
+ if (!explicitOutput) {
164
+ throw new Error("-o/--output requires a file argument");
165
+ }
166
+ } else if (args[0] === "--lib") {
155
167
  args.shift();
156
168
  const libPath = args.shift();
157
169
  if (!libPath) throw new Error("--lib requires a file argument");
@@ -172,7 +184,7 @@ try {
172
184
  format = args.shift();
173
185
  if (!["ko", "klib", "kvm"].includes(format))
174
186
  throw new Error(`Unknown format: ${format}. Use ko, klib, or kvm.`);
175
- } else if (args[0].startsWith("--")) {
187
+ } else if (args[0].startsWith("-")) {
176
188
  throw new Error(`Unknown option: ${args[0]}`);
177
189
  } else {
178
190
  break;
@@ -180,11 +192,13 @@ try {
180
192
  }
181
193
 
182
194
  const inputArg = args.shift() || null;
183
- const outputPath = args.shift() || null;
195
+ const positionalOutput = args.shift() || null;
184
196
  if (args.length > 0) {
185
197
  throw new Error(`Unexpected argument: ${args[0]}`);
186
198
  }
187
199
 
200
+ const outputPath = explicitOutput || positionalOutput || null;
201
+
188
202
  const outputFormat = format || inferFormat(outputPath);
189
203
  const input = resolveInput(inputArg);
190
204
  const inputType = input.type;
@@ -5,20 +5,24 @@ import { argv, exit, stdin, stdout } from "node:process";
5
5
  import { decompileObjectBuffer } from "../object.mjs";
6
6
 
7
7
  function helpText() {
8
+ const prog = argv[1] || "decompile.mjs";
8
9
  return [
9
10
  "Decompile a .ko or .klib object into readable k source.",
10
11
  "",
11
- `Usage: ${argv[1]} [ object-file [ k-file ] ]`,
12
+ `Usage: ${prog} [options] [ object-file [ k-file ] ]`,
12
13
  "",
13
14
  "Arguments:",
14
- " object-file Input .ko or .klib path. Reads object data from stdin when omitted.",
15
- " k-file Output .k path. Writes source to stdout when omitted.",
15
+ " object-file Input .ko or .klib path.",
16
+ " Reads object data from stdin when omitted.",
17
+ " k-file Output .k path (default: stdout).",
16
18
  "",
17
19
  "Options:",
18
- " -h, --help Show this help.",
20
+ " -o, --output path Specify output file path explicitly.",
21
+ " -h, --help Show this help.",
19
22
  "",
20
- "Example:",
21
- ` ${argv[1]} program.ko program.decompiled.k`
23
+ "Examples:",
24
+ ` ${prog} program.ko -o program.decompiled.k`,
25
+ ` ${prog} program.ko program.decompiled.k`
22
26
  ].join("\n");
23
27
  }
24
28
 
@@ -35,13 +39,39 @@ async function readStdinBuffer() {
35
39
  }
36
40
 
37
41
  try {
38
- const [, , objectPath, outputPath] = argv;
39
- if (objectPath === "-h" || objectPath === "--help") {
42
+ const rawArgs = argv.slice(2);
43
+ if (rawArgs.includes("-h") || rawArgs.includes("--help")) {
40
44
  usage(console.log);
41
45
  exit(0);
42
46
  }
43
47
 
44
- const objectBuffer = objectPath == null ? await readStdinBuffer() : fs.readFileSync(objectPath);
48
+ let explicitOutput = null;
49
+ const remainingArgs = [];
50
+ while (rawArgs.length > 0) {
51
+ const arg = rawArgs[0];
52
+ if (arg === "-o" || arg === "--output") {
53
+ rawArgs.shift();
54
+ explicitOutput = rawArgs.shift();
55
+ if (!explicitOutput) {
56
+ throw new Error("-o/--output requires a file argument");
57
+ }
58
+ } else if (arg.startsWith("-")) {
59
+ throw new Error(`Unknown option: ${arg}`);
60
+ } else {
61
+ remainingArgs.push(rawArgs.shift());
62
+ }
63
+ }
64
+
65
+ const objectPath = remainingArgs.shift() || null;
66
+ const positionalOutput = remainingArgs.shift() || null;
67
+ if (remainingArgs.length > 0) {
68
+ throw new Error(`Unexpected argument: ${remainingArgs[0]}`);
69
+ }
70
+ const outputPath = explicitOutput || positionalOutput || null;
71
+
72
+ const objectBuffer = objectPath == null
73
+ ? await readStdinBuffer()
74
+ : fs.readFileSync(objectPath);
45
75
  const source = decompileObjectBuffer(objectBuffer);
46
76
  if (outputPath == null) {
47
77
  stdout.write(source);
@@ -49,7 +79,7 @@ try {
49
79
  fs.writeFileSync(outputPath, source);
50
80
  }
51
81
  } catch (error) {
52
- console.error(error);
82
+ console.error(error.message || String(error));
53
83
  usage();
54
84
  exit(1);
55
85
  }
@@ -5,24 +5,28 @@ import { argv, exit, stdin, stdout } from "node:process";
5
5
  import { extractAliasesFromObjectBuffer } from "../object.mjs";
6
6
 
7
7
  function helpText() {
8
+ const prog = argv[1] || "extract-aliases.mjs";
8
9
  return [
9
- "Extract metadata aliases from a .ko or .klib as a valid k source snippet.",
10
+ "Extract metadata aliases from a .ko or .klib as valid k source.",
10
11
  "",
11
- `Usage: ${argv[1]} [ object-file [ k-file ] ]`,
12
+ `Usage: ${prog} [options] [ object-file [ k-file ] ]`,
12
13
  "",
13
- "Output is grouped by metadata type (code, then rel), then sorted by alias",
14
- "name and compiledAt. Earlier definitions of the same alias are commented",
15
- "out so only the latest one remains active.",
14
+ "Output is grouped by metadata type (code, then rel), then sorted",
15
+ "by alias name and compiledAt. Earlier definitions of the same alias",
16
+ "are commented out so only the latest one remains active.",
16
17
  "",
17
18
  "Arguments:",
18
- " object-file Input .ko or .klib path. Reads object data from stdin when omitted.",
19
- " k-file Output .k path. Writes source to stdout when omitted.",
19
+ " object-file Input .ko or .klib path.",
20
+ " Reads object data from stdin when omitted.",
21
+ " k-file Output .k path (default: stdout).",
20
22
  "",
21
23
  "Options:",
22
- " -h, --help Show this help.",
24
+ " -o, --output path Specify output file path explicitly.",
25
+ " -h, --help Show this help.",
23
26
  "",
24
- "Example:",
25
- ` ${argv[1]} core.klib aliases.k`
27
+ "Examples:",
28
+ ` ${prog} core.klib -o aliases.k`,
29
+ ` ${prog} core.klib aliases.k`
26
30
  ].join("\n");
27
31
  }
28
32
 
@@ -39,13 +43,39 @@ async function readStdinBuffer() {
39
43
  }
40
44
 
41
45
  try {
42
- const [, , objectPath, outputPath] = argv;
43
- if (objectPath === "-h" || objectPath === "--help") {
46
+ const rawArgs = argv.slice(2);
47
+ if (rawArgs.includes("-h") || rawArgs.includes("--help")) {
44
48
  usage(console.log);
45
49
  exit(0);
46
50
  }
47
51
 
48
- const objectBuffer = objectPath == null ? await readStdinBuffer() : fs.readFileSync(objectPath);
52
+ let explicitOutput = null;
53
+ const remainingArgs = [];
54
+ while (rawArgs.length > 0) {
55
+ const arg = rawArgs[0];
56
+ if (arg === "-o" || arg === "--output") {
57
+ rawArgs.shift();
58
+ explicitOutput = rawArgs.shift();
59
+ if (!explicitOutput) {
60
+ throw new Error("-o/--output requires a file argument");
61
+ }
62
+ } else if (arg.startsWith("-")) {
63
+ throw new Error(`Unknown option: ${arg}`);
64
+ } else {
65
+ remainingArgs.push(rawArgs.shift());
66
+ }
67
+ }
68
+
69
+ const objectPath = remainingArgs.shift() || null;
70
+ const positionalOutput = remainingArgs.shift() || null;
71
+ if (remainingArgs.length > 0) {
72
+ throw new Error(`Unexpected argument: ${remainingArgs[0]}`);
73
+ }
74
+ const outputPath = explicitOutput || positionalOutput || null;
75
+
76
+ const objectBuffer = objectPath == null
77
+ ? await readStdinBuffer()
78
+ : fs.readFileSync(objectPath);
49
79
  const source = extractAliasesFromObjectBuffer(objectBuffer);
50
80
  if (outputPath == null) {
51
81
  stdout.write(source);
@@ -53,7 +83,7 @@ try {
53
83
  fs.writeFileSync(outputPath, source);
54
84
  }
55
85
  } catch (error) {
56
- console.error(error);
86
+ console.error(error.message || String(error));
57
87
  usage();
58
88
  exit(1);
59
89
  }