@fraczak/k 8.6.1 → 8.7.1
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.
- package/CHANGELOG.md +37 -0
- package/DOCS/CODECS.md +20 -14
- package/DOCS/FILE_FORMATS.md +53 -12
- package/DOCS/GETTING_STARTED.md +15 -8
- package/DOCS/PATTERNS.md +10 -0
- package/DOCS/REPL.md +12 -7
- package/Examples/arithmetics.k +81 -468
- package/Examples/ieee-arithmetics.k +37 -33
- package/Examples/poly.k +107 -104
- package/README.md +19 -11
- package/backend-api.mjs +3 -1
- package/backends/llvm/README.md +1 -1
- package/backends/llvm/bin/k-llvm-build.mjs +5 -5
- package/backends/llvm/bin/k-llvm-compile.mjs +4 -4
- package/backends/llvm/bin/k-llvm.mjs +6 -6
- package/backends/llvm/src/cli.mjs +17 -15
- package/backends/llvm/tests/integration.sh +6 -1
- package/backends/wasm/README.md +3 -3
- package/backends/wasm/bin/k-wasm-compile.mjs +4 -4
- package/backends/wasm/bin/k-wasm.mjs +4 -4
- package/backends/wasm/src/cli.mjs +12 -10
- package/backends/wasm/src/wasm.mjs +4 -4
- package/backends/wasm/tests/integration.sh +24 -4
- package/browser/shims/fs.mjs +19 -3
- package/canonical-pattern.mjs +214 -57
- package/compiler.mjs +26 -0
- package/core.k +2 -1
- package/harness/suites/poly.mjs +14 -30
- package/index.mjs +67 -2
- package/k.mjs +14 -18
- package/kir.mjs +3 -1
- package/kvm.mjs +11 -11
- package/lib/arithmetics.k +286 -0
- package/lib/bit.k +68 -0
- package/lib/bits.k +227 -0
- package/lib/btrie.k +187 -0
- package/lib/djson.k +327 -0
- package/lib/ieee.k +709 -0
- package/lib/list.k +49 -0
- package/lib/string.k +588 -0
- package/named-patterns.mjs +2 -14
- package/object.mjs +32 -7
- package/objects/README.md +9 -3
- package/objects/compile.mjs +11 -14
- package/package.json +1 -1
- package/repl.mjs +24 -5
- package/scripts/benchmark-idempotency.mjs +22 -15
- package/scripts/benchmark.mjs +29 -10
- package/scripts/build-repl-html.mjs +41 -13
- package/scripts/perf-ieee.mjs +9 -1
- package/scripts/perf-int.mjs +10 -17
- package/scripts/perf-multiplication.mjs +9 -15
- package/scripts/perf-poly.mjs +16 -32
- package/scripts/run-tests.mjs +3 -2
- package/scripts/test-package.mjs +13 -2
- package/tests/helpers/cli.mjs +19 -3
- package/tests/integration.sh +25 -5
- package/tests/test-arithmetics.mjs +4 -2
- package/tests/test-djson-methods.mjs +21 -12
- package/tests/test-ieee-arithmetic.mjs +11 -3
- package/tests/test-ieee-text.mjs +19 -4
- package/tests/test-k-object.mjs +15 -4
- package/tests/test-karatsuba.mjs +1 -1
- package/tests/test-kvm-polymorphic.mjs +58 -34
- package/tests/test-lib.mjs +117 -0
- package/tests/test-library-isolation.mjs +381 -0
- package/tests/test-named-patterns.mjs +21 -3
- package/tests/test-parse-json.mjs +44 -14
- package/tests/test-poly.mjs +10 -4
- package/tests/test-repl-html.mjs +18 -7
- package/tests/test-repl.mjs +50 -35
- package/Examples/djson.k +0 -894
- package/Examples/ieee.k +0 -969
- package/Examples/karatsuba-mult.k +0 -227
- package/Examples/list.k +0 -10
package/index.mjs
CHANGED
|
@@ -41,21 +41,86 @@ function annotate(script, options = {}) {
|
|
|
41
41
|
const representatives = codes.register(defs.codes);
|
|
42
42
|
const rels = {...defs.rels, "__main__": {def: exp}};
|
|
43
43
|
|
|
44
|
+
// 1. Inject library patterns into defs.patterns before validation and expansion
|
|
45
|
+
// NOTE: Library patterns are known by their hashes ONLY unless --use is specified.
|
|
46
|
+
if (options.libraries) {
|
|
47
|
+
for (const lib of options.libraries) {
|
|
48
|
+
const libPatterns =
|
|
49
|
+
lib.patterns ||
|
|
50
|
+
lib.defs?.patterns ||
|
|
51
|
+
lib.sourceDefs?.patterns ||
|
|
52
|
+
{};
|
|
53
|
+
for (const [name, pat] of Object.entries(libPatterns)) {
|
|
54
|
+
if (name.startsWith("@") && !(name in (defs.patterns || {}))) {
|
|
55
|
+
if (!defs.patterns) defs.patterns = {};
|
|
56
|
+
defs.patterns[name] = pat;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 2. Handle pattern aliases from useSpecs / use (e.g. float64[]:number[])
|
|
63
|
+
const useSpecs = [...(options.useSpecs || options.use || [])];
|
|
64
|
+
if (options.libraries && useSpecs.length > 0) {
|
|
65
|
+
for (const spec of useSpecs) {
|
|
66
|
+
const parts = spec.trim().split(/[\s,]+/);
|
|
67
|
+
for (const item of parts) {
|
|
68
|
+
if (!item) continue;
|
|
69
|
+
const [rawLib, rawLocal] = item.includes(":") ? item.split(":", 2) : [item, item];
|
|
70
|
+
const libName = rawLib.replace(/\[.*\]$/, "").trim();
|
|
71
|
+
const localName = rawLocal.replace(/\[.*\]$/, "").trim();
|
|
72
|
+
for (const lib of options.libraries) {
|
|
73
|
+
const libPatterns = lib.patterns || lib.defs?.patterns || lib.sourceDefs?.patterns || {};
|
|
74
|
+
const patHash = lib.patternAlias?.[libName] || (libName.startsWith("@") ? libName : null);
|
|
75
|
+
const pat = (patHash && libPatterns[patHash]) || libPatterns[libName];
|
|
76
|
+
if (pat) {
|
|
77
|
+
if (!defs.patterns) defs.patterns = {};
|
|
78
|
+
if (!(localName in defs.patterns)) {
|
|
79
|
+
defs.patterns[localName] = pat;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
44
87
|
validatePatternDefinitions(defs.patterns || {}, options);
|
|
45
88
|
expandPatternsInRels(rels, defs.patterns || {}, options);
|
|
46
89
|
|
|
47
|
-
// Inject library relations into the rels table so @hash refs resolve
|
|
90
|
+
// 3. Inject library relations into the rels table so @hash refs resolve
|
|
91
|
+
// NOTE: Library relations are known by their hashes ONLY unless --use is specified.
|
|
48
92
|
if (options.libraries) {
|
|
49
93
|
for (const lib of options.libraries) {
|
|
50
94
|
const libRels = lib.rels || lib.defs?.rels || {};
|
|
51
95
|
for (const [name, rel] of Object.entries(libRels)) {
|
|
52
|
-
if (!(name in rels)) {
|
|
96
|
+
if (name.startsWith("@") && !(name in rels)) {
|
|
53
97
|
rels[name] = { ...rel, _library: true };
|
|
54
98
|
}
|
|
55
99
|
}
|
|
56
100
|
}
|
|
57
101
|
}
|
|
58
102
|
|
|
103
|
+
// 4. Handle relation aliases from useSpecs / use (e.g. inc:inc_bits)
|
|
104
|
+
if (options.libraries && useSpecs.length > 0) {
|
|
105
|
+
for (const spec of useSpecs) {
|
|
106
|
+
const parts = spec.trim().split(/[\s,]+/);
|
|
107
|
+
for (const item of parts) {
|
|
108
|
+
if (!item) continue;
|
|
109
|
+
const [rawLib, rawLocal] = item.includes(":") ? item.split(":", 2) : [item, item];
|
|
110
|
+
const libName = rawLib.replace(/\[.*\]$/, "").trim();
|
|
111
|
+
const localName = rawLocal.replace(/\[.*\]$/, "").trim();
|
|
112
|
+
for (const lib of options.libraries) {
|
|
113
|
+
const libRels = lib.rels || lib.defs?.rels || {};
|
|
114
|
+
const relHash = lib.relAlias?.[libName] || (libName.startsWith("@") ? libName : null);
|
|
115
|
+
const rel = (relHash && libRels[relHash]) || libRels[libName];
|
|
116
|
+
if (rel && !(localName in rels)) {
|
|
117
|
+
rels[localName] = { ...rel, _library: true };
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
59
124
|
const { relAlias, compileStats } = compileTypes(representatives, rels, options);
|
|
60
125
|
|
|
61
126
|
return {rels, representatives, relAlias, compileStats, sourceDefs: defs};
|
package/k.mjs
CHANGED
|
@@ -12,8 +12,7 @@ import {
|
|
|
12
12
|
compileLibrary,
|
|
13
13
|
decodeObject,
|
|
14
14
|
objectToFunction,
|
|
15
|
-
loadLibrary
|
|
16
|
-
buildExportPreamble
|
|
15
|
+
loadLibrary
|
|
17
16
|
} from "./object.mjs";
|
|
18
17
|
|
|
19
18
|
let kScript, inputStream;
|
|
@@ -34,14 +33,14 @@ function helpText() {
|
|
|
34
33
|
"",
|
|
35
34
|
"Options:",
|
|
36
35
|
" --lib file Load one .klib or .k library before compiling.",
|
|
37
|
-
" --
|
|
36
|
+
" --use spec Use library alias in scope (repeatable).",
|
|
38
37
|
" spec is 'name' or 'libname:localname'.",
|
|
39
38
|
" -h, --help Show this help.",
|
|
40
39
|
"",
|
|
41
40
|
"Examples:",
|
|
42
41
|
` echo '"abc"' | k-parse | ${prog} '{.1 0}' | k-print`,
|
|
43
42
|
` echo '{"x":1,"y":2}' | k-json --parse | \\`,
|
|
44
|
-
` ${prog} --lib Examples/poly.k --
|
|
43
|
+
` ${prog} --lib Examples/poly.k --use concat \\`,
|
|
45
44
|
` 's={()xs,()ys}concat; s' | k-json --print`
|
|
46
45
|
].join("\n");
|
|
47
46
|
}
|
|
@@ -61,12 +60,13 @@ function isFile(filePath) {
|
|
|
61
60
|
}
|
|
62
61
|
}
|
|
63
62
|
|
|
64
|
-
function compileFile(filePath, libraries,
|
|
63
|
+
function compileFile(filePath, libraries, useSpecs = []) {
|
|
65
64
|
const buffer = fs.readFileSync(filePath);
|
|
66
65
|
try {
|
|
67
66
|
return objectToFunction(decodeObject(buffer));
|
|
68
67
|
} catch {
|
|
69
|
-
|
|
68
|
+
const raw = buffer.toString("utf8");
|
|
69
|
+
return k.compile(raw, { libraries, useSpecs });
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
72
|
|
|
@@ -78,8 +78,8 @@ function compileFile(filePath, libraries, preamble) {
|
|
|
78
78
|
}
|
|
79
79
|
|
|
80
80
|
const libraries = [];
|
|
81
|
-
const
|
|
82
|
-
// Parse --lib and --
|
|
81
|
+
const useSpecs = [];
|
|
82
|
+
// Parse --lib and --use flags
|
|
83
83
|
while (args.length > 0 && args[0].startsWith("--")) {
|
|
84
84
|
if (args[0] === "--lib") {
|
|
85
85
|
args.shift();
|
|
@@ -97,18 +97,16 @@ function compileFile(filePath, libraries, preamble) {
|
|
|
97
97
|
const libBuffer = fs.readFileSync(libPath);
|
|
98
98
|
libraries.push(loadLibrary(decodeObject(libBuffer)));
|
|
99
99
|
}
|
|
100
|
-
} else if (args[0] === "--
|
|
100
|
+
} else if (args[0] === "--use") {
|
|
101
101
|
args.shift();
|
|
102
102
|
const spec = args.shift();
|
|
103
|
-
if (!spec) throw new Error("--
|
|
104
|
-
|
|
103
|
+
if (!spec) throw new Error("--use requires a spec argument");
|
|
104
|
+
useSpecs.push(spec);
|
|
105
105
|
} else {
|
|
106
106
|
break;
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
-
const preamble = buildExportPreamble(exports, libraries);
|
|
111
|
-
|
|
112
110
|
let kScriptStr = (function (arg) {
|
|
113
111
|
if (arg == null) {
|
|
114
112
|
throw new Error("Missing script argument");
|
|
@@ -119,12 +117,10 @@ function compileFile(filePath, libraries, preamble) {
|
|
|
119
117
|
"pass the source/object file path directly"
|
|
120
118
|
);
|
|
121
119
|
}
|
|
122
|
-
if (isFile(arg)) return compileFile(arg, libraries,
|
|
123
|
-
return
|
|
120
|
+
if (isFile(arg)) return compileFile(arg, libraries, useSpecs);
|
|
121
|
+
return k.compile(arg, { libraries, useSpecs });
|
|
124
122
|
})(args.shift());
|
|
125
|
-
let kScript =
|
|
126
|
-
? kScriptStr
|
|
127
|
-
: k.compile(kScriptStr, { libraries });
|
|
123
|
+
let kScript = kScriptStr;
|
|
128
124
|
inputStream = (function (arg) {
|
|
129
125
|
if (arg == null) {
|
|
130
126
|
return stdin;
|
package/kir.mjs
CHANGED
|
@@ -581,9 +581,11 @@ export function retypeObjectRelation(object, relationName, inputPattern, options
|
|
|
581
581
|
|
|
582
582
|
const target = resolveRelation(object, relationName);
|
|
583
583
|
const source = `?${propertyListToFilter(inputPattern)} __kir_target__`;
|
|
584
|
+
const helperRels = Object.keys(object.rels || {}).filter((k) => k !== "__main__");
|
|
584
585
|
const retypedObject = hydrateObject(compileObject(source, {
|
|
585
586
|
source: options.source || "<kir-retype>",
|
|
586
|
-
libraries: [relationLibraryWithTarget(object, target.rel)]
|
|
587
|
+
libraries: [relationLibraryWithTarget(object, target.rel)],
|
|
588
|
+
use: ["__kir_target__", ...helperRels]
|
|
587
589
|
}));
|
|
588
590
|
return objectToKIRP(retypedObject);
|
|
589
591
|
}
|
package/kvm.mjs
CHANGED
|
@@ -13,8 +13,7 @@ import {
|
|
|
13
13
|
compileLibrary,
|
|
14
14
|
compileObjectBuffer,
|
|
15
15
|
decodeObject,
|
|
16
|
-
loadLibrary
|
|
17
|
-
buildExportPreamble
|
|
16
|
+
loadLibrary
|
|
18
17
|
} from "./object.mjs";
|
|
19
18
|
import codes from "./codes.mjs";
|
|
20
19
|
import { isMainEntrypoint } from "./codecs/runtime/cli-entry.mjs";
|
|
@@ -959,7 +958,7 @@ function helpText() {
|
|
|
959
958
|
"",
|
|
960
959
|
"Options:",
|
|
961
960
|
" --lib file Load one .klib or .k library before compiling.",
|
|
962
|
-
" --
|
|
961
|
+
" --use spec Use library alias in scope (repeatable).",
|
|
963
962
|
" spec is 'name' or 'libname:localname'.",
|
|
964
963
|
" --envelope-free Run the interpreter in envelope-free mode.",
|
|
965
964
|
" -h, --help Show this help.",
|
|
@@ -967,7 +966,7 @@ function helpText() {
|
|
|
967
966
|
"Examples:",
|
|
968
967
|
` echo '"abc"' | k-parse | ${prog} '{.1 0}' | k-print`,
|
|
969
968
|
` echo '{"x":1,"y":2}' | k-json --parse | \\`,
|
|
970
|
-
` ${prog} --lib Examples/poly.k --
|
|
969
|
+
` ${prog} --lib Examples/poly.k --use concat \\`,
|
|
971
970
|
` 's={()xs,()ys}concat; s' | k-json --print`
|
|
972
971
|
].join("\n");
|
|
973
972
|
}
|
|
@@ -985,7 +984,7 @@ async function main() {
|
|
|
985
984
|
|
|
986
985
|
let envelopeFree = false;
|
|
987
986
|
const libraries = [];
|
|
988
|
-
const
|
|
987
|
+
const useSpecs = [];
|
|
989
988
|
|
|
990
989
|
// Parse options
|
|
991
990
|
while (args.length > 0) {
|
|
@@ -1008,11 +1007,11 @@ async function main() {
|
|
|
1008
1007
|
const libBuffer = fs.readFileSync(libPath);
|
|
1009
1008
|
libraries.push(loadLibrary(decodeObject(libBuffer)));
|
|
1010
1009
|
}
|
|
1011
|
-
} else if (args[0] === "--
|
|
1010
|
+
} else if (args[0] === "--use") {
|
|
1012
1011
|
args.shift();
|
|
1013
1012
|
const spec = args.shift();
|
|
1014
|
-
if (!spec) throw new Error("--
|
|
1015
|
-
|
|
1013
|
+
if (!spec) throw new Error("--use requires a spec argument");
|
|
1014
|
+
useSpecs.push(spec);
|
|
1016
1015
|
} else if (args[0].startsWith("--")) {
|
|
1017
1016
|
throw new Error(`Unknown option: ${args[0]}`);
|
|
1018
1017
|
} else {
|
|
@@ -1039,13 +1038,14 @@ async function main() {
|
|
|
1039
1038
|
if (error.message === "Cannot run a .klib library without a main relation; load it with --lib.") {
|
|
1040
1039
|
throw error;
|
|
1041
1040
|
}
|
|
1041
|
+
const raw = buffer.toString("utf8");
|
|
1042
1042
|
return {
|
|
1043
1043
|
kind: "source",
|
|
1044
|
-
source:
|
|
1044
|
+
source: raw
|
|
1045
1045
|
};
|
|
1046
1046
|
}
|
|
1047
1047
|
}
|
|
1048
|
-
return { kind: "source", source:
|
|
1048
|
+
return { kind: "source", source: arg };
|
|
1049
1049
|
})(args.shift());
|
|
1050
1050
|
|
|
1051
1051
|
const inputStream = (function (arg) {
|
|
@@ -1061,7 +1061,7 @@ async function main() {
|
|
|
1061
1061
|
|
|
1062
1062
|
const object = programInput.kind === "object"
|
|
1063
1063
|
? programInput.object
|
|
1064
|
-
: decodeObject(compileObjectBuffer(programInput.source, { libraries }));
|
|
1064
|
+
: decodeObject(compileObjectBuffer(programInput.source, { libraries, useSpecs }));
|
|
1065
1065
|
const kir = objectToKIRP(object);
|
|
1066
1066
|
const mainRelName = kir.main;
|
|
1067
1067
|
const mainRel = kir.rels[mainRelName];
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
# --lib lib/bits.k --use trim inv_loop inv cmp inc_bits dec_bits plus_bits minus_bits mul_bits
|
|
2
|
+
|
|
3
|
+
-- lib/arithmetics.k — Signed arbitrary-precision integers (int[])
|
|
4
|
+
|
|
5
|
+
---------------------------------------------------------------
|
|
6
|
+
-- §1. Base Patterns & Primitives
|
|
7
|
+
---------------------------------------------------------------
|
|
8
|
+
|
|
9
|
+
bool[] = < {} true, {} false >;
|
|
10
|
+
order[] = < {} lt, {} eq, {} gt >;
|
|
11
|
+
bits[] = < {} _, B 0, B 1 > = B;
|
|
12
|
+
|
|
13
|
+
true = {} |true ?bool[];
|
|
14
|
+
false = {} |false ?bool[];
|
|
15
|
+
un_true = ?bool[] /true;
|
|
16
|
+
un_false = ?bool[] /false;
|
|
17
|
+
un_lt = ?order[] /lt;
|
|
18
|
+
un_eq = ?order[] /eq;
|
|
19
|
+
un_gt = ?order[] /gt;
|
|
20
|
+
|
|
21
|
+
_ = {} |_ ?bits[];
|
|
22
|
+
0b = |0 ?bits[];
|
|
23
|
+
1b = |1 ?bits[];
|
|
24
|
+
un_ = ?bits[] /_;
|
|
25
|
+
un0 = ?bits[] /0;
|
|
26
|
+
un1 = ?bits[] /1;
|
|
27
|
+
_? = un_ _;
|
|
28
|
+
0 = _ 0b;
|
|
29
|
+
1 = _ 1b;
|
|
30
|
+
|
|
31
|
+
---------------------------------------------------------------
|
|
32
|
+
-- §2. Natural Constants & Helpers (bits[])
|
|
33
|
+
---------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
succ = inc_bits;
|
|
36
|
+
2 = 1 succ;
|
|
37
|
+
3 = 2 succ;
|
|
38
|
+
4 = 3 succ;
|
|
39
|
+
5 = 4 succ;
|
|
40
|
+
6 = 5 succ;
|
|
41
|
+
7 = 6 succ;
|
|
42
|
+
8 = 7 succ;
|
|
43
|
+
9 = 8 succ;
|
|
44
|
+
10 = 9 succ;
|
|
45
|
+
11 = 10 succ;
|
|
46
|
+
12 = 11 succ;
|
|
47
|
+
|
|
48
|
+
empty? = _?;
|
|
49
|
+
remove_leading_zeros = trim;
|
|
50
|
+
nat = trim < _? 0, () >;
|
|
51
|
+
concat = { .x inv x, .y r } inv_loop;
|
|
52
|
+
|
|
53
|
+
cmp_nat = { .x trim x, .y trim y } cmp;
|
|
54
|
+
GT = { cmp_nat un_gt if, () then } .then;
|
|
55
|
+
EQ = { cmp_nat un_eq if, () then } .then;
|
|
56
|
+
LE = { cmp_nat <un_lt, un_eq> if, () then } .then;
|
|
57
|
+
|
|
58
|
+
---------------------------------------------------------------
|
|
59
|
+
-- §3. Signed Integer Pattern & Primitives (int[])
|
|
60
|
+
---------------------------------------------------------------
|
|
61
|
+
|
|
62
|
+
int[] = < bits[] "+", bits[] "-" >;
|
|
63
|
+
int? = ?int[];
|
|
64
|
+
int_pair[] = { int[] x, int[] y };
|
|
65
|
+
|
|
66
|
+
-- Only the 4 atomic primitives mention ?int[]
|
|
67
|
+
pos_int = |"+" ?int[];
|
|
68
|
+
neg_int = |"-" ?int[];
|
|
69
|
+
un_pos = ?int[] /"+";
|
|
70
|
+
un_neg = ?int[] /"-";
|
|
71
|
+
|
|
72
|
+
int = nat pos_int;
|
|
73
|
+
abs = < un_pos, un_neg >;
|
|
74
|
+
|
|
75
|
+
pos? = { un_pos trim un1 if, () then } .then;
|
|
76
|
+
neg? = { un_neg if, () then } .then;
|
|
77
|
+
zero_int? = { un_pos trim un_ if, () then } .then;
|
|
78
|
+
minus_one? = { un_neg trim un1 un_ if, () then } .then;
|
|
79
|
+
|
|
80
|
+
swap_sign = <
|
|
81
|
+
zero_int?,
|
|
82
|
+
un_pos neg_int,
|
|
83
|
+
un_neg pos_int
|
|
84
|
+
>;
|
|
85
|
+
|
|
86
|
+
---------------------------------------------------------------
|
|
87
|
+
-- §4. Integer Increment, Decrement, Addition, Subtraction, Multiplication
|
|
88
|
+
---------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
inc = <
|
|
91
|
+
un_pos inc_bits nat pos_int,
|
|
92
|
+
minus_one? 0 int,
|
|
93
|
+
un_neg dec_bits nat neg_int
|
|
94
|
+
>;
|
|
95
|
+
|
|
96
|
+
dec = <
|
|
97
|
+
zero_int? 1 neg_int,
|
|
98
|
+
un_pos dec_bits nat pos_int,
|
|
99
|
+
un_neg inc_bits nat neg_int
|
|
100
|
+
>;
|
|
101
|
+
|
|
102
|
+
plus = <
|
|
103
|
+
{ .x un_pos x, .y un_pos y } plus_bits nat pos_int,
|
|
104
|
+
{ .x un_neg x, .y un_neg y } plus_bits nat neg_int,
|
|
105
|
+
{ .y un_neg x, .x un_pos y } GT minus_bits nat neg_int,
|
|
106
|
+
{ .x un_pos x, .y un_neg y } minus_bits nat pos_int,
|
|
107
|
+
{ .x un_neg x, .y un_pos y } GT minus_bits nat neg_int,
|
|
108
|
+
{ .y un_pos x, .x un_neg y } minus_bits nat pos_int
|
|
109
|
+
>;
|
|
110
|
+
|
|
111
|
+
minus = { .x x, .y swap_sign y } plus;
|
|
112
|
+
|
|
113
|
+
times = <
|
|
114
|
+
{ .x un_pos x, .y un_pos y } mul_bits int,
|
|
115
|
+
{ .x un_neg x, .y un_neg y } mul_bits int,
|
|
116
|
+
{ .x un_pos x, .y un_neg y } mul_bits int swap_sign,
|
|
117
|
+
{ .x un_neg x, .y un_pos y } mul_bits int swap_sign
|
|
118
|
+
>;
|
|
119
|
+
|
|
120
|
+
---------------------------------------------------------------
|
|
121
|
+
-- §5. Karatsuba Multiplication (O(n^1.585))
|
|
122
|
+
---------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
peel2 = < <un0, un1> <un0, un1>, <un0, un1>, _? >;
|
|
125
|
+
|
|
126
|
+
half_loop = <
|
|
127
|
+
{ .x un_ a, .y un_ b, .m then } .then,
|
|
128
|
+
{ .x peel2 x, .y peel2 y, .m 0b m } half_loop
|
|
129
|
+
>;
|
|
130
|
+
half_bits = { .x trim x, .y trim y, _ m } half_loop;
|
|
131
|
+
|
|
132
|
+
drop8 = un0 un0 un0 un0 un0 un0 un0 un0;
|
|
133
|
+
drop64 = drop8 drop8 drop8 drop8 drop8 drop8 drop8 drop8;
|
|
134
|
+
drop256 = drop64 drop64 drop64 drop64;
|
|
135
|
+
at_least_256? = < drop256 true, false >;
|
|
136
|
+
|
|
137
|
+
split_rev_loop = <
|
|
138
|
+
{ .m un_ if, { .low nat low, .x_rev inv nat high } then } .then,
|
|
139
|
+
{ .x_rev un_ if, { .low nat low, 0 high } then } .then,
|
|
140
|
+
<
|
|
141
|
+
{ .x_rev un0 x_rev, .m un0 m, .low 0b low },
|
|
142
|
+
{ .x_rev un1 x_rev, .m un0 m, .low 1b low }
|
|
143
|
+
> split_rev_loop
|
|
144
|
+
>;
|
|
145
|
+
split_at = { .x inv x_rev, .m m, _ low } split_rev_loop;
|
|
146
|
+
|
|
147
|
+
shift_bits = <
|
|
148
|
+
{ .val trim un_ if, 0 then } .then,
|
|
149
|
+
{ .val inv x, .m r } inv_loop
|
|
150
|
+
>;
|
|
151
|
+
|
|
152
|
+
shift2_bits = <
|
|
153
|
+
{ .val trim un_ if, 0 then } .then,
|
|
154
|
+
{ .val inv x, { .m x, .m r } inv_loop r } inv_loop
|
|
155
|
+
>;
|
|
156
|
+
|
|
157
|
+
karatsuba_bits = { { .x x, .y y } half_bits m, .x x, .y y } <
|
|
158
|
+
{ .m at_least_256? un_false if, { .x x, .y y } mul_bits nat then } .then,
|
|
159
|
+
{
|
|
160
|
+
.m at_least_256? un_true if,
|
|
161
|
+
{
|
|
162
|
+
{ .x x, .m m } split_at sx,
|
|
163
|
+
{ .y x, .m m } split_at sy,
|
|
164
|
+
.m m
|
|
165
|
+
}
|
|
166
|
+
{
|
|
167
|
+
{ .sx.high x, .sy.high y } karatsuba_bits z2,
|
|
168
|
+
{ .sx.low x, .sy.low y } karatsuba_bits z0,
|
|
169
|
+
{
|
|
170
|
+
{ .sx.high x, .sx.low y } plus_bits x,
|
|
171
|
+
{ .sy.high x, .sy.low y } plus_bits y
|
|
172
|
+
} karatsuba_bits z_sum,
|
|
173
|
+
.m m
|
|
174
|
+
}
|
|
175
|
+
{
|
|
176
|
+
.z2 z2,
|
|
177
|
+
.z0 z0,
|
|
178
|
+
{ { .z_sum x, .z2 y } minus_bits x, .z0 y } minus_bits z1,
|
|
179
|
+
.m m
|
|
180
|
+
}
|
|
181
|
+
{
|
|
182
|
+
{ .z2 val, .m m } shift2_bits z2_s,
|
|
183
|
+
{ .z1 val, .m m } shift_bits z1_s,
|
|
184
|
+
.z0 z0
|
|
185
|
+
}
|
|
186
|
+
{ { .z2_s x, .z1_s y } plus_bits x, .z0 y } plus_bits nat then
|
|
187
|
+
} .then
|
|
188
|
+
>;
|
|
189
|
+
|
|
190
|
+
karatsuba = <
|
|
191
|
+
{ .x un_pos x, .y un_pos y } karatsuba_bits int,
|
|
192
|
+
{ .x un_neg x, .y un_neg y } karatsuba_bits int,
|
|
193
|
+
{ .x un_pos x, .y un_neg y } karatsuba_bits int swap_sign,
|
|
194
|
+
{ .x un_neg x, .y un_pos y } karatsuba_bits int swap_sign
|
|
195
|
+
>;
|
|
196
|
+
|
|
197
|
+
---------------------------------------------------------------
|
|
198
|
+
-- §6. Integer Division (Adaptive Hybrid), Modulo, GCD, LCM
|
|
199
|
+
---------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
shift_in_0 = trim < _? 0, { inv 0b x, _ r } inv_loop >;
|
|
202
|
+
shift_in_1 = trim < _? 1, { inv 1b x, _ r } inv_loop >;
|
|
203
|
+
sub_bits = minus_bits nat;
|
|
204
|
+
|
|
205
|
+
div_restoring = <
|
|
206
|
+
{ .x un_ if, { .q inv int div, .r rem } then } .then,
|
|
207
|
+
<
|
|
208
|
+
{ .x un0 x, .r shift_in_0 r, .y y, .q q },
|
|
209
|
+
{ .x un1 x, .r shift_in_1 r, .y y, .q q }
|
|
210
|
+
>
|
|
211
|
+
<
|
|
212
|
+
{ { .y x, .r y } LE if, { .x x, .y y, .q 1b q, { .r x, .y y } sub_bits r } then } .then,
|
|
213
|
+
{ { .y x, .r y } GT if, { .x x, .y y, .q 0b q, .r r } then } .then
|
|
214
|
+
>
|
|
215
|
+
div_restoring
|
|
216
|
+
>;
|
|
217
|
+
|
|
218
|
+
pad_down = <
|
|
219
|
+
{ .x un_ if, { ._y _y, .steps steps } then } .then,
|
|
220
|
+
{ .x <un0, un1> x, ._y 0b _y, .steps 0b steps } pad_down
|
|
221
|
+
>;
|
|
222
|
+
|
|
223
|
+
align_down = <
|
|
224
|
+
{ .x <un0, un1> x, .y <un0, un1> y, ._y _y } align_down,
|
|
225
|
+
{ .y un_ if, { .x x, ._y _y, _ steps } pad_down then } .then,
|
|
226
|
+
{ .x un_ a, .y un_ b, { ._y _y, _ steps } then } .then
|
|
227
|
+
>;
|
|
228
|
+
|
|
229
|
+
div_down =
|
|
230
|
+
{ .x x, ._y _y, .steps steps, .q q, ._y inv nat y_scaled }
|
|
231
|
+
<
|
|
232
|
+
{
|
|
233
|
+
{ .y_scaled x, .x y } LE if,
|
|
234
|
+
{ { .x x, .y_scaled y } sub_bits x, .q 1b q, ._y _y, .steps steps } then
|
|
235
|
+
} .then,
|
|
236
|
+
{
|
|
237
|
+
{ .y_scaled x, .x y } GT if,
|
|
238
|
+
{ .x x, .q 0b q, ._y _y, .steps steps } then
|
|
239
|
+
} .then
|
|
240
|
+
>
|
|
241
|
+
<
|
|
242
|
+
{ .steps un_ if, { .q inv int div, .x rem } then } .then,
|
|
243
|
+
{ .x x, ._y un0 _y, .steps un0 steps, .q q } div_down
|
|
244
|
+
>;
|
|
245
|
+
|
|
246
|
+
check_2y = <
|
|
247
|
+
{ .x un_ a, .y <_?, un0, un1> b } false,
|
|
248
|
+
{ .y un_ a, .x <un0, un1> b } true,
|
|
249
|
+
{ .x <un0, un1> un_ a, .y <un0, un1> b } false,
|
|
250
|
+
{ .x <un0, un1> <un0, un1> x, .y <un0, un1> y } check_2y
|
|
251
|
+
>;
|
|
252
|
+
|
|
253
|
+
div_mag = <
|
|
254
|
+
{ .x un_ a, .y <_?, un0, un1> b, { 0 int div, 0 rem } then } .then,
|
|
255
|
+
{ { .y x, .x y } GT if, { 0 int div, .x rem } then } .then,
|
|
256
|
+
{
|
|
257
|
+
{ .x x, .y y } check_2y un_false if,
|
|
258
|
+
{ { .x x, .y y, .y inv _y } align_down aligned, .x x }
|
|
259
|
+
{ .x x, .aligned._y _y, .aligned.steps steps, _ q } div_down then
|
|
260
|
+
} .then,
|
|
261
|
+
{
|
|
262
|
+
{ .x x, .y y } check_2y un_true if,
|
|
263
|
+
{ .x x, .y y, 0 r, _ q } div_restoring then
|
|
264
|
+
} .then
|
|
265
|
+
>;
|
|
266
|
+
|
|
267
|
+
div = <
|
|
268
|
+
{ .x un_pos trim x, .y un_pos trim y } div_mag,
|
|
269
|
+
{ .x un_neg trim x, .y un_neg trim y } div_mag,
|
|
270
|
+
{ .x un_pos trim x, .y un_neg trim y } div_mag { .div swap_sign div, .rem rem },
|
|
271
|
+
{ .x un_neg trim x, .y un_pos trim y } div_mag { .div swap_sign div, .rem rem }
|
|
272
|
+
>;
|
|
273
|
+
|
|
274
|
+
mod = { .x int x, .y int y } div .rem;
|
|
275
|
+
|
|
276
|
+
gcd_loop = <
|
|
277
|
+
{ .y trim un_ if, .x nat then } .then,
|
|
278
|
+
{ .y x, { .x x, .y y } mod y } gcd_loop
|
|
279
|
+
>;
|
|
280
|
+
|
|
281
|
+
gcd = <
|
|
282
|
+
{ .y x, .x y } GT,
|
|
283
|
+
()
|
|
284
|
+
> gcd_loop;
|
|
285
|
+
|
|
286
|
+
lcm = { { .x int x, gcd int y } div .div x, .y int y } times abs;
|
package/lib/bit.k
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
-- lib/bit.k — Finite enumeration patterns: bit[], bool[], order[]
|
|
2
|
+
|
|
3
|
+
---------------------------------------------------------------
|
|
4
|
+
-- §1. Bit
|
|
5
|
+
---------------------------------------------------------------
|
|
6
|
+
|
|
7
|
+
bit[] = < {} 0, {} 1 >;
|
|
8
|
+
|
|
9
|
+
-- Primitive constructors and destructors
|
|
10
|
+
0 = {} |0 ?bit[];
|
|
11
|
+
1 = {} |1 ?bit[];
|
|
12
|
+
is0 = ?bit[] /0;
|
|
13
|
+
is1 = ?bit[] /1;
|
|
14
|
+
|
|
15
|
+
-- Polymorphic tag guards
|
|
16
|
+
0? = ?X /0 |0 ?X;
|
|
17
|
+
1? = ?X /1 |1 ?X;
|
|
18
|
+
|
|
19
|
+
-- Bit operations and equality guard
|
|
20
|
+
not_bit = < is0 1, is1 0 >;
|
|
21
|
+
and_bit = < .x is0 0, .y is0 0, { .x is1 a, .y is1 b } 1 >;
|
|
22
|
+
or_bit = < .x is1 1, .y is1 1, { .x is0 a, .y is0 b } 0 >;
|
|
23
|
+
xor_bit = <
|
|
24
|
+
{ .x is0 a, .y is0 b } 0,
|
|
25
|
+
{ .x is1 a, .y is1 b } 0,
|
|
26
|
+
{ .x is0 a, .y is1 b } 1,
|
|
27
|
+
{ .x is1 a, .y is0 b } 1
|
|
28
|
+
>;
|
|
29
|
+
eq_bit? = <
|
|
30
|
+
{ .x is0 0 x, .y is0 0 y },
|
|
31
|
+
{ .x is1 1 x, .y is1 1 y }
|
|
32
|
+
>;
|
|
33
|
+
|
|
34
|
+
---------------------------------------------------------------
|
|
35
|
+
-- §2. Bool
|
|
36
|
+
---------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
bool[] = < {} true, {} false >;
|
|
39
|
+
|
|
40
|
+
-- Primitive constructors and destructors
|
|
41
|
+
true = {} |true ?bool[];
|
|
42
|
+
false = {} |false ?bool[];
|
|
43
|
+
un_true = ?bool[] /true;
|
|
44
|
+
un_false = ?bool[] /false;
|
|
45
|
+
|
|
46
|
+
-- Bool guards and negation
|
|
47
|
+
true? = un_true true;
|
|
48
|
+
false? = un_false false;
|
|
49
|
+
not = < un_true false, un_false true >;
|
|
50
|
+
|
|
51
|
+
---------------------------------------------------------------
|
|
52
|
+
-- §3. Order
|
|
53
|
+
---------------------------------------------------------------
|
|
54
|
+
|
|
55
|
+
order[] = < {} lt, {} eq, {} gt >;
|
|
56
|
+
|
|
57
|
+
-- Primitive constructors and destructors
|
|
58
|
+
lt = {} |lt ?order[];
|
|
59
|
+
eq = {} |eq ?order[];
|
|
60
|
+
gt = {} |gt ?order[];
|
|
61
|
+
un_lt = ?order[] /lt;
|
|
62
|
+
un_eq = ?order[] /eq;
|
|
63
|
+
un_gt = ?order[] /gt;
|
|
64
|
+
|
|
65
|
+
-- Order guards
|
|
66
|
+
lt_order? = un_lt lt;
|
|
67
|
+
eq_order? = un_eq eq;
|
|
68
|
+
gt_order? = un_gt gt;
|