@fraczak/k 6.0.0 → 6.0.2

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 (40) hide show
  1. package/.codex +0 -0
  2. package/AGENTS.md +35 -0
  3. package/CHANGELOG.md +48 -0
  4. package/CLAUDE.md +64 -0
  5. package/DOCS/BIG_PICTURE.md +4 -8
  6. package/DOCS/BINARY_CODEC_STATUS_AND_TODO.md +74 -0
  7. package/DOCS/CONVERGENCE.md +92 -0
  8. package/DOCS/DIVERGENCE_DETECTION.md +24 -0
  9. package/DOCS/Makefile +99 -0
  10. package/DOCS/OBJECT_FILE_AND_PATTERN.md +217 -0
  11. package/DOCS/PATTERNS.md +114 -0
  12. package/DOCS/PATTERNS_AND_TYPED_VALUES.md +665 -0
  13. package/DOCS/REPL.md +125 -125
  14. package/DOCS/TEXTUAL_VALUES.md +108 -0
  15. package/DOCS/TYPE_DERIVATION.md +230 -0
  16. package/DOCS/a.html +398 -0
  17. package/DOCS/book/06-values-in-memory.md +1085 -0
  18. package/DOCS/book/07-the-partial-function-abi.md +143 -0
  19. package/DOCS/book/08-operational-semantics-and-execution.md +201 -0
  20. package/DOCS/book/09-compiler-architecture.md +160 -0
  21. package/DOCS/book/10-from-ast-to-intermediate-representation.md +167 -0
  22. package/DOCS/book/14-canonical-serialization.md +176 -0
  23. package/DOCS/book/appendix-b-incorporating-external-predefined-types-and-functions.md +155 -0
  24. package/DOCS/book/overview.txt +68 -0
  25. package/NAT.k~ +452 -0
  26. package/README.md +71 -27
  27. package/codecs/BINARY_FORMAT.html +471 -0
  28. package/codecs/POLYMORPHIC_BINARY_FORMAT.html +355 -0
  29. package/codecs/README.md +8 -0
  30. package/codecs/pandoc.css +71 -0
  31. package/codecs/runtime/test-codec.mjs +89 -0
  32. package/ieee.klib +0 -0
  33. package/k-vscode/package-lock.json +4176 -0
  34. package/package.json +10 -13
  35. package/{codecs/k-pattern.mjs → patterns/from-k.mjs} +3 -3
  36. package/repl2.mjs +270 -51
  37. package/scripts/generate-dependency-graph.mjs +121 -0
  38. package/test-repl2.mjs +67 -9
  39. package/type_registry/registry.mjs~ +105 -0
  40. package/type_registry/typeParser.jison~ +132 -0
package/test-repl2.mjs CHANGED
@@ -2,8 +2,20 @@ import assert from "node:assert";
2
2
  import fs from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
-
6
- import { completeInput, createState, evaluateInput } from "./repl2.mjs";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ import {
8
+ aliasNames,
9
+ analyzeAcceptedSnippet,
10
+ analyzeRawSnippet,
11
+ completeInput,
12
+ createState,
13
+ evaluateInput,
14
+ explicitSnippetTerminated,
15
+ isMainEntrypoint,
16
+ lineHasExplicitContinuation,
17
+ lineTerminatesSnippet
18
+ } from "./repl2.mjs";
7
19
  import { decodeObject, objectToFunction } from "./object.mjs";
8
20
  import { Product } from "./Value.mjs";
9
21
 
@@ -40,11 +52,38 @@ assert(completions.some((line) => line.endsWith(state.typeAliases.nat)));
40
52
  completions = completeInput(`(${canonicalPartial}`, state)[0];
41
53
  assert(completions.includes(`(${state.typeAliases.nat}`));
42
54
 
