@mettascript/core 2.0.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.
- package/LICENSE +21 -0
- package/README.md +35 -0
- package/dist/chunk-ITWN5EHF.js +49 -0
- package/dist/host-kERXz0y1.d.ts +1035 -0
- package/dist/host.d.ts +1 -0
- package/dist/host.js +6 -0
- package/dist/index.d.ts +460 -0
- package/dist/index.js +15865 -0
- package/package.json +56 -0
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { j as ComposeHostInteropsOptions, u as HostInterop, v as HostTextLoader, as as composeHostInterops } from './host-kERXz0y1.js';
|
package/dist/host.js
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
import { M as MinEnv, A as Atom, B as Bindings, I as InternTable, T as TraceSink, H as HostImportFn, a as AsyncGroundFn, F as FlatKB } from './host-kERXz0y1.js';
|
|
2
|
+
export { b as ActiveTableEntry, c as AsyncInSyncError, d as BAIL, e as BindingRel, C as CompiledFns, f as CompiledHolder, g as CompiledImpureOps, h as CompiledRunResult, i as CompletedTableEntry, j as ComposeHostInteropsOptions, E as EncodedAtomKey, k as EqRel, l as ExprAtom, m as FlatAtomSpace, n as FlatAtomSpaceTable, o as Frame, G as GndAtom, p as Ground, q as GroundFn, r as GroundedExec, s as GroundedMatch, t as GroundingTable, u as HostInterop, v as HostTextLoader, w as IntVal, x as Interner, y as Item, z as MetaType, R as ReduceEffect, D as ReduceResult, J as Ret, S as Skel, K as SkelBody, L as SkelClause, N as SkelGoal, O as SkelTail, P as St, Q as Stack, U as StackCons, V as SymAtom, W as TAG_ARITY, X as TAG_NEWVAR, Y as TAG_SYMBOL, Z as TAG_VARREF, _ as TableBudget, $ as TableKey, a0 as TableKeyKind, a1 as TableSpace, a2 as TokenTrie, a3 as TraceEvent, a4 as ValRel, a5 as VarAtom, a6 as VariantAtomKey, a7 as World, a8 as _internals, a9 as addAtomToEnv, aa as addEqRaw, ab as addInt, ac as addValRaw, ad as atomEq, ae as atomSize, af as atomVars, ag as baseTable, ah as buildEnv, ai as callGrounded, aj as canCompactAtom, ak as canInternExprItems, al as canonInt, am as checkApplication, an as cmpIntVal, ao as collectVars, ap as compareNumbers, aq as compileDependentNondetGroup, ar as compileEnv, as as composeHostInterops, at as createInternTable, au as decodeAt, av as decodeAtom, aw as emptyBindings, ax as emptyEnv, ay as emptyExpr, az as encodeAtom, aA as encodeInto, aB as encodePattern, aC as encodeVariantKey, aD as eqRelations, aE as evalAtom, aF as expr, aG as freshenRule, aH as fromRelations, aI as gbool, aJ as getTypes, aK as gfloat, aL as gint, aM as gnd, aN as groundEq, aO as groundType, aP as groundedOperationType, aQ as gstr, aR as gunit, aS as hasEq, aT as hasLoop, aU as hasLoopFromBase, aV as hashOf, aW as initSt, aX as intAbs, aY as intDiv, aZ as intMod, a_ as internAtom, a$ as internBuiltExpr, b0 as internExpr, b1 as isEmpty, b2 as isErrorAtom, b3 as isExpr, b4 as isGnd, b5 as isSym, b6 as isTableSafeGroundedOp, b7 as isVar, b8 as isZero, b9 as lookupVal, ba as makeEqRel, bb as makeValRel, bc as matchFlatAt, bd as metaType, be as mettaEval, bf as mettaEvalAsync, bg as mixHash, bh as mulInt, bi as pettaOpNames, bj as prependValRaw, bk as registerAsyncGroundedOperation, bl as registerGroundedOperation, bm as relations, bn as removeVal, bo as runCompiled, bp as runCompiledEffectCount, bq as setHostEffectsEnabled, br as setOutputSink, bs as setRawSink, bt as setStaticCompactThresholdForTests, bu as size, bv as someVal, bw as stdTable, bx as strHash, by as subInt, bz as sym, bA as toF64, bB as valEntries, bC as variable } from './host-kERXz0y1.js';
|
|
3
|
+
|
|
4
|
+
/** Ops that read or write mutable state, do I/O, read types/spaces, or introduce nondeterminism.
|
|
5
|
+
* A functor whose body reaches any of these (directly or transitively) is not tabled in P1. */
|
|
6
|
+
declare const IMPURE_OPS: ReadonlySet<string>;
|
|
7
|
+
/** `IMPURE_OPS` minus `empty`, for moded tabling only (see `analyzePurityModed`). `empty`'s own grounded
|
|
8
|
+
* implementation (`builtins.ts`) is `() => ok()`: a zero-argument constant with no state, argument, or
|
|
9
|
+
* space dependency whatsoever, so it cannot make a call's answer set depend on anything the call's own
|
|
10
|
+
* arguments (and the world's rule set, which the version-keyed path already accounts for) do not already
|
|
11
|
+
* capture — unlike every other entry here (nondeterminism ops, I/O, space/state reads and writes). It
|
|
12
|
+
* is grouped with those in `IMPURE_OPS` only because ground tabling has never needed to look past that
|
|
13
|
+
* conservative default; `(empty)` pruning a failed branch is the standard, idiomatic way a MeTTa function
|
|
14
|
+
* signals "no answer" (Prolog's `fail`), so excluding it here is what actually lets moded tabling apply
|
|
15
|
+
* to ordinary backward-chaining predicates instead of never firing on any of them. */
|
|
16
|
+
declare const MODED_IMPURE_OPS: ReadonlySet<string>;
|
|
17
|
+
/** A named grounded operation is table-safe only when it is an unchanged built-in on the pure list. */
|
|
18
|
+
declare function isTablingImpureHead(env: MinEnv, name: string, impureOps?: ReadonlySet<string>): boolean;
|
|
19
|
+
/** The set of functor names safe to table. Conservative: a variable-headed (`$x`-headed) equation can match
|
|
20
|
+
* anything, so its presence disables tabling entirely. (`varRules` also holds expression-headed equations,
|
|
21
|
+
* which match only their own constructor and are harmless here.) `impureOps` defaults to `IMPURE_OPS`
|
|
22
|
+
* (every existing caller's exact prior behavior); moded tabling passes `MODED_IMPURE_OPS` instead. No
|
|
23
|
+
* internal cache here (unlike `runtimeFunctorPure` in eval.ts), so parameterizing carries no
|
|
24
|
+
* cache-key-collision risk — each call recomputes the fixpoint fresh over whichever set it's given. */
|
|
25
|
+
declare function analyzePurity(env: MinEnv, impureOps?: ReadonlySet<string>): Set<string>;
|
|
26
|
+
/** How many calls in `a` target any functor in `targets`. */
|
|
27
|
+
declare function functorCallCount(a: Atom, targets: ReadonlySet<string>): number;
|
|
28
|
+
/** Pure functors worth automatic tabling. A recursive SCC is worth tabling when some rule body branches
|
|
29
|
+
* into that same SCC at least twice. This keeps fib/proof-search overlap tabled while avoiding unbounded
|
|
30
|
+
* caches for single-tail recursion such as factorial or trial division. */
|
|
31
|
+
declare function analyzeTableWorth(env: MinEnv, pureFunctors: ReadonlySet<string>): Set<string>;
|
|
32
|
+
/** A key is well-formed only if it contains no Float leaf (IEEE-754 breaks lawful equality, so a
|
|
33
|
+
* float-keyed table could merge or split keys differently from `match`). Mutable references never
|
|
34
|
+
* appear in a ground call, so the float check is the only one needed in P1. */
|
|
35
|
+
declare function keyWellFormed(a: Atom): boolean;
|
|
36
|
+
|
|
37
|
+
/** A relation: a set of tuples, each a binding of this relation's variables to values. */
|
|
38
|
+
interface Relation<V> {
|
|
39
|
+
readonly vars: readonly string[];
|
|
40
|
+
readonly tuples: ReadonlyArray<ReadonlyMap<string, V>>;
|
|
41
|
+
}
|
|
42
|
+
/** Hooks for streaming the join: `onDescend`/`onAscend` bracket each variable binding as the search descends
|
|
43
|
+
* and backtracks, and `onLeaf` fires at each full solution. The caller keeps whatever state it needs (a
|
|
44
|
+
* partial map, or a trail synced to the descent) so the join itself never materializes the answer set. */
|
|
45
|
+
interface WcoFoldHooks<V> {
|
|
46
|
+
onDescend(variable: string, value: V): void;
|
|
47
|
+
onAscend(variable: string): void;
|
|
48
|
+
onLeaf(): void;
|
|
49
|
+
}
|
|
50
|
+
/** The worst-case-optimal join (generic join / leapfrog-triejoin family) as a streaming fold: it drives the
|
|
51
|
+
* same trie-cursor intersection as the textbook join but, instead of collecting binding maps, brackets each
|
|
52
|
+
* variable binding with `onDescend`/`onAscend` and calls `onLeaf` per solution. Each relation is indexed
|
|
53
|
+
* once into a trie over its variables in the join order, so binding a variable intersects the relations'
|
|
54
|
+
* current trie levels by key lookup. A consumer that only needs an aggregate (COUNT/EXISTS) keeps a trail
|
|
55
|
+
* synced to the descent and never materializes the answer set (MORK's `trie_join_count` kernel). `key` maps
|
|
56
|
+
* a value to a comparable string; pass `varOrder` to fix the elimination order (first-seen otherwise). */
|
|
57
|
+
declare function wcoJoinFold<V>(rels: ReadonlyArray<Relation<V>>, key: (v: V) => string, hooks: WcoFoldHooks<V>, varOrder?: readonly string[]): void;
|
|
58
|
+
/** Collect every join solution as a fresh binding map: a thin materializing wrapper over `wcoJoinFold`. */
|
|
59
|
+
declare function wcoJoin<V>(rels: ReadonlyArray<Relation<V>>, key: (v: V) => string, varOrder?: readonly string[]): Array<Map<string, V>>;
|
|
60
|
+
|
|
61
|
+
/** A substitution: an association list of variable name to atom. */
|
|
62
|
+
type Subst = ReadonlyArray<readonly [string, Atom]>;
|
|
63
|
+
declare const emptySubst: Subst;
|
|
64
|
+
/** First value assigned to `x`, if any. */
|
|
65
|
+
declare function lookupSubst(s: Subst, x: string): Atom | undefined;
|
|
66
|
+
/** Drop every binding for `x`. */
|
|
67
|
+
declare function eraseSubst(s: Subst, x: string): Subst;
|
|
68
|
+
/** `(x,a) :: erase s x` (LeaTTa `Subst.extend`). */
|
|
69
|
+
declare function extendSubst(s: Subst, x: string, a: Atom): Subst;
|
|
70
|
+
/** Apply `s` to an atom: replace each variable by its assigned value (one pass; the substituted
|
|
71
|
+
* value is not itself re-substituted). */
|
|
72
|
+
declare function applySubst(s: Subst, a: Atom): Atom;
|
|
73
|
+
/** Occurs-check: does `$x` appear anywhere in the atom? */
|
|
74
|
+
declare function occurs(x: string, a: Atom): boolean;
|
|
75
|
+
|
|
76
|
+
/** Most-general unifier of two atoms, or null if they do not unify. */
|
|
77
|
+
declare function unifyTop(a: Atom, b: Atom): Subst | null;
|
|
78
|
+
/** Whether two atoms unify (the satisfiability check used by addVarBinding). */
|
|
79
|
+
declare function unifiable(a: Atom, b: Atom): boolean;
|
|
80
|
+
|
|
81
|
+
/** A custom matcher for grounded atoms; may be nondeterministic. */
|
|
82
|
+
type GroundMatcher = (left: Atom, right: Atom) => Bindings[];
|
|
83
|
+
/** Value pairs currently being reconciled somewhere up the call stack, keyed by object identity (l -> {r}).
|
|
84
|
+
* Allocated by the first conflicting `reconcile` in a merge cascade and threaded through the recursion. */
|
|
85
|
+
type ReconcileSeen = Map<Atom, Set<Atom>>;
|
|
86
|
+
/** Add `$x ← v` to `b` consistently. If `$x` is already bound to a different value, reconcile the old value
|
|
87
|
+
* against the new one (propagating the unification constraint), rejecting a cyclic result. Mirrors hyperon's
|
|
88
|
+
* `add_var_binding` with LeaTTa's occurs check. */
|
|
89
|
+
declare function addVarBinding(b: Bindings, x: string, v: Atom, seen?: ReconcileSeen): Bindings[];
|
|
90
|
+
/** Add the alias `$x = $y` to `b` consistently. If both are already value-bound to different values,
|
|
91
|
+
* reconcile those values (mirrors hyperon's `add_var_equality`); otherwise record the equality. */
|
|
92
|
+
declare function addVarEquality(b: Bindings, x: string, y: string, seen?: ReconcileSeen): Bindings[];
|
|
93
|
+
/** Combine two binding sets into all their consistent unions (LeaTTa `merge`). */
|
|
94
|
+
declare function merge(a: Bindings, b: Bindings, seen?: ReconcileSeen): Bindings[];
|
|
95
|
+
/** Match atoms in the official left/right style (LeaTTa `matchAtomsWith`). `leftSuffix` (default empty)
|
|
96
|
+
* scopes the LEFT atom's variables: a left variable `$x` is treated as `$x<suffix>`, so a rule LHS can be
|
|
97
|
+
* matched without first cloning it with freshened variables. */
|
|
98
|
+
declare function matchAtomsWith(custom: GroundMatcher | undefined, l: Atom, r: Atom, leftSuffix?: string): Bindings[];
|
|
99
|
+
/** Match pattern `l` against `r` with the default matcher (no custom grounded matching). */
|
|
100
|
+
declare function matchAtoms(l: Atom, r: Atom): Bindings[];
|
|
101
|
+
/** Match a rule LHS `l` against `r`, scoping `l`'s variables with `suffix` (so the rule need not be cloned
|
|
102
|
+
* with freshened variables first). The resulting bindings key the rule variables as `name<suffix>`, exactly
|
|
103
|
+
* as upfront freshening would, so `instantiate(_, rhs, suffix)` resolves the matching RHS identically. */
|
|
104
|
+
declare function matchAtomsScoped(l: Atom, r: Atom, suffix: string): Bindings[];
|
|
105
|
+
|
|
106
|
+
/** A binding set viewed as a substitution: value bindings only; `eq` aliases are dropped. */
|
|
107
|
+
declare function bindingsToSubst(b: Bindings): Subst;
|
|
108
|
+
/**
|
|
109
|
+
* Apply a binding set to an atom as a substitution, resolved to a fixpoint. A binding set produced by
|
|
110
|
+
* unification is triangular: a variable's value can mention another still-bound variable (nonlinear
|
|
111
|
+
* pattern reconciliation and merge both build these). A single pass would leave that inner variable in
|
|
112
|
+
* the result, and if scope restriction later drops its binding the derived constraint is lost, which is
|
|
113
|
+
* unsound. So a substituted value is itself resolved through the same binding set.
|
|
114
|
+
*
|
|
115
|
+
* The resolution is bounded, terminating, and scales linearly in the binding set:
|
|
116
|
+
* - a variable-to-variable chain (`$a -> $b -> ... -> value`) is followed iteratively, so a long chain
|
|
117
|
+
* costs stack depth O(term nesting), not O(chain length), with O(1) lookups once indexed;
|
|
118
|
+
* - a binding cycle (`$x -> $y -> $x`, or a structural `$x -> (f $y)`, `$y -> (g $x)`) is truncated at
|
|
119
|
+
* the repeated variable, returning the variable, matching the codebase's other deep resolver
|
|
120
|
+
* `resolveTermDeep`. The evaluator filters a cyclic binding afterward via `hasLoop`;
|
|
121
|
+
* - a fully resolved (untruncated) expression node is memoized by object identity, so a DAG-shared value
|
|
122
|
+
* subterm is resolved once, not once per path, which also bounds memory (no path expansion).
|
|
123
|
+
*
|
|
124
|
+
* `suffix` scopes a rule RHS's variables: a template `$x` resolves as `name<suffix>`, and an unbound one
|
|
125
|
+
* becomes the freshened `name<suffix>`. A value pulled from the binding set already carries its final
|
|
126
|
+
* names, so it and everything reached through it resolves with no suffix.
|
|
127
|
+
*/
|
|
128
|
+
declare function instantiate(b: Bindings, a: Atom, suffix?: string, intern?: InternTable): Atom;
|
|
129
|
+
|
|
130
|
+
/** Rename every variable in `a` to `%N`, N assigned in first-occurrence order per `map` (shared across a
|
|
131
|
+
* whole `canonicalize` call so repeat occurrences of the same variable get the same placeholder). Exported
|
|
132
|
+
* for tabling's moded (non-ground) cache keys: two calls that are the same up to which concrete variable
|
|
133
|
+
* names they happen to use canonicalize to the same atom, and `map`'s insertion order (`[...map.keys()]`)
|
|
134
|
+
* recovers which original name became which `%N`, needed to freshen a cached answer back to a new call's
|
|
135
|
+
* actual names. `memo` is a per-call cache (fresh map, so per-call use only): within one canonicalize
|
|
136
|
+
* call, a variable already in `map` always renames the same way, so a shared expr node (instantiate
|
|
137
|
+
* shares unchanged subterms by reference) needs walking only once, not once per incoming path — the same
|
|
138
|
+
* DAG-vs-tree reasoning as instantiate/occursThrough/atomEq elsewhere in this package. */
|
|
139
|
+
declare function canonicalize(a: Atom, map: Map<string, string>, memo?: Map<Atom, Atom>): Atom;
|
|
140
|
+
declare function alphaEq(a: Atom, b: Atom): boolean;
|
|
141
|
+
|
|
142
|
+
type TokenConstructor = (token: string) => Atom;
|
|
143
|
+
declare class Tokenizer {
|
|
144
|
+
private readonly entries;
|
|
145
|
+
/** Register a (regex, constructor). Order matters: the first matching pattern wins. */
|
|
146
|
+
register(re: RegExp, make: TokenConstructor): void;
|
|
147
|
+
/** A grounded atom for `token`, or undefined if no pattern matches (caller falls back to Symbol). */
|
|
148
|
+
tokenize(token: string): Atom | undefined;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
interface TopAtom {
|
|
152
|
+
readonly atom: Atom;
|
|
153
|
+
readonly bang: boolean;
|
|
154
|
+
}
|
|
155
|
+
declare const isWs: (c: string) => boolean;
|
|
156
|
+
declare const isDelim: (c: string) => boolean;
|
|
157
|
+
declare const isWordBodyDelim: (c: string, word: string) => boolean;
|
|
158
|
+
/** Top-level `!` dispatches evaluation only when it is the exact `!` token. A word that merely begins with
|
|
159
|
+
* `!`, such as `!foo` or `!!foo`, is a symbol. */
|
|
160
|
+
declare function isBangQueryPrefixAt(s: string, pos: number): boolean;
|
|
161
|
+
/** Advance past whitespace and `;` line comments starting at `pos`; returns the new index. Shared by the
|
|
162
|
+
* plain parser (via `Cursor`) and the spanned CST parser, so the two cannot disagree on trivia. */
|
|
163
|
+
declare function skipTrivia(s: string, pos: number): number;
|
|
164
|
+
/** Read a `"..."` string literal starting at the opening quote index `start`. Returns the grounded String
|
|
165
|
+
* atom, the index just past the closing quote (or end-of-input when unterminated), and whether a closing
|
|
166
|
+
* quote was found. Inverse of `format`'s JSON.stringify output. Shared by the plain parser (which throws on
|
|
167
|
+
* `terminated === false`) and the recovering spanned CST parser (which records a diagnostic instead). */
|
|
168
|
+
declare function readStringAt(s: string, start: number): {
|
|
169
|
+
atom: Atom;
|
|
170
|
+
end: number;
|
|
171
|
+
terminated: boolean;
|
|
172
|
+
};
|
|
173
|
+
declare const MAX_DEPTH = 4096;
|
|
174
|
+
/** Turn a bare word (already extracted, no delimiters) into its atom: a `$`-word is a variable, otherwise
|
|
175
|
+
* the tokenizer decides, falling back to a Symbol. Shared by the plain and spanned parsers. */
|
|
176
|
+
declare function leafAtom(word: string, tk: Tokenizer): Atom;
|
|
177
|
+
declare function parse(src: string, tk: Tokenizer): Atom | undefined;
|
|
178
|
+
/** Parse a whole program into its sequence of top-level atoms. */
|
|
179
|
+
declare function parseAll(src: string, tk: Tokenizer): TopAtom[];
|
|
180
|
+
/** Print an atom back to MeTTa source (inverse of parse for normalized input). */
|
|
181
|
+
declare function format(a: Atom): string;
|
|
182
|
+
|
|
183
|
+
interface Space {
|
|
184
|
+
add(atom: Atom): void;
|
|
185
|
+
/** Remove the first structurally-equal atom; returns whether one was removed. */
|
|
186
|
+
remove(atom: Atom): boolean;
|
|
187
|
+
/** All binding sets under which `pattern` matches a stored atom. `freshen`, if given, is applied
|
|
188
|
+
* to each stored atom before matching (rule-variable freshening). */
|
|
189
|
+
query(pattern: Atom, freshen?: (a: Atom) => Atom): Bindings[];
|
|
190
|
+
atoms(): readonly Atom[];
|
|
191
|
+
}
|
|
192
|
+
/** In-memory space with a symbol-head index for ordinary expression queries. */
|
|
193
|
+
declare class InMemorySpace implements Space {
|
|
194
|
+
private readonly store;
|
|
195
|
+
private readonly byHead;
|
|
196
|
+
private readonly unindexed;
|
|
197
|
+
add(atom: Atom): void;
|
|
198
|
+
remove(atom: Atom): boolean;
|
|
199
|
+
private indexedCandidates;
|
|
200
|
+
query(pattern: Atom, freshen?: (a: Atom) => Atom): Bindings[];
|
|
201
|
+
atoms(): readonly Atom[];
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The standard tokenizer: integer/float literals and the `True`/`False` grounded booleans. */
|
|
205
|
+
declare function standardTokenizer(): Tokenizer;
|
|
206
|
+
/** The prelude's atoms (parsed once and cached). */
|
|
207
|
+
declare function preludeAtoms(): Atom[];
|
|
208
|
+
interface QueryResult {
|
|
209
|
+
readonly query: Atom;
|
|
210
|
+
readonly results: Atom[];
|
|
211
|
+
}
|
|
212
|
+
declare const DEFAULT_FUEL = 100000;
|
|
213
|
+
interface RunOptions {
|
|
214
|
+
readonly tabling?: boolean;
|
|
215
|
+
readonly experimental?: {
|
|
216
|
+
readonly hashCons?: boolean;
|
|
217
|
+
readonly flatAtomspace?: boolean;
|
|
218
|
+
readonly trail?: boolean;
|
|
219
|
+
readonly conjNested?: boolean;
|
|
220
|
+
readonly rangeIndex?: boolean;
|
|
221
|
+
readonly matchEvalMark?: boolean;
|
|
222
|
+
readonly directMatch?: boolean;
|
|
223
|
+
readonly staticCompact?: boolean;
|
|
224
|
+
};
|
|
225
|
+
readonly maxStackDepth?: number;
|
|
226
|
+
readonly trace?: TraceSink | undefined;
|
|
227
|
+
readonly parEvalImpl?: (rulesSrc: string, branchSrcs: string[], firstOnly: boolean) => (string[] | null)[];
|
|
228
|
+
readonly parEvalAsyncImpl?: (rulesSrc: string, branchSrcs: string[], firstOnly: boolean) => Promise<(string[] | null)[]>;
|
|
229
|
+
readonly hostImport?: HostImportFn;
|
|
230
|
+
}
|
|
231
|
+
/** Evaluate a parsed program sequentially. `imports` backs `import!` (pre-read by the caller). */
|
|
232
|
+
declare function evalSequential(atoms: readonly {
|
|
233
|
+
atom: Atom;
|
|
234
|
+
bang: boolean;
|
|
235
|
+
}[], fuel?: number, imports?: Map<string, Atom[]>, opts?: RunOptions): QueryResult[];
|
|
236
|
+
/** Evaluate every top-level directive, including non-`!` atoms as empty result directives. */
|
|
237
|
+
declare function evalSequentialAllDirectives(atoms: readonly {
|
|
238
|
+
atom: Atom;
|
|
239
|
+
bang: boolean;
|
|
240
|
+
}[], fuel?: number, imports?: Map<string, Atom[]>, opts?: RunOptions): QueryResult[];
|
|
241
|
+
/** Parse and run a MeTTa source string sequentially. */
|
|
242
|
+
declare function runProgram(src: string, fuel?: number, imports?: Map<string, Atom[]>, opts?: RunOptions): QueryResult[];
|
|
243
|
+
/** Parse and run a MeTTa source string, returning one result entry per top-level directive. */
|
|
244
|
+
declare function runProgramAllDirectives(src: string, fuel?: number, imports?: Map<string, Atom[]>, opts?: RunOptions): QueryResult[];
|
|
245
|
+
/** Async sequential evaluation: like `runProgram`, but `!`-queries are awaited, so async grounded
|
|
246
|
+
* operations (registered in `asyncOps`) can perform I/O. Sync programs give identical results to
|
|
247
|
+
* `runProgram`; the async path only differs when an async op is actually reached. */
|
|
248
|
+
declare function runProgramAsync(src: string, asyncOps?: Map<string, AsyncGroundFn>, fuel?: number, imports?: Map<string, Atom[]>, opts?: RunOptions): Promise<QueryResult[]>;
|
|
249
|
+
/** Module names referenced by top-level `import!` statements (so a caller can pre-read them). */
|
|
250
|
+
declare function collectImports(src: string): string[];
|
|
251
|
+
/** An oracle assertion passes iff its query evaluates to exactly the unit atom `()`. */
|
|
252
|
+
declare function isOraclePass(r: QueryResult): boolean;
|
|
253
|
+
/** Run a test file and report pass/fail counts and the failing queries. */
|
|
254
|
+
declare function oracleReport(src: string, fuel?: number, imports?: Map<string, Atom[]>): {
|
|
255
|
+
total: number;
|
|
256
|
+
passed: number;
|
|
257
|
+
failures: string[];
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
/** The `concurrency` module: timing/concurrency extensions (transaction, and later par/race/mutex). */
|
|
261
|
+
declare const CONCURRENCY_MODULE_SRC = "\n (: transaction (-> Atom %Undefined%))\n";
|
|
262
|
+
/** The `json` module: JSON encode/decode plus dict-space query helpers. */
|
|
263
|
+
declare const JSON_MODULE_SRC = "\n (: dict-space (-> Expression Grounded))\n (: json-encode (-> Atom String))\n (: json-decode (-> String Atom))\n (: get-keys (-> Grounded Atom))\n (: get-value (-> Grounded Atom %Undefined%))\n\n (@doc get-value\n (@desc \"Function takes space and key as input, checks if space contains key-value pairs in form of (key value) and returns value tied to the input key\")\n (@params (\n (@param \"Space\")\n (@param \"Key\")))\n (@return \"Value which tied to input key, empty if no such key in space\"))\n (= (get-value $dictspace $key) (unify $dictspace ($key $value) $value (empty)))\n\n (@doc get-keys\n (@desc \"Function takes space and returns all keys from (<key> <value>) tuples in space\")\n (@params (\n (@param \"Space\")))\n (@return \"All keys in the input space\"))\n (= (get-keys $dictspace)\n (function\n (chain (unify $dictspace ($key $value) $key Empty) $t (return $t)) ))\n\n (@doc dict-space\n (@desc \"Function takes key-value pairs in form of expression as input, creates space and adds key-value pairs into it\")\n (@params (\n (@param \"Expression\")))\n (@return \"Space\"))\n\n (@doc json-encode\n (@desc \"Function takes atom as an input and encodes it to json-string. Atom could be a string, number, expression, space and combination of those\")\n (@params (\n (@param \"Input atom\")))\n (@return \"Json string\"))\n\n (@doc json-decode\n (@desc \"Function takes json string as an input and decodes it to the metta objects (list to expression, dictionary to space which will contain key-value pairs in form of (key value), string to string, number to number)\")\n (@params (\n (@param \"Json string\")))\n (@return \"Metta object\"))\n";
|
|
264
|
+
/** Register a built-in module source resolvable via `(import! &self <name>)`. Reserved native names cannot be shadowed. */
|
|
265
|
+
declare function registerBuiltinModule(name: string, src: string): void;
|
|
266
|
+
/** The `catalog` module: module-catalog management (list/update/clear), mirroring hyperon-experimental.
|
|
267
|
+
* The operations are grounded (in builtins.ts) over a minimal in-memory catalog; this source supplies
|
|
268
|
+
* their type signatures and documentation. */
|
|
269
|
+
declare const CATALOG_MODULE_SRC = "\n (: catalog-list! (-> Symbol (->)))\n (: catalog-update! (-> Symbol (->)))\n (: catalog-clear! (-> Symbol (->)))\n\n (@doc catalog-list!\n (@desc \"Lists the contents of all module catalogs that support the list method\")\n (@params ((@param \"Name of the catalog to list, or all to list every available catalog\")))\n (@return \"Unit atom\"))\n (@doc catalog-update!\n (@desc \"Updates the contents of all managed catalogs to the latest version of all modules\")\n (@params ((@param \"Name of the catalog to update, or all to update every catalog\")))\n (@return \"Unit atom\"))\n (@doc catalog-clear!\n (@desc \"Clears the contents of all managed catalogs\")\n (@params ((@param \"Name of the catalog to clear, or all to clear every catalog\")))\n (@return \"Unit atom\"))\n";
|
|
270
|
+
/** The `fileio` module: opt-in host file IO for Node-like hosts. */
|
|
271
|
+
declare const FILEIO_MODULE_SRC = "\n (: FileHandle Type)\n (: file-open! (-> String String FileHandle))\n (: file-close! (-> FileHandle (->)))\n (: file-read-to-string! (-> FileHandle String))\n (: file-read-exact! (-> FileHandle Number String))\n (: file-write! (-> FileHandle String (->)))\n (: file-seek! (-> FileHandle Number (->)))\n (: file-get-size! (-> FileHandle Number))\n\n (@doc file-open!\n (@desc \"Function takes path to the file and open options r, w, c, a, t, both in form of string, creates filehandle and returns it\")\n (@params (\n (@param \"Filepath string atom\")\n (@param \"Open options string atom: r read, w write, c create if missing, a append to file, t truncate file\")))\n (@return \"Filehandle or error if combination of path and open options is wrong, for example file does not exist and no c option, or rc option provided since c demands w\"))\n\n (@doc file-read-to-string!\n (@desc \"Function takes filehandle provided by file-open! reads its content from current cursor place till the end of file and returns content in form of string.\")\n (@params (\n (@param \"Filehandle\")))\n (@return \"File's content\"))\n\n (@doc file-close!\n (@desc \"Closes a filehandle immediately. Dropped filehandles are also closed automatically.\")\n (@params (\n (@param \"Filehandle\")))\n (@return \"Unit atom\"))\n\n (@doc file-write!\n (@desc \"Function takes filehandle provided by file-open!, content to be written string atom and puts content into file associated with filehandle\")\n (@params (\n (@param \"Filehandle\")\n (@param \"Content string atom\")))\n (@return \"Unit atom\"))\n\n (@doc file-seek!\n (@desc \"Function takes filehandle provided by file-open! and desired cursor position number and sets cursor to provided position\")\n (@params (\n (@param \"Filehandle\")\n (@param \"Desired cursor position number\")))\n (@return \"Unit atom\"))\n\n (@doc file-read-exact!\n (@desc \"Function takes filehandle provided by file-open! and desired number of bytes to read number, reads content of file from current cursor position and returns it in form of string\")\n (@params (\n (@param \"Filehandle\")\n (@param \"Number of bytes to read\")))\n (@return \"File's content\"))\n\n (@doc file-get-size!\n (@desc \"Function takes filehandle provided by file-open! and returns size of file\")\n (@params (\n (@param \"Filehandle\")))\n (@return \"Size of file\"))\n";
|
|
272
|
+
/** The `git` module: opt-in host git imports for Node-like hosts. */
|
|
273
|
+
declare const GIT_MODULE_SRC = "\n (: GitImportOp Type)\n (: git-import! (-> String (->)))\n (: git-import! GitImportOp)\n\n (@doc git-import!\n (@desc \"Clones a git repository shallowly into the repos directory if it is not already present\")\n (@params (\n (@param \"Git repository URL or local path\")))\n (@return \"Unit atom, or Error atom if the host git capability is unavailable or cloning fails\"))\n";
|
|
274
|
+
/** The built-in extension modules, by the name used in `(import! &self <name>)`. */
|
|
275
|
+
declare function builtinModules(): Map<string, Atom[]>;
|
|
276
|
+
/** A fresh imports map seeded with the built-in extension modules, optionally merged with caller
|
|
277
|
+
* imports. Built-ins are only applied when a program actually `(import! ...)`s them, so this never
|
|
278
|
+
* affects the Hyperon oracle baseline. Built-in module names are reserved: a caller-supplied module of
|
|
279
|
+
* the same name does NOT override the built-in. */
|
|
280
|
+
declare function withBuiltinModules(extra?: Map<string, Atom[]>): Map<string, Atom[]>;
|
|
281
|
+
|
|
282
|
+
declare const STDLIB_SRC = "\n ; ---- Types of the grounded ops (math, bool, atom). Hyperon's grounded atoms carry their type\n ; intrinsically and `get-type` reads it; @metta-ts grounds these as host functions in builtins.ts,\n ; so the type signature is declared here to match. Values from hyperon-experimental math.rs/atom.rs\n ; (math ops are f64-valued, so e.g. pow-math/sqrt-math return Number; min-atom/max-atom take any\n ; expression, typed %Undefined% -> Number). The core arithmetic and comparison ops (+ - < == \u2026) are\n ; already declared in the prelude.\n (: pow-math (-> Number Number Number))\n (: sqrt-math (-> Number Number))\n (: abs-math (-> Number Number))\n (: log-math (-> Number Number Number))\n (: trunc-math (-> Number Number))\n (: ceil-math (-> Number Number))\n (: floor-math (-> Number Number))\n (: round-math (-> Number Number))\n (: sin-math (-> Number Number))\n (: asin-math (-> Number Number))\n (: cos-math (-> Number Number))\n (: acos-math (-> Number Number))\n (: tan-math (-> Number Number))\n (: atan-math (-> Number Number))\n (: isnan-math (-> Number Bool))\n (: isinf-math (-> Number Bool))\n (: min-atom (-> %Undefined% Number))\n (: max-atom (-> %Undefined% Number))\n (: sqrt (-> Number Number))\n (: sin (-> Number Number))\n (: cos (-> Number Number))\n (: exp (-> Number Number))\n (: log (-> Number Number Number))\n (: min (-> Number Number Number))\n (: max (-> Number Number Number))\n (: and (-> Bool Bool Bool))\n (: or (-> Bool Bool Bool))\n (: not (-> Bool Bool))\n (: xor (-> Bool Bool Bool))\n (: length (-> %Undefined% Number))\n (: first (-> %Undefined% Atom))\n (: last (-> %Undefined% Atom))\n (: reverse (-> %Undefined% Expression))\n (: msort (-> %Undefined% Expression))\n (: sort (-> %Undefined% Expression))\n (: list_to_set (-> %Undefined% Expression))\n (: second-from-pair (-> %Undefined% Atom))\n (: append (-> %Undefined% %Undefined% Expression))\n (: is-member (-> %Undefined% %Undefined% Bool))\n (: is-alpha-member (-> %Undefined% %Undefined% Bool))\n (: member (-> %Undefined% %Undefined% Bool))\n (: exclude-item (-> %Undefined% %Undefined% Expression))\n (: is-var (-> Atom Bool))\n (: is-ground (-> Atom Bool))\n (: is-expr (-> Atom Bool))\n (: is-space (-> Atom Bool))\n (: get-mettatype (-> Atom Atom))\n (: parse (-> String Atom))\n (: sread (-> String Atom))\n (: random-int (-> Number Number Number))\n (: random-float (-> Number Number Number))\n (: current-time (-> Number))\n (: metta-thread (-> Atom Atom Atom Atom))\n (: once (-> Atom %Undefined%))\n (: with-mutex (-> Atom Atom %Undefined%))\n (: with_mutex (-> Atom Atom %Undefined%))\n (: hyperpose (-> %Undefined% %Undefined%))\n\n ; sealed alpha-renames the variables of its second argument. That argument is Atom-typed so the\n ; body reaches sealed unevaluated (hyperon-experimental core.rs: (-> Expression Atom Atom)); without\n ; this the reduce loop would evaluate the body first, e.g. collapsing (== 1 $e) before renaming.\n (: sealed (-> Expression Atom Atom))\n\n ; ---- IO (host primitives grounded in builtins.ts) ----\n (: println! (-> %Undefined% (->)))\n (: print! (-> %Undefined% (->)))\n (: format-args (-> String Expression String))\n ; repr renders an atom's textual form. The argument is Atom-typed (not evaluated) so repr shows the\n ; atom as written; to repr a reduced form, evaluate it first (e.g. bind it with let).\n (: repr (-> Atom String))\n\n ; trace! prints its first argument and returns the (evaluated) second.\n (: trace! (-> %Undefined% Atom %Undefined%))\n (= (trace! $msg $ret) (let $unit (println! $msg) $ret))\n\n ; Partial application is ordinary PeTTa behavior. A known under-applied head becomes\n ; (partial head args); applying that closure rebuilds the fuller call and evaluates it.\n (: partial (-> Atom Expression Atom))\n (= ((partial $f $bound) $a)\n (let $args (append $bound ($a))\n (let $call (cons-atom $f $args) (metta $call %Undefined% &self))))\n (= ((partial $f $bound) $a $b)\n (let $args (append $bound ($a $b))\n (let $call (cons-atom $f $args) (metta $call %Undefined% &self))))\n\n ; Lambda heads are expressions, so they do not pass through the symbol-headed\n ; under-application hook above.\n (= ((|-> ($p1 $p2) $body) $a1)\n (partial (|-> ($p1 $p2) $body) ($a1)))\n (= ((|-> ($p1 $p2 $p3) $body) $a1)\n (partial (|-> ($p1 $p2 $p3) $body) ($a1)))\n (= ((|-> ($p1 $p2 $p3) $body) $a1 $a2)\n (partial (|-> ($p1 $p2 $p3) $body) ($a1 $a2)))\n\n ; PeTTa-compatible single-threaded wrapper. The async mutex is with-mutex; this spelling exists so PeTTa\n ; corpus examples can run on the synchronous runner where there is no concurrent mutation to protect.\n (= (with_mutex $name $body) (metta $body %Undefined% &self))\n\n ; include = import a module's contents into the current space.\n (: include (-> Atom %Undefined%))\n (= (include $module) (import! &self $module))\n\n ; ---- Error system ----\n (: ErrorType Type)\n (: ErrorDescription Type)\n (: IncorrectNumberOfArguments ErrorDescription)\n (: BadType (-> Type Type ErrorDescription))\n (: BadArgType (-> Number Type Type ErrorDescription))\n\n ; ---- Module system (minimal: @metta-ts resolves modules via import! into a space) ----\n (: module-space-no-deps (-> SpaceType SpaceType))\n (= (module-space-no-deps $s) $s)\n (: print-mods! (-> (->)))\n (= (print-mods!) ())\n (: git-module! (-> Atom (->)))\n (= (git-module! $url) (Error (git-module! $url) \"git-module! is not supported in @metta-ts\"))\n\n ; ---- Documentation system (ported from hyperon stdlib.metta) ----\n (: DocDescription Type)\n (: DocInformal Type)\n (: DocFormal Type)\n (: DocItem Type)\n (: DocKindFunction Type)\n (: DocKindAtom Type)\n (: DocType Type)\n (: DocParameters Type)\n (: DocParameter Type)\n (: DocParameterInformal Type)\n (: DocReturn Type)\n (: DocReturnInformal Type)\n (: @doc (-> Atom DocDescription DocInformal))\n (: @doc (-> Atom DocDescription DocParameters DocReturnInformal DocInformal))\n (: @desc (-> String DocDescription))\n (: @param (-> String DocParameterInformal))\n (: @param (-> DocType DocDescription DocParameter))\n (: @return (-> String DocReturnInformal))\n (: @return (-> DocType DocDescription DocReturn))\n (: @doc-formal (-> DocItem DocKindFunction DocType DocDescription DocParameters DocReturn DocFormal))\n (: @doc-formal DocFormal)\n (: @item (-> Atom DocItem))\n (: @kind (-> Atom DocKindFunction))\n (: @type (-> Type DocType))\n (: @params (-> Expression DocParameters))\n\n (= (get-doc-single-atom $space $atom)\n (let $type (get-type-space $space $atom)\n (if (is-function $type)\n (get-doc-function $space $atom $type)\n (get-doc-atom $space $atom) )))\n (= (get-doc-function $space $name $type)\n (unify $space (@doc $name $desc (@params $params) $ret)\n (let $type' (if (== $type %Undefined%) (undefined-doc-function-type $params) (cdr-atom $type))\n (let ($params' $ret') (get-doc-params $params $ret $type')\n (@doc-formal (@item $name) (@kind function) (@type $type) $desc (@params $params') $ret')))\n Empty ))\n (= (get-doc-atom $space $atom)\n (let $type (get-type-space $space $atom)\n (unify $space (@doc $atom $desc)\n (@doc-formal (@item $atom) (@kind atom) (@type $type) $desc)\n (unify $space (@doc $atom $desc' (@params $params) $ret)\n (get-doc-function $space $atom %Undefined%)\n Empty ))))\n (= (get-doc-params $params $ret $types)\n (let $head-type (car-atom $types)\n (let $tail-types (cdr-atom $types)\n (if (== () $params)\n (let (@return $ret-desc) $ret\n (() (@return (@type $head-type) (@desc $ret-desc))) )\n (let (@param $param-desc) (car-atom $params)\n (let $tail-params (cdr-atom $params)\n (let ($params' $result-ret) (get-doc-params $tail-params $ret $tail-types)\n (let $result-params (cons-atom (@param (@type $head-type) (@desc $param-desc)) $params')\n ($result-params $result-ret) ))))))))\n (= (undefined-doc-function-type $params)\n (if (== () $params) (%Undefined%)\n (let $params-tail (cdr-atom $params)\n (let $tail (undefined-doc-function-type $params-tail)\n (cons-atom %Undefined% $tail) ))))\n (= (help-param! $param)\n (let (@param (@type $type) (@desc $desc)) $param\n (println! (format-args \" {} {}\" ((type $type) $desc))) ))\n (: help-space! (-> SpaceType (->)))\n (= (help-space! $space)\n (let $_ (collapse\n (unify $space (@doc $name (@desc $desc) $params $ret)\n (let () (println! (format-args \"{} {}\" ($name $desc))) Empty)\n Empty )) ()))\n\n ; mod-space! loads a module into a fresh space and returns it.\n (: mod-space! (-> Atom SpaceType))\n (= (mod-space! $module) (let $s (new-space) (let $u (import! $s $module) $s)))\n\n ; ---- builtin documentation: @doc entries read by get-doc; descriptions from the hyperon stdlib ----\n (@doc + (@desc \"Sums two numbers\") (@params ((@param \"Addend\") (@param \"Augend\"))) (@return \"Sum\"))\n (@doc - (@desc \"Subtracts second argument from first one\") (@params ((@param \"Minuend\") (@param \"Deductible\"))) (@return \"Difference\"))\n (@doc * (@desc \"Multiplies two numbers\") (@params ((@param \"Multiplier\") (@param \"Multiplicand\"))) (@return \"Product\"))\n (@doc / (@desc \"Divides first argument by second one\") (@params ((@param \"Dividend\") (@param \"Divisor\"))) (@return \"Fraction\"))\n (@doc % (@desc \"Modulo operator. Returns the remainder of dividing the first argument by the second\") (@params ((@param \"Dividend\") (@param \"Divisor\"))) (@return \"Remainder\"))\n (@doc if (@desc \"Replaces itself by one of the arguments depending on the condition\") (@params ((@param \"Boolean condition\") (@param \"Result when condition is True\") (@param \"Result when condition is False\"))) (@return \"Second or third argument\"))\n (@doc car-atom (@desc \"Extracts the first atom of an expression as a tuple\") (@params ((@param \"Expression\"))) (@return \"First atom of an expression\"))\n (@doc cdr-atom (@desc \"Extracts the tail of an expression (all but the first atom)\") (@params ((@param \"Expression\"))) (@return \"Tail of an expression\"))\n (@doc match (@desc \"Searches a space (first argument) for atoms matching a pattern (second argument) and returns the output template (third argument)\") (@params ((@param \"Atomspace to search\") (@param \"Pattern atom to match\") (@param \"Output template, typically containing variables from the pattern\"))) (@return \"The template with matched variables filled, or Empty\"))\n (@doc get-type (@desc \"Returns the type notation of the input atom\") (@params ((@param \"Atom to get the type for\"))) (@return \"Type notation, or %Undefined% if the atom has no type\"))\n\n ; comparison and equality\n (@doc < (@desc \"Less than. Checks whether the first argument is less than the second\") (@params ((@param \"First number\") (@param \"Second number\"))) (@return \"True if the first argument is less than the second, False otherwise\"))\n (@doc <= (@desc \"Less than or equal. Checks whether the first argument is less than or equal to the second\") (@params ((@param \"First number\") (@param \"Second number\"))) (@return \"True if the first argument is less than or equal to the second, False otherwise\"))\n (@doc > (@desc \"Greater than. Checks whether the first argument is greater than the second\") (@params ((@param \"First number\") (@param \"Second number\"))) (@return \"True if the first argument is greater than the second, False otherwise\"))\n (@doc >= (@desc \"Greater than or equal. Checks whether the first argument is greater than or equal to the second\") (@params ((@param \"First number\") (@param \"Second number\"))) (@return \"True if the first argument is greater than or equal to the second, False otherwise\"))\n (@doc == (@desc \"Checks equality of two arguments of the same type\") (@params ((@param \"First argument\") (@param \"Second argument\"))) (@return \"True if the two arguments are equal, False otherwise\"))\n (@doc != (@desc \"Checks inequality of two arguments of the same type\") (@params ((@param \"First argument\") (@param \"Second argument\"))) (@return \"True if the two arguments are not equal, False otherwise\"))\n (@doc = (@desc \"Defines a reduction rule for expressions\") (@params ((@param \"Pattern to match against the expression to reduce\") (@param \"Result of reduction or transformation of the pattern\"))) (@return \"Not reduced itself unless custom equalities over equalities are added\"))\n (@doc =alpha (@desc \"Checks alpha equality of two expressions\") (@params ((@param \"First expression\") (@param \"Second expression\"))) (@return \"True if both expressions are alpha equal, False otherwise\"))\n\n ; boolean\n (@doc and (@desc \"Logical conjunction of two arguments\") (@params ((@param \"First argument\") (@param \"Second argument\"))) (@return \"True if both arguments are True, False otherwise\"))\n (@doc or (@desc \"Logical disjunction of two arguments\") (@params ((@param \"First argument\") (@param \"Second argument\"))) (@return \"True if any argument is True, False otherwise\"))\n (@doc xor (@desc \"Logical exclusive or\") (@params ((@param \"First argument\") (@param \"Second argument\"))) (@return \"True if exactly one input is True\"))\n (@doc not (@desc \"Logical negation\") (@params ((@param \"Argument\"))) (@return \"The negated boolean input\"))\n\n ; math\n (@doc abs-math (@desc \"Returns the absolute value of the input number\") (@params ((@param \"Input number\"))) (@return \"Absolute value\"))\n (@doc acos-math (@desc \"Returns the arccosine of the input value\") (@params ((@param \"Float number\"))) (@return \"Result of the arccosine function\"))\n (@doc asin-math (@desc \"Returns the arcsine of the input value\") (@params ((@param \"Float number\"))) (@return \"Result of the arcsine function\"))\n (@doc atan-math (@desc \"Returns the arctangent of the input value\") (@params ((@param \"Float number\"))) (@return \"Result of the arctangent function\"))\n (@doc ceil-math (@desc \"Returns the smallest integer greater than or equal to the input value\") (@params ((@param \"Float value\"))) (@return \"Integer greater than or equal to the input\"))\n (@doc cos-math (@desc \"Returns the cosine of the input value in radians\") (@params ((@param \"Angle in radians\"))) (@return \"Result of the cosine function\"))\n (@doc floor-math (@desc \"Returns the largest integer less than or equal to the input value\") (@params ((@param \"Float value\"))) (@return \"Integer less than or equal to the input\"))\n (@doc round-math (@desc \"Returns the nearest integer to the input float value\") (@params ((@param \"Float value\"))) (@return \"Nearest integer to the input\"))\n (@doc sin-math (@desc \"Returns the sine of the input value in radians\") (@params ((@param \"Angle in radians\"))) (@return \"Result of the sine function\"))\n (@doc sqrt-math (@desc \"Returns the square root of the input number\") (@params ((@param \"Input number\"))) (@return \"Result of the square root function\"))\n (@doc tan-math (@desc \"Returns the tangent of the input value in radians\") (@params ((@param \"Angle in radians\"))) (@return \"Result of the tangent function\"))\n (@doc trunc-math (@desc \"Returns the integer part of the input value\") (@params ((@param \"Float value\"))) (@return \"Integer part of the input\"))\n (@doc isinf-math (@desc \"Checks whether the input value is positive or negative infinity\") (@params ((@param \"Number\"))) (@return \"True or False\"))\n (@doc isnan-math (@desc \"Checks whether the input value is NaN\") (@params ((@param \"Number\"))) (@return \"True or False\"))\n (@doc log-math (@desc \"Returns the logarithm of a number given a base\") (@params ((@param \"Base\") (@param \"Input number\"))) (@return \"Result of the logarithm function\"))\n (@doc pow-math (@desc \"Returns the base raised to the given power\") (@params ((@param \"Base\") (@param \"Power\"))) (@return \"Result of the power function\"))\n (@doc sqrt (@desc \"Returns the square root of the input number\") (@params ((@param \"Input number\"))) (@return \"Square root\"))\n (@doc sin (@desc \"Returns the sine of the input value in radians\") (@params ((@param \"Angle in radians\"))) (@return \"Sine of the input\"))\n (@doc cos (@desc \"Returns the cosine of the input value in radians\") (@params ((@param \"Angle in radians\"))) (@return \"Cosine of the input\"))\n (@doc exp (@desc \"Returns e raised to the input number\") (@params ((@param \"Input number\"))) (@return \"Exponential value\"))\n (@doc log (@desc \"Returns the logarithm of a number in a base\") (@params ((@param \"Base\") (@param \"Input number\"))) (@return \"Logarithm\"))\n (@doc min (@desc \"Returns the smaller of two numbers\") (@params ((@param \"First number\") (@param \"Second number\"))) (@return \"Smaller number\"))\n (@doc max (@desc \"Returns the larger of two numbers\") (@params ((@param \"First number\") (@param \"Second number\"))) (@return \"Larger number\"))\n\n ; list and expression\n (@doc cons-atom (@desc \"Constructs an expression from a head and a tail\") (@params ((@param \"Head of the expression\") (@param \"Tail of the expression\"))) (@return \"New expression with the head prepended to the tail\"))\n (@doc decons-atom (@desc \"Splits a non-empty expression into its head and tail\") (@params ((@param \"Expression\"))) (@return \"Deconstructed expression as head and tail\"))\n (@doc index-atom (@desc \"Returns the atom at the given index of an expression, or an error if out of bounds\") (@params ((@param \"Expression\") (@param \"Index\"))) (@return \"Atom at the index, or an error\"))\n (@doc size-atom (@desc \"Returns the size of an expression\") (@params ((@param \"Expression\"))) (@return \"Size of the expression\"))\n (@doc filter-atom (@desc \"Keeps the atoms of a list that satisfy a predicate\") (@params ((@param \"List of atoms\") (@param \"Variable\") (@param \"Filter predicate\"))) (@return \"Filtered list\"))\n (@doc map-atom (@desc \"Evaluates a template for each atom in a list\") (@params ((@param \"List of atoms\") (@param \"Variable name\") (@param \"Template using the variable\"))) (@return \"List of results\"))\n (@doc foldl-atom (@desc \"Folds an operation across a list from an initial value\") (@params ((@param \"List of values\") (@param \"Initial value\") (@param \"Variable\") (@param \"Variable\") (@param \"Operation\"))) (@return \"Result of folding the operation across the list\"))\n (@doc for-each-in-atom (@desc \"Applies a function to each atom in an expression\") (@params ((@param \"Expression whose atoms the function is applied to\") (@param \"Function to apply\"))) (@return \"Unit atom\"))\n (@doc atom-subst (@desc \"Substitutes a variable in a template with a value\") (@params ((@param \"Value to substitute in\") (@param \"Variable to replace\") (@param \"Template containing the variable\"))) (@return \"The template with the variable substituted\"))\n (@doc length (@desc \"Returns the number of atoms in an expression\") (@params ((@param \"Expression\"))) (@return \"Number of atoms\"))\n (@doc first (@desc \"Returns the first atom in a non-empty expression\") (@params ((@param \"Expression\"))) (@return \"First atom\"))\n (@doc last (@desc \"Returns the last atom in a non-empty expression\") (@params ((@param \"Expression\"))) (@return \"Last atom\"))\n (@doc reverse (@desc \"Returns the atoms of an expression in reverse order\") (@params ((@param \"Expression\"))) (@return \"Reversed expression\"))\n (@doc msort (@desc \"Sorts an expression by standard atom order, preserving duplicates\") (@params ((@param \"Expression\"))) (@return \"Sorted expression\"))\n (@doc sort (@desc \"Sorts an expression by standard atom order and removes duplicate atoms\") (@params ((@param \"Expression\"))) (@return \"Sorted expression with duplicates removed\"))\n (@doc list_to_set (@desc \"Removes duplicate atoms from an expression, preserving first occurrences\") (@params ((@param \"Expression\"))) (@return \"Expression with duplicates removed\"))\n (@doc append (@desc \"Concatenates two expressions\") (@params ((@param \"First expression\") (@param \"Second expression\"))) (@return \"Concatenated expression\"))\n (@doc member (@desc \"Succeeds with True when an atom is a member of an expression\") (@params ((@param \"Atom to search for\") (@param \"Expression to search\"))) (@return \"True if the atom is present, otherwise Empty\"))\n (@doc is-member (@desc \"Checks whether an atom is a member of an expression\") (@params ((@param \"Atom to search for\") (@param \"Expression to search\"))) (@return \"True if the atom is present, False otherwise\"))\n (@doc is-alpha-member (@desc \"Checks whether an atom is alpha-equal to a member of an expression\") (@params ((@param \"Atom to search for\") (@param \"Expression to search\"))) (@return \"True if an alpha-equal atom is present, False otherwise\"))\n (@doc exclude-item (@desc \"Returns an expression with every occurrence of an atom removed\") (@params ((@param \"Atom to remove\") (@param \"Expression to filter\"))) (@return \"Filtered expression\"))\n (@doc second-from-pair (@desc \"Returns the second atom of a pair\") (@params ((@param \"Pair\"))) (@return \"Second atom of the pair\"))\n\n ; set operations\n (@doc union (@desc \"Returns the union of two nondeterministic inputs\") (@params ((@param \"Nondeterministic set of values\") (@param \"Another nondeterministic set of values\"))) (@return \"Union of the sets\"))\n (@doc intersection (@desc \"Returns the intersection of two nondeterministic inputs\") (@params ((@param \"Nondeterministic set of values\") (@param \"Another nondeterministic set of values\"))) (@return \"Intersection of the sets\"))\n (@doc subtraction (@desc \"Returns the subtraction of two nondeterministic inputs\") (@params ((@param \"Nondeterministic set of values\") (@param \"Another nondeterministic set of values\"))) (@return \"Subtraction of the sets\"))\n (@doc union-atom (@desc \"Returns the union of two tuples\") (@params ((@param \"List of values\") (@param \"List of values\"))) (@return \"Union of the tuples\"))\n (@doc intersection-atom (@desc \"Returns the intersection of two tuples\") (@params ((@param \"List of values\") (@param \"List of values\"))) (@return \"Intersection of the tuples\"))\n (@doc subtraction-atom (@desc \"Returns the subtraction of two tuples\") (@params ((@param \"List of values\") (@param \"List of values\"))) (@return \"Subtraction of the tuples\"))\n (@doc unique (@desc \"Returns only the unique values from a nondeterministic input\") (@params ((@param \"Nondeterministic set of values\"))) (@return \"Unique values\"))\n (@doc unique-atom (@desc \"Returns only the unique values from a tuple\") (@params ((@param \"List of values\"))) (@return \"Unique values\"))\n (@doc min-atom (@desc \"Returns the minimum value in an expression of numbers\") (@params ((@param \"Expression of Number atoms\"))) (@return \"Minimum value, or an error if the expression is non-numeric or empty\"))\n (@doc max-atom (@desc \"Returns the maximum value in an expression of numbers\") (@params ((@param \"Expression of Number atoms\"))) (@return \"Maximum value, or an error if the expression is non-numeric or empty\"))\n\n ; control flow\n (@doc if-equal (@desc \"Checks whether the first two arguments are equal and evaluates the third if so, the fourth otherwise\") (@params ((@param \"First argument\") (@param \"Second argument\") (@param \"Evaluated if equal\") (@param \"Evaluated if not equal\"))) (@return \"The evaluated third or fourth argument\"))\n (@doc if-error (@desc \"Checks whether the first argument is an error and returns the second if so, the third otherwise\") (@params ((@param \"Atom to check for an error\") (@param \"Value if the first is an error\") (@param \"Value otherwise\"))) (@return \"The second or third argument\"))\n (@doc return-on-error (@desc \"Returns the first argument if it is Empty or an error, the second otherwise\") (@params ((@param \"Previous evaluation result\") (@param \"Atom for further evaluation\"))) (@return \"The previous result if it is an error or Empty, otherwise the second argument\"))\n (@doc if-decons-expr (@desc \"Deconstructs a non-empty expression into head and tail and evaluates a template, or a default otherwise\") (@params ((@param \"Expression to deconstruct\") (@param \"Head variable\") (@param \"Tail variable\") (@param \"Template if the expression is non-empty\") (@param \"Default otherwise\"))) (@return \"The template with head and tail, or the default\"))\n (@doc case (@desc \"Tests pattern-matching conditions for a value in sequence\") (@params ((@param \"Atom to evaluate\") (@param \"Tuple of pattern-to-result pairs\"))) (@return \"The result of the first matching condition\"))\n (@doc switch (@desc \"Tests pattern-matching conditions for a value in sequence\") (@params ((@param \"Atom to match against the patterns\") (@param \"Tuple of pattern-to-result pairs\"))) (@return \"The result for the first matching pattern\"))\n (@doc switch-internal (@desc \"Tests one case of a switch and recurses if the condition is not met\") (@params ((@param \"Atom to evaluate\") (@param \"Deconsed tuple of pattern-to-result pairs\"))) (@return \"The result of the matched condition\"))\n (@doc let (@desc \"Unifies the first two arguments and evaluates the third under the resulting bindings\") (@params ((@param \"First atom to unify\") (@param \"Second atom to unify, evaluated first\") (@param \"Expression evaluated if the two unify\"))) (@return \"The third argument, or Empty\"))\n (@doc let* (@desc \"Sequentially unifies a list of pairs, then evaluates a body\") (@params ((@param \"List of pairs of atoms to unify\") (@param \"Expression evaluated if every pair unifies\"))) (@return \"The body, or Empty\"))\n (@doc id (@desc \"Returns its argument unchanged\") (@params ((@param \"Input argument\"))) (@return \"The input argument\"))\n (@doc noeval (@desc \"Returns its argument unevaluated\") (@params ((@param \"Input argument\"))) (@return \"The input argument\"))\n (@doc noreduce-eq (@desc \"Checks equality of two atoms without reducing them\") (@params ((@param \"First atom\") (@param \"Second atom\"))) (@return \"True if the unreduced atoms are equal, False otherwise\"))\n\n ; minimal MeTTa\n (@doc eval (@desc \"Performs one step of evaluation of the input atom\") (@params ((@param \"Atom to evaluate, reducible by an equality or a grounded call\"))) (@return \"Result of one evaluation step\"))\n (@doc evalc (@desc \"Performs one step of evaluation of the input atom in the context of a space\") (@params ((@param \"Atom to evaluate\") (@param \"Space to evaluate the atom in\"))) (@return \"Result of one evaluation step\"))\n (@doc chain (@desc \"Evaluates the first argument, binds it to the variable, then evaluates the template\") (@params ((@param \"Atom to evaluate\") (@param \"Variable\") (@param \"Atom evaluated at the end\"))) (@return \"Result of evaluating the template\"))\n (@doc unify (@desc \"Matches the first two arguments and returns the third if they match, the fourth otherwise\") (@params ((@param \"First atom to unify\") (@param \"Second atom to unify\") (@param \"Result if they match\") (@param \"Result otherwise\"))) (@return \"The third argument if matched, otherwise the fourth\"))\n (@doc function (@desc \"Evaluates its argument until it becomes a return, then reduces to the returned value\") (@params ((@param \"Atom to evaluate\"))) (@return \"Result of the atom's evaluation\"))\n (@doc return (@desc \"Returns a value from an enclosing function expression\") (@params ((@param \"Value to return\"))) (@return \"The passed argument\"))\n (@doc collapse-bind (@desc \"Evaluates the atom and returns all alternative evaluations as atom-and-bindings pairs\") (@params ((@param \"Minimal MeTTa operation to evaluate\"))) (@return \"All alternative evaluations\"))\n (@doc superpose-bind (@desc \"Puts a list of atom-and-bindings results back into the interpreter plan\") (@params ((@param \"Expression of atom-and-bindings pairs\"))) (@return \"Nondeterministic list of atoms\"))\n (@doc metta (@desc \"Runs the MeTTa interpreter on an atom\") (@params ((@param \"Atom to interpret\") (@param \"Expected type of the atom\") (@param \"Space to interpret the atom in\"))) (@return \"Result of interpretation\"))\n (@doc metta-thread (@desc \"Runs the MeTTa interpreter on an atom and threads its bindings into the current evaluation\") (@params ((@param \"Atom to interpret\") (@param \"Expected type of the atom\") (@param \"Space to interpret the atom in\"))) (@return \"Result of interpretation\"))\n\n ; spaces and matching\n (@doc add-atom (@desc \"Adds an atom to a space without reducing it\") (@params ((@param \"Space to add the atom to\") (@param \"Atom to add\"))) (@return \"Unit atom\"))\n (@doc remove-atom (@desc \"Removes an atom from a space\") (@params ((@param \"Space to remove the atom from\") (@param \"Atom to remove\"))) (@return \"Unit atom\"))\n (@doc add-atoms (@desc \"Adds the atoms of an expression to a space without reducing them\") (@params ((@param \"Space\") (@param \"Expression of atoms to add\"))) (@return \"Unit atom\"))\n (@doc add-reduct (@desc \"Reduces an atom and adds the result to a space\") (@params ((@param \"Space to add the atom to\") (@param \"Atom to reduce and add\"))) (@return \"Unit atom\"))\n (@doc add-reducts (@desc \"Reduces the atoms of an expression and adds the results to a space\") (@params ((@param \"Space\") (@param \"Expression to reduce and add\"))) (@return \"Unit atom\"))\n (@doc get-atoms (@desc \"Returns all atoms in a space\") (@params ((@param \"Reference to the space\"))) (@return \"List of all atoms in the space\"))\n (@doc new-space (@desc \"Creates a new atomspace usable as a separate space from &self\") (@params ()) (@return \"Reference to a new space\"))\n (@doc context-space (@desc \"Returns the space used as the context in atom evaluation\") (@params ()) (@return \"The context space\"))\n\n ; state monad\n (@doc new-state (@desc \"Creates a new state atom wrapping its argument\") (@params ((@param \"Atom to wrap\"))) (@return \"A state wrapping the argument\"))\n (@doc get-state (@desc \"Returns the atom wrapped by a state\") (@params ((@param \"State\"))) (@return \"Atom wrapped by the state\"))\n (@doc change-state! (@desc \"Replaces the wrapped atom of a state with a new value\") (@params ((@param \"State created by new-state\") (@param \"Atom to replace the wrapped atom\"))) (@return \"State with the replaced atom\"))\n\n ; nondeterminism and quoting\n (@doc superpose (@desc \"Turns a tuple into a nondeterministic result\") (@params ((@param \"Tuple to convert\"))) (@return \"The argument as a nondeterministic result\"))\n (@doc hyperpose (@desc \"Turns an expression into nondeterministic results\") (@params ((@param \"Expression to convert\"))) (@return \"The expression items as nondeterministic results\"))\n (@doc collapse (@desc \"Converts a nondeterministic result into a tuple\") (@params ((@param \"Atom to evaluate\"))) (@return \"Tuple\"))\n (@doc once (@desc \"Evaluates an atom and keeps only its first result\") (@params ((@param \"Atom to evaluate\"))) (@return \"First result, or Empty if there is no result\"))\n (@doc quote (@desc \"Prevents an atom from being reduced\") (@params ((@param \"Atom\"))) (@return \"Quoted atom\"))\n (@doc unquote (@desc \"Unquotes a quoted atom\") (@params ((@param \"Quoted atom\"))) (@return \"Unquoted atom\"))\n (@doc sealed (@desc \"Replaces every variable in an atom with a unique variable, except those to ignore\") (@params ((@param \"Variable list to ignore\") (@param \"Atom that uses the variables\"))) (@return \"The atom with its variables made unique\"))\n (@doc capture (@desc \"Wraps an atom and captures the current space\") (@params ((@param \"Function name whose space to capture\"))) (@return \"Function\"))\n (@doc with-mutex (@desc \"Evaluates a body while holding a mutex with the given name\") (@params ((@param \"Mutex name\") (@param \"Body to evaluate\"))) (@return \"Body result\"))\n (@doc with_mutex (@desc \"PeTTa-compatible single-threaded wrapper that evaluates its body\") (@params ((@param \"Mutex name\") (@param \"Body to evaluate\"))) (@return \"Body result\"))\n\n ; IO and misc\n (@doc println! (@desc \"Prints a line of text to the console\") (@params ((@param \"Expression or atom to print\"))) (@return \"Unit atom\"))\n (@doc print! (@desc \"Prints text to the console without adding a newline\") (@params ((@param \"Expression or atom to print\"))) (@return \"Unit atom\"))\n (@doc trace! (@desc \"Prints the first argument and returns the second; both are evaluated\") (@params ((@param \"Atom to print\") (@param \"Atom to return\"))) (@return \"The evaluated second argument\"))\n (@doc repr (@desc \"Returns the textual representation of an atom\") (@params ((@param \"Atom to render\"))) (@return \"String representation\"))\n (@doc format-args (@desc \"Fills the placeholders in a string with atoms from an expression\") (@params ((@param \"String with placeholders to replace\") (@param \"Atoms to place into the string\"))) (@return \"The string with placeholders replaced\"))\n (@doc parse (@desc \"Parses a string of MeTTa source and returns its first atom\") (@params ((@param \"Source string\"))) (@return \"First parsed atom, or the empty expression if the string has no atoms\"))\n (@doc sread (@desc \"Parses a string of MeTTa source and returns its first atom\") (@params ((@param \"Source string\"))) (@return \"First parsed atom, or the empty expression if the string has no atoms\"))\n (@doc current-time (@desc \"Returns the current Unix time in seconds\") (@params ()) (@return \"Current Unix time\"))\n (@doc random-float (@desc \"Returns a random float in the half-open interval from the lower bound to the upper bound\") (@params ((@param \"Lower bound\") (@param \"Upper bound\"))) (@return \"Random float\"))\n (@doc random-int (@desc \"Returns a random integer in the half-open interval from the lower bound to the upper bound\") (@params ((@param \"Lower bound\") (@param \"Upper bound\"))) (@return \"Random integer\"))\n (@doc nop (@desc \"Outputs the unit atom\") (@params ()) (@return \"Unit atom\"))\n (@doc pragma! (@desc \"Changes the value of a global key, such as type-check, interpreter, or max-stack-depth\") (@params ((@param \"Key name\") (@param \"New value\"))) (@return \"Unit atom\"))\n (@doc bind! (@desc \"Registers a token replaced by an atom during parsing of the rest of the program\") (@params ((@param \"Token name\") (@param \"Atom associated with the token after reduction\"))) (@return \"Unit atom\"))\n (@doc sort-strings (@desc \"Sorts an expression of strings in alphabetical order\") (@params ((@param \"List of strings\"))) (@return \"Sorted list of strings\"))\n (@doc first-from-pair (@desc \"Returns the first atom of a pair\") (@params ((@param \"Pair\"))) (@return \"First atom of the pair\"))\n ; empty is intentionally not documented: it cuts its own evaluation branch, so an @doc-formal mentioning it\n ; reduces to an Error rather than the record. The catalog describes it instead.\n\n ; type introspection\n (@doc get-type-space (@desc \"Returns the type notation of an atom relative to a specified space\") (@params ((@param \"Space to search for the type\") (@param \"Atom to get the type for\"))) (@return \"Type notation, or %Undefined% if the atom has no type in the space\"))\n (@doc get-metatype (@desc \"Returns the metatype of the input atom\") (@params ((@param \"Atom to get the metatype for\"))) (@return \"The metatype of the input atom\"))\n (@doc is-var (@desc \"Checks whether the input atom is a variable\") (@params ((@param \"Atom to check\"))) (@return \"True if the atom is a variable, False otherwise\"))\n (@doc is-ground (@desc \"Checks whether the input atom contains no variables\") (@params ((@param \"Atom to check\"))) (@return \"True if the atom contains no variables, False otherwise\"))\n (@doc is-expr (@desc \"Checks whether the input atom is an expression\") (@params ((@param \"Atom to check\"))) (@return \"True if the atom is an expression, False otherwise\"))\n (@doc is-space (@desc \"Checks whether the input atom is a space reference\") (@params ((@param \"Atom to check\"))) (@return \"True if the atom is a space reference, False otherwise\"))\n (@doc get-mettatype (@desc \"Returns the implementation metatype of the input atom\") (@params ((@param \"Atom to inspect\"))) (@return \"Variable, Grounded, Expression, or Symbol\"))\n (@doc is-function (@desc \"Checks whether the input type is a function type\") (@params ((@param \"Type atom\"))) (@return \"True if the type is a function type, False otherwise\"))\n (@doc match-types (@desc \"Unifies two types and returns the third argument if they unify, the fourth otherwise\") (@params ((@param \"First type\") (@param \"Second type\") (@param \"Returned if the types unify\") (@param \"Returned if the types do not unify\"))) (@return \"The third or fourth argument\"))\n (@doc match-type-or (@desc \"Unifies two types and ORs the result with a boolean\") (@params ((@param \"Boolean value\") (@param \"First type\") (@param \"Second type\"))) (@return \"True or False\"))\n (@doc type-cast (@desc \"Casts an atom to a type using a space as context\") (@params ((@param \"Atom to cast\") (@param \"Type to cast to\") (@param \"Context space\"))) (@return \"The atom if the cast succeeds, otherwise a BadType error\"))\n\n ; documentation system\n (@doc @doc (@desc \"Stores informal documentation for a symbol\"))\n (@doc @desc (@desc \"Wraps documentation text\"))\n (@doc @param (@desc \"Wraps a parameter description\"))\n (@doc @params (@desc \"Wraps the informal parameter list\"))\n (@doc @return (@desc \"Wraps a return description\"))\n (@doc @type (@desc \"Wraps a type annotation in formal documentation\"))\n (@doc @item (@desc \"Wraps the documented item name\"))\n (@doc @kind (@desc \"Wraps the documented item kind\"))\n (@doc @doc-formal (@desc \"Represents documentation after get-doc has attached kinds, types, params, and return info\"))\n (@doc get-doc (@desc \"Returns documentation for an atom or function\") (@params ((@param \"Atom or function name to document\"))) (@return \"Documentation for the atom or function\"))\n (@doc get-doc-atom (@desc \"Gets documentation for a non-function atom\") (@params ((@param \"Space to search for documentation\") (@param \"Atom name to document\"))) (@return \"Documentation for the atom\"))\n (@doc get-doc-single-atom (@desc \"Gets documentation for either a function or an atom, dispatching on which it is\") (@params ((@param \"Space to search for documentation\") (@param \"Atom or function name to document\"))) (@return \"Documentation for the atom or function\"))\n (@doc get-doc-function (@desc \"Gets documentation for a function, or default documentation if none exists\") (@params ((@param \"Space to search for documentation\") (@param \"Function name to document\") (@param \"Type notation for the function\"))) (@return \"Documentation for the function\"))\n (@doc get-doc-params (@desc \"Builds a function's parameter and return documentation, each augmented with its type\") (@params ((@param \"List of parameter descriptions\") (@param \"Return description\") (@param \"Type notation without the leading arrow\"))) (@return \"United list of parameters and return, each with its type\"))\n (@doc undefined-doc-function-type (@desc \"Builds a placeholder type list for a function with no type notation\") (@params ((@param \"List of parameters for the function\"))) (@return \"A list of %Undefined% types sized to the parameters\"))\n (@doc help! (@desc \"Prints documentation for an atom or module; with no argument prints the corelib functions\") (@params ((@param \"Atom or module to document\"))) (@return \"Unit atom\"))\n (@doc help-param! (@desc \"Prints a single parameter's documentation, used by help!\") (@params ((@param \"Parameter to print\"))) (@return \"Unit atom\"))\n (@doc help-space! (@desc \"Prints documentation for every atom in a space\") (@params ((@param \"Space to document\"))) (@return \"Unit atom\"))\n\n ; assertions\n (@doc assertEqual (@desc \"Compares the results of evaluating two expressions\") (@params ((@param \"First expression\") (@param \"Second expression\"))) (@return \"Unit atom if the results are equal, an error otherwise\"))\n (@doc assertAlphaEqual (@desc \"Compares the results of evaluating two expressions using alpha equality\") (@params ((@param \"First expression\") (@param \"Second expression\"))) (@return \"Unit atom if the results are alpha equal, an error otherwise\"))\n (@doc assertEqualToResult (@desc \"Compares the results of evaluating the first expression to the unevaluated second expression\") (@params ((@param \"First expression, evaluated\") (@param \"Second expression with the expected results, not evaluated\"))) (@return \"Unit atom if equal, an error otherwise\"))\n (@doc assertAlphaEqualToResult (@desc \"Alpha-compares the results of evaluating the first expression to the unevaluated second\") (@params ((@param \"First expression, evaluated\") (@param \"Second expression, not evaluated\"))) (@return \"Unit atom if alpha equal, an error otherwise\"))\n (@doc assertEqualMsg (@desc \"Compares the results of evaluating two expressions, returning a message on failure\") (@params ((@param \"First expression\") (@param \"Second expression\") (@param \"Message to return on failure\"))) (@return \"Unit atom if equal, the message otherwise\"))\n (@doc assertAlphaEqualMsg (@desc \"Alpha-compares the results of evaluating two expressions, returning a message on failure\") (@params ((@param \"First expression\") (@param \"Second expression\") (@param \"Message to return on failure\"))) (@return \"Unit atom if alpha equal, the message otherwise\"))\n (@doc assertEqualToResultMsg (@desc \"Compares evaluation results to an unevaluated expected value, returning a message on failure\") (@params ((@param \"First expression, evaluated\") (@param \"Second expression, not evaluated\") (@param \"Message to return on failure\"))) (@return \"Unit atom if equal, the message otherwise\"))\n (@doc assertAlphaEqualToResultMsg (@desc \"Alpha-compares evaluation results to an unevaluated expected value, returning a message on failure\") (@params ((@param \"First expression, evaluated\") (@param \"Second expression, not evaluated\") (@param \"Message to return on failure\"))) (@return \"Unit atom if alpha equal, the message otherwise\"))\n (@doc assertIncludes (@desc \"Checks that the second argument is included in the results of evaluating the first\") (@params ((@param \"First expression\") (@param \"Second expression\"))) (@return \"Unit atom if included, an error otherwise\"))\n\n ; errors\n (@doc Error (@desc \"Constructs an error atom\") (@params ((@param \"Atom that failed\") (@param \"Error description\"))) (@return \"Error atom\"))\n (@doc BadType (@desc \"Constructs an error description for an expected type and an actual type\") (@params ((@param \"Expected type\") (@param \"Actual type\"))) (@return \"BadType error description\"))\n (@doc BadArgType (@desc \"Constructs an error description for an argument with the wrong type\") (@params ((@param \"Argument position\") (@param \"Expected type\") (@param \"Actual type\"))) (@return \"BadArgType error description\"))\n (@doc ErrorType (@desc \"Type of error atoms\"))\n (@doc SpaceType (@desc \"Type of atomspace references\"))\n (@doc ErrorDescription (@desc \"Type of values that describe an error\"))\n (@doc IncorrectNumberOfArguments (@desc \"Error description used when a function is called with the wrong number of arguments\"))\n\n ; modules\n (@doc import! (@desc \"Imports a module by relative path, binding it to a token; &self imports into the current space\") (@params ((@param \"Symbol turned into the token for the imported space\") (@param \"Module name or relative path\"))) (@return \"Unit atom\"))\n (@doc include (@desc \"Includes a MeTTa script into the current space, like import! with &self\") (@params ((@param \"Name of the MeTTa script to include\"))) (@return \"Unit atom\"))\n (@doc register-module! (@desc \"Loads a module into the runner from a file system path\") (@params ((@param \"File system path\"))) (@return \"Unit atom\"))\n (@doc mod-space! (@desc \"Returns the space of a module, loading the module if it is not yet loaded\") (@params ((@param \"Module name\"))) (@return \"The module's space\"))\n (@doc module-space-no-deps (@desc \"Returns a module space without its dependencies\") (@params ((@param \"Module space\"))) (@return \"The space without its included dependencies\"))\n (@doc print-mods! (@desc \"Prints all modules with their corresponding spaces\") (@params ()) (@return \"Unit atom\"))\n (@doc git-module! (@desc \"Returns an error because git modules are not supported in @metta-ts\") (@params ((@param \"Git module URL\"))) (@return \"Unsupported-module error\"))\n";
|
|
283
|
+
/** The standard-library evaluation atoms: type declarations and function definitions, without the @doc
|
|
284
|
+
* documentation data. Loaded by the runner into every program's space. The @doc atoms are held separately
|
|
285
|
+
* (stdlibDocAtoms) so a program that never calls get-doc does not pay to load 185 documentation atoms into
|
|
286
|
+
* its space; that load is ~+22% of the stdlib-load microbenchmark. Parsed once and cached. */
|
|
287
|
+
declare function stdlibAtoms(): Atom[];
|
|
288
|
+
/** The standard-library `@doc` documentation atoms, consulted by get-doc as a fallback when a symbol is not
|
|
289
|
+
* documented in the program's own space. Kept out of the eval environment. Parsed once and cached. */
|
|
290
|
+
declare function stdlibDocAtoms(): Atom[];
|
|
291
|
+
|
|
292
|
+
/** A frequent subpattern and its compression economics. */
|
|
293
|
+
interface HeavyPattern {
|
|
294
|
+
/** The repeated subpattern (decoded for inspection). */
|
|
295
|
+
readonly pattern: Atom;
|
|
296
|
+
/** How many times it occurs across the KB. */
|
|
297
|
+
readonly count: number;
|
|
298
|
+
/** Its size in tokens. */
|
|
299
|
+
readonly len: number;
|
|
300
|
+
/** Tokens saved by factoring it: `(count - 1) * len - count * refCost`. */
|
|
301
|
+
readonly gain: number;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* The top-`k` heaviest repeated subpatterns in `kb`, by compression gain. `refCost` is the token cost of
|
|
305
|
+
* a reference to a factored definition (MORK starts at ~4–8). Only subpatterns occurring ≥2 times with
|
|
306
|
+
* positive gain are returned (single symbols never pay to factor). Brute-force and exact; the oracle
|
|
307
|
+
* for any future output-sensitive index.
|
|
308
|
+
*/
|
|
309
|
+
declare function williamTopK(kb: FlatKB, k: number, refCost?: number): HeavyPattern[];
|
|
310
|
+
|
|
311
|
+
declare class Trail {
|
|
312
|
+
private readonly binds;
|
|
313
|
+
private readonly trail;
|
|
314
|
+
/** A restore point: the current trail length. */
|
|
315
|
+
mark(): number;
|
|
316
|
+
/** Undo every binding made since `m`. */
|
|
317
|
+
undo(m: number): void;
|
|
318
|
+
/** Bind `$name` to `a` and record it on the trail. The caller guarantees `$name` is currently unbound. */
|
|
319
|
+
bind(name: string, a: Atom): void;
|
|
320
|
+
/** Follow variable bindings to the representative: a non-variable, or an unbound variable. */
|
|
321
|
+
deref(a: Atom): Atom;
|
|
322
|
+
/** The atom currently bound to `$name`, if any (the direct binding, not dereferenced). */
|
|
323
|
+
get(name: string): Atom | undefined;
|
|
324
|
+
/** Resolve `a` against the current bindings, one pass (the same discipline as the immutable
|
|
325
|
+
* `instantiate`/`applySubst`): a variable becomes its bound value as-is; the value's own variables are
|
|
326
|
+
* not re-resolved, and an expression's children are resolved. This matches the evaluator exactly,
|
|
327
|
+
* including that a cyclic binding (`$y = (.. $y ..)`, which `matchAtoms` produces and `hasLoop` does not
|
|
328
|
+
* reject) terminates instead of looping. A new term is built only where a child changed. */
|
|
329
|
+
resolve(a: Atom): Atom;
|
|
330
|
+
}
|
|
331
|
+
/** Unify two atoms against the trail, binding variables in place; returns whether they unify. On failure
|
|
332
|
+
* the trail may hold partial bindings, so callers undo to a mark. Mirrors the immutable matcher: a
|
|
333
|
+
* variable binds to the other side (no occurs check; `matchAtoms` admits cyclic bindings and the
|
|
334
|
+
* evaluator's one-pass `resolve` handles them, so adding one here would diverge), two symbols/grounded
|
|
335
|
+
* values must be equal, two expressions must have equal arity and unify pointwise. */
|
|
336
|
+
declare function unifyTrail(tr: Trail, l0: Atom, r0: Atom): boolean;
|
|
337
|
+
|
|
338
|
+
/** 0-based line and UTF-16 character offset, matching the LSP Position. MeTTa source offsets are
|
|
339
|
+
* JS string indices, which are already UTF-16 code units, so the mapping is direct. */
|
|
340
|
+
interface Position {
|
|
341
|
+
readonly line: number;
|
|
342
|
+
readonly character: number;
|
|
343
|
+
}
|
|
344
|
+
interface Range {
|
|
345
|
+
readonly start: Position;
|
|
346
|
+
readonly end: Position;
|
|
347
|
+
}
|
|
348
|
+
declare enum DiagnosticSeverity {
|
|
349
|
+
Error = 1,
|
|
350
|
+
Warning = 2,
|
|
351
|
+
Information = 3,
|
|
352
|
+
Hint = 4
|
|
353
|
+
}
|
|
354
|
+
/** rustc's confidence tiers for a suggested fix. Phase 1 records the tier; applying the fix is later work. */
|
|
355
|
+
declare enum Applicability {
|
|
356
|
+
MachineApplicable = "machine-applicable",
|
|
357
|
+
MaybeIncorrect = "maybe-incorrect",
|
|
358
|
+
HasPlaceholders = "has-placeholders"
|
|
359
|
+
}
|
|
360
|
+
interface Suggestion {
|
|
361
|
+
readonly span: Range;
|
|
362
|
+
readonly replacement: string;
|
|
363
|
+
readonly applicability: Applicability;
|
|
364
|
+
readonly message: string;
|
|
365
|
+
}
|
|
366
|
+
/** A secondary labeled span or a spanless note/help line (rustc's sub-diagnostics; LSP relatedInformation
|
|
367
|
+
* without the URI, which the server adds). */
|
|
368
|
+
interface RelatedInformation {
|
|
369
|
+
readonly range?: Range;
|
|
370
|
+
readonly message: string;
|
|
371
|
+
}
|
|
372
|
+
interface Diagnostic {
|
|
373
|
+
readonly range: Range;
|
|
374
|
+
readonly severity: DiagnosticSeverity;
|
|
375
|
+
readonly code: string;
|
|
376
|
+
readonly message: string;
|
|
377
|
+
readonly relatedInformation?: readonly RelatedInformation[];
|
|
378
|
+
readonly suggestions?: readonly Suggestion[];
|
|
379
|
+
}
|
|
380
|
+
/** Map a source string index to a 0-based line/character position. */
|
|
381
|
+
declare function offsetToPosition(src: string, offset: number): Position;
|
|
382
|
+
/** Build an LSP Range from two source string indices. */
|
|
383
|
+
declare function spanToRange(src: string, start: number, end: number): Range;
|
|
384
|
+
|
|
385
|
+
/** Levenshtein edit distance between two strings (two-row dynamic programming). */
|
|
386
|
+
declare function levenshtein(a: string, b: string): number;
|
|
387
|
+
declare class FuzzyMatcher {
|
|
388
|
+
private readonly terms;
|
|
389
|
+
constructor(terms: Iterable<string>);
|
|
390
|
+
/** Known names within edit distance of `query`, closest first. Returns [] for queries shorter than
|
|
391
|
+
* 3 characters (too noisy) or with no term inside the distance bound. The bound scales with query
|
|
392
|
+
* length: 1 edit for short names, 2 for longer, matching the tolerance rustc/compilers use. */
|
|
393
|
+
suggest(query: string, maxDistance?: number): string[];
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
interface Span {
|
|
397
|
+
readonly start: number;
|
|
398
|
+
readonly end: number;
|
|
399
|
+
}
|
|
400
|
+
/** Syntactic classification of a leaf or expression node, for editor tokenization. It is derived from the
|
|
401
|
+
* atom, so it is consistent with what the node parses to: a `number` node carries a grounded int/float, a
|
|
402
|
+
* `variable` a Variable, and everything else (including `True`/`False`) a `symbol`. */
|
|
403
|
+
type CstNodeKind = "expr" | "symbol" | "variable" | "string" | "number";
|
|
404
|
+
/** One CST node: the atom it parses to, a syntactic kind, its source range, and, for expressions, the
|
|
405
|
+
* child nodes plus the paren spans. `bang`/`bangSpan` mark a top-level `!`-query and the `!` itself. An
|
|
406
|
+
* expression parsed by end-of-input recovery has no `close`. Comments are not atoms and live in
|
|
407
|
+
* `Cst.comments`, not in the tree. */
|
|
408
|
+
interface SpannedNode {
|
|
409
|
+
readonly atom: Atom;
|
|
410
|
+
readonly kind: CstNodeKind;
|
|
411
|
+
readonly span: Span;
|
|
412
|
+
readonly children?: readonly SpannedNode[];
|
|
413
|
+
readonly bang?: boolean;
|
|
414
|
+
readonly bangSpan?: Span;
|
|
415
|
+
readonly open?: Span;
|
|
416
|
+
readonly close?: Span;
|
|
417
|
+
}
|
|
418
|
+
/** A `;` line comment's source range (its text is `src.slice(span.start, span.end)`). */
|
|
419
|
+
interface CstComment {
|
|
420
|
+
readonly span: Span;
|
|
421
|
+
}
|
|
422
|
+
/** LSP DiagnosticSeverity values, so a server can forward these without a mapping table. */
|
|
423
|
+
type CstSeverity = 1 | 2;
|
|
424
|
+
/** A recovery diagnostic: a source range, a stable code, a message, and a severity. */
|
|
425
|
+
interface CstDiagnostic {
|
|
426
|
+
readonly span: Span;
|
|
427
|
+
readonly code: string;
|
|
428
|
+
readonly message: string;
|
|
429
|
+
readonly severity: CstSeverity;
|
|
430
|
+
}
|
|
431
|
+
/** The whole parse: top-level nodes (atom-bearing, `!`-marked), the comments, and any recovery diagnostics
|
|
432
|
+
* (empty for well-formed source). */
|
|
433
|
+
interface Cst {
|
|
434
|
+
readonly nodes: readonly SpannedNode[];
|
|
435
|
+
readonly comments: readonly CstComment[];
|
|
436
|
+
readonly diagnostics: readonly CstDiagnostic[];
|
|
437
|
+
}
|
|
438
|
+
/** Parse a whole program into a recovering CST. Never throws. */
|
|
439
|
+
declare function parseCst(src: string, tk: Tokenizer): Cst;
|
|
440
|
+
/** Parse a whole program into spanned top-level nodes, dropping comments and recovery diagnostics. Kept for
|
|
441
|
+
* callers that only need the atom tree (the static analyzer); prefer `parseCst` for editor use. Recovers
|
|
442
|
+
* rather than throwing, so a partial tree is returned for malformed input. */
|
|
443
|
+
declare function parseAllSpanned(src: string, tk: Tokenizer): SpannedNode[];
|
|
444
|
+
|
|
445
|
+
interface DiagnoseConfig {
|
|
446
|
+
/** Enable the undefined-head near-miss check. Off by default: MeTTa's ADD-mode makes an unknown
|
|
447
|
+
* head legal (added to the space as data), so this heuristic must be opted into. */
|
|
448
|
+
readonly undefinedSymbols: boolean;
|
|
449
|
+
}
|
|
450
|
+
/** Analyze a parsed program. Returns diagnostics deduplicated by (position, code) and sorted by position. */
|
|
451
|
+
declare function analyze(src: string, cst: readonly SpannedNode[], env: MinEnv, config: DiagnoseConfig): Diagnostic[];
|
|
452
|
+
/** Parse `src`, build the standard env (prelude + stdlib + petta + the program's own atoms), and analyze. */
|
|
453
|
+
declare function analyzeSource(src: string, config: DiagnoseConfig): Diagnostic[];
|
|
454
|
+
|
|
455
|
+
/** Render one diagnostic as a multi-line rustc-style frame. */
|
|
456
|
+
declare function renderDiagnostic(src: string, filename: string, d: Diagnostic): string;
|
|
457
|
+
/** Render every diagnostic, separated by a blank line. */
|
|
458
|
+
declare function renderAll(src: string, filename: string, ds: readonly Diagnostic[]): string;
|
|
459
|
+
|
|
460
|
+
export { Applicability, AsyncGroundFn, Atom, Bindings, CATALOG_MODULE_SRC, CONCURRENCY_MODULE_SRC, type Cst, type CstComment, type CstDiagnostic, type CstNodeKind, type CstSeverity, DEFAULT_FUEL, type DiagnoseConfig, type Diagnostic, DiagnosticSeverity, FILEIO_MODULE_SRC, FlatKB, FuzzyMatcher, GIT_MODULE_SRC, type GroundMatcher, type HeavyPattern, HostImportFn, IMPURE_OPS, InMemorySpace, InternTable, JSON_MODULE_SRC, MAX_DEPTH, MODED_IMPURE_OPS, MinEnv, type Position, type QueryResult, type Range, type RelatedInformation, type Relation, type RunOptions, STDLIB_SRC, type Space, type Span, type SpannedNode, type Subst, type Suggestion, type TokenConstructor, Tokenizer, type TopAtom, TraceSink, Trail, type WcoFoldHooks, addVarBinding, addVarEquality, alphaEq, analyze, analyzePurity, analyzeSource, analyzeTableWorth, applySubst, bindingsToSubst, builtinModules, canonicalize, collectImports, emptySubst, eraseSubst, evalSequential, evalSequentialAllDirectives, extendSubst, format, functorCallCount, instantiate, isBangQueryPrefixAt, isDelim, isOraclePass, isTablingImpureHead, isWordBodyDelim, isWs, keyWellFormed, leafAtom, levenshtein, lookupSubst, matchAtoms, matchAtomsScoped, matchAtomsWith, merge, occurs, offsetToPosition, oracleReport, parse, parseAll, parseAllSpanned, parseCst, preludeAtoms, readStringAt, registerBuiltinModule, renderAll, renderDiagnostic, runProgram, runProgramAllDirectives, runProgramAsync, skipTrivia, spanToRange, standardTokenizer, stdlibAtoms, stdlibDocAtoms, unifiable, unifyTop, unifyTrail, wcoJoin, wcoJoinFold, williamTopK, withBuiltinModules };
|