55
+ completions = completeInput(":run su", state)[0];
56
+ assert(completions.includes(":run succ"));
57
+
58
+ completions = completeInput("$na", state)[0];
59
+ assert(completions.includes("$nat"));
60
+
61
+ assert.deepEqual(aliasNames(state), ["nat", "succ"]);
62
+ assert.equal(lineTerminatesSnippet(";"), true);
63
+ assert.equal(lineTerminatesSnippet(" ; "), true);
64
+ assert.equal(lineTerminatesSnippet(" ; -- comment"), false);
65
+ assert.equal(lineTerminatesSnippet("succ"), false);
66
+ assert.equal(explicitSnippetTerminated("$ bool = <{} true, {} false>;"), true);
67
+ assert.equal(lineHasExplicitContinuation("succ \\"), true);
68
+ assert.equal(analyzeRawSnippet("$ bool = <{} true, {} false>").kind, "incomplete");
69
+ assert.equal(analyzeAcceptedSnippet("$ bool = <{} true, {} false>;", true).kind, "definitionsOnly");
70
+ assert.equal(analyzeRawSnippet("a =").kind, "incomplete");
71
+ assert.equal(analyzeRawSnippet("{} | succ").kind, "withMain");
72
+
73
+ const offsetState = createState();
74
+ await evaluateInput(":type ab = <{} 1, {} 2>", offsetState);
75
+ await evaluateInput(":type bool = <{} true, {} false>", offsetState);
76
+ await assert.rejects(
77
+ () => evaluateInput("$ab", offsetState),
78
+ /Type Error in 'filter' \(lines 1:1\.\.\.1:4\)/
79
+ );
80
+
43
81
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "k-repl2-"));
44
82
  const libPath = path.join(tmpDir, "session.klib");
45
83
  const koPath = path.join(tmpDir, "succ.ko");
46
84
  const sourcePath = path.join(tmpDir, "session.k");
47
- output = await evaluateInput(`:save ${libPath}`, state);
85
+ const symlinkPath = path.resolve(".test-k-repl2-link");
86
+ output = await evaluateInput(`:klib ${libPath}`, state);
48
87
  assert.equal(output[0], `saved ${libPath}`);
49
88
 
50
89
  completions = completeInput(`:load ${tmpDir}/ses`, state)[0];
@@ -65,6 +104,14 @@ assert.match(output[0], /^nat = @/m);
65
104
  output = await evaluateInput(":rels", loadedSource);
66
105
  assert.match(output[0], /^succ = @/m);
67
106
 
107
+ const replPath = fileURLToPath(new URL("./repl2.mjs", import.meta.url));
108
+ try {
109
+ fs.rmSync(symlinkPath, { force: true });
110
+ } catch {}
111
+ fs.symlinkSync(replPath, symlinkPath);
112
+ fs.chmodSync(replPath, 0o755);
113
+ assert.equal(isMainEntrypoint(symlinkPath), true);
114
+
68
115
  const reloaded = createState();
69
116
  output = await evaluateInput(`:load ${libPath}`, reloaded);
70
117
  assert.equal(output[0], `loaded ${libPath}`);
@@ -79,12 +126,22 @@ output = await evaluateInput("succ", reloaded);
79
126
  assert.equal(output[0], "{}|succ ?<{} succ, ...>");
80
127
 
81
128
  const shorthand = createState();
82
- output = await evaluateInput("$ nat = <{} zero, nat succ>;", shorthand);
83
- assert.match(output[0], /^\$ nat = @/);
84
- output = await evaluateInput("succ = |succ;", shorthand);
85
- assert.match(output[0], /^succ = @/);
86
- output = await evaluateInput("succ", shorthand);
87
- assert.equal(output[0], "{}|succ ?<{} succ, ...>");
129
+ output = await evaluateInput("$ nat = <{} zero, nat succ>\n; succ = |succ\n;", shorthand);
130
+ assert.deepEqual(output, []);
131
+ output = await evaluateInput(":codes", shorthand);
132
+ assert.match(output[0], /^nat = @/m);
133
+ output = await evaluateInput(":rels", shorthand);
134
+ assert.match(output[0], /^succ = @/m);
135
+ output = await evaluateInput("$ bool = <{} true, {} false>\n; not = $bool </true | false, {} | true >\n; {} | true not", shorthand);
136
+ assert.match(output[0], /^\{\}\|false \?</);
137
+ assert.match(output[0], / false/);
138
+ assert.match(output[0], / true/);
139
+ output = await evaluateInput("$ maybe = <{} none, {} some>;", shorthand);
140
+ assert.deepEqual(output, []);
141
+ output = await evaluateInput(":codes", shorthand);
142
+ assert.match(output[0], /^maybe = @/m);
143
+ output = await evaluateInput("{} | true not", shorthand);
144
+ assert.match(output[0], /^\{\}\|false \?</);
88
145
 
89
146
  await assert.rejects(
90
147
  () => evaluateInput("/type", createState()),
@@ -92,4 +149,5 @@ await assert.rejects(
92
149
  );
93
150
 
94
151
  fs.rmSync(tmpDir, { recursive: true, force: true });
152
+ fs.rmSync(symlinkPath, { force: true });
95
153
  console.log("OK");
@@ -0,0 +1,105 @@
1
+ import http from 'http';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { fileURLToPath } from 'url';
5
+ import codes from '../codes.mjs';
6
+ import { parse } from './typeParser.mjs';
7
+
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const REGISTRY_FILE = path.join(__dirname, 'registry.json');
10
+ const PORT = 3001;
11
+
12
+ // Load existing registry if it exists
13
+ if (fs.existsSync(REGISTRY_FILE)) {
14
+ console.log('Loading existing registry...');
15
+ try {
16
+ const data = fs.readFileSync(REGISTRY_FILE, 'utf8');
17
+ const json = JSON.parse(data);
18
+ codes.load(json);
19
+ console.log(`Loaded ${Object.keys(json).length} types.`);
20
+ } catch (err) {
21
+ console.error('Error loading registry:', err);
22
+ }
23
+ } else {
24
+ console.log('No existing registry found. Starting fresh.');
25
+ }
26
+
27
+ const server = http.createServer((req, res) => {
28
+ // Helper to send JSON response
29
+ const sendJSON = (data, status = 200) => {
30
+ res.writeHead(status, { 'Content-Type': 'application/json' });
31
+ res.end(JSON.stringify(data));
32
+ };
33
+
34
+ // Helper to send Error
35
+ const sendError = (message, status = 400) => {
36
+ res.writeHead(status, { 'Content-Type': 'application/json' });
37
+ res.end(JSON.stringify({ error: message }));
38
+ };
39
+
40
+ // Route: POST
41
+ if (req.method === 'POST') {
42
+ let body = '';
43
+ req.on('data', chunk => {
44
+ body += chunk.toString();
45
+ });
46
+ req.on('end', () => {
47
+ try {
48
+ // 1. Parse the input string using the Jison parser
49
+ // The parser expects a string of type definitions
50
+ console.log("Received body:", body);
51
+ const definitions = parse(body);
52
+ console.log("Parsed definitions:", JSON.stringify(definitions, null, 2));
53
+
54
+ // 2. Register the parsed codes
55
+ // codes.register returns the representatives map { temp_name: canonical_hash }
56
+ const representatives = codes.register(definitions);
57
+
58
+ // Filter out generated names (_gen_...) and canonical names (@...)
59
+ const filteredRepresentatives = Object.fromEntries(
60
+ Object.entries(representatives).filter(([key, value]) =>
61
+ !key.startsWith('_gen_') && !key.startsWith('@')
62
+ )
63
+ );
64
+
65
+ // 3. Save to disk
66
+ const dump = codes.dump();
67
+ fs.writeFileSync(REGISTRY_FILE, JSON.stringify(dump, null, 2));
68
+
69
+ // 4. Return the mapping
70
+ sendJSON(filteredRepresentatives);
71
+
72
+ } catch (err) {
73
+ console.error(err);
74
+ sendError(`Registration failed: ${err.message}`);
75
+ }
76
+ });
77
+ }
78
+ // Route: GET
79
+ else if (req.method === 'GET') {
80
+ const typeId = req.url.split('/').pop();
81
+ console.log("Requested type ID:", typeId);
82
+ if (!typeId) {
83
+ sendError('Missing type ID');
84
+ return;
85
+ }
86
+ // Decode URI component in case @ is encoded
87
+ const decodedId = decodeURIComponent(typeId);
88
+ console.log("Decoded type ID:", decodedId);
89
+
90
+ const typeDef = codes.find(decodedId);
91
+ if (typeDef.code === 'undefined') {
92
+ sendError('Type not found', 404);
93
+ } else {
94
+ sendJSON(typeDef);
95
+ }
96
+ }
97
+ // 404 Not Found
98
+ else {
99
+ sendError('Not Found', 404);
100
+ }
101
+ });
102
+
103
+ server.listen(PORT, () => {
104
+ console.log(`Type Registry running at http://localhost:${PORT}/`);
105
+ });
@@ -0,0 +1,132 @@
1
+ %{
2
+
3
+ let defs = {};
4
+ let genCount = 0;
5
+ let genNameId;
6
+
7
+ function genName() {
8
+ return `_gen_${genCount++}`;
9
+ }
10
+
11
+ function fromEscString(escString) {
12
+ const isSingleQuoted = escString.startsWith("'");
13
+ let str = escString.substring(1, escString.length - 1);
14
+ if (isSingleQuoted) {
15
+ str = str.replace(/\\'/g, "'");
16
+ } else {
17
+ str = str.replace(/\\"/g, '"');
18
+ }
19
+ str = str.replace(/\\\\/g, '\\');
20
+ str = str.replace(/\\\//g, '/');
21
+ str = str.replace(/\\b/g, '\b');
22
+ str = str.replace(/\\f/g, '\f');
23
+ str = str.replace(/\\n/g, '\n');
24
+ str = str.replace(/\\r/g, '\r');
25
+ str = str.replace(/\\t/g, '\t');
26
+ str = str.replace(/\\u([\dA-F]{4})/gi, (match, p1) => String.fromCharCode(parseInt(p1, 16)));
27
+
28
+ return str;
29
+ }
30
+
31
+ %}
32
+
33
+ %lex
34
+
35
+ %%
36
+ \s+ /* blanks */
37
+ "<" return 'LA';
38
+ ">" return 'RA';
39
+ "{" return 'LC';
40
+ "}" return 'RC';
41
+ "=" return 'EQ';
42
+ "," return 'COMMA';
43
+ ";" return 'SC';
44
+ "@" return 'AT';
45
+ "$" return 'DOLLAR';
46
+ \"([^"\\]|\\(.|\n))*\"|\'([^'\\]|\\(.|\n))*\' return 'STRING';
47
+ [a-zA-Z0-9_+-][a-zA-Z0-9_?!+-]* return 'NAME';
48
+ <<EOF>> return 'EOF';
49
+ . return 'INVALID';
50
+
51
+ /lex
52
+
53
+ %token NAME STRING
54
+ %token LA RA LC RC EQ COMMA SC AT DOLLAR
55
+ %token EOF
56
+
57
+ %start expressions
58
+
59
+ %%
60
+
61
+ expressions
62
+ : initialize_defs definitions EOF
63
+ { return defs; }
64
+ ;
65
+
66
+ initialize_defs
67
+ : /* empty */
68
+ { defs = {}; genCount = 0; }
69
+ ;
70
+
71
+ definitions
72
+ : definition
73
+ | definitions definition
74
+ ;
75
+
76
+ definition
77
+ : DOLLAR name EQ LA field_list RA SC
78
+ { defs[$2] = { code: 'union', union: $5 }; }
79
+ | DOLLAR name EQ LC field_list RC SC
80
+ { defs[$2] = { code: 'product', product: $5 }; }
81
+ ;
82
+
83
+ type_expr
84
+ : LA field_list RA
85
+ {
86
+ genNameId = genName();
87
+ defs[genNameId] = { code: 'union', union: $2 };
88
+ $$ = genNameId;
89
+ }
90
+ | LC field_list RC
91
+ {
92
+ genNameId = genName();
93
+ defs[genNameId] = { code: 'product', product: $2 };
94
+ $$ = genNameId;
95
+ }
96
+ | ref
97
+ { $$ = $1; }
98
+ ;
99
+
100
+ ref
101
+ : name
102
+ { $$ = $1; }
103
+ | AT name
104
+ { $$ = '@' + $2; }
105
+ ;
106
+
107
+ field_list
108
+ : /* empty */
109
+ { $$ = {}; }
110
+ | field
111
+ { $$ = {}; $$[$1.label] = $1.type; }
112
+ | field_list COMMA field
113
+ { $$ = $1; $$[$3.label] = $3.type; }
114
+ ;
115
+
116
+ field
117
+ : type_expr label
118
+ { $$ = { type: $1, label: $2 }; }
119
+ ;
120
+
121
+ label
122
+ : name
123
+ { $$ = $1; }
124
+ | str
125
+ { $$ = $1; }
126
+ ;
127
+
128
+ name: NAME { $$ = yytext; };
129
+ str: STRING { $$ = fromEscString(yytext); };
130
+
131
+ %%
132
+