mathjslab
Version:
MathJSLab - An interpreter with language syntax like MATLAB®/Octave, ISBN 978-65-00-82338-7.
2,375 lines • 95.7 kB
TypeScript
/**
* MATLAB®/Octave like syntax parser/interpreter/compiler.
*/
import type { NodeInput, NodeExpr, NodeFunctionDefinition, NodeBuiltInFunction, AliasNameTable, BuiltInFunctionTable, CommandWordListTable, ExpressionBoundaryValue } from './AST';
import { ClassDefinition } from './ClassDefinition';
import { ClassInstance } from './ClassInstance';
import { ClassStaticMethod } from './ClassStaticMethod';
import { Scope } from './Scope';
import { CallFrame } from './CallFrame';
import type { SourceEntry, SourceProvider, SourceResolver, SourceTable } from './SourceResolver';
import { Context } from './Context';
import { CircularReferenceError, EvalError, InterpreterError, ReferenceError, SyntaxError, UndefinedReferenceError } from './InterpreterError';
import type { CallArgumentValue } from './FunctionCall';
/**
* Numeric exit status used by the public `exitStatus` property.
*/
type ExitStatus = number;
/** Named exit status table. */
type ExitStatusValues = Record<string, ExitStatus>;
/** Host-provided class source entry. */
type ClassSource = SourceEntry;
/** Host-provided function-file source entry. */
type FunctionSource = SourceEntry;
/** Host-provided script-file source entry. */
type ScriptSource = SourceEntry;
/** Callback used to provide classdef source for a class name. */
type ClassSourceProvider = SourceProvider;
/** Table of host-provided class sources keyed by class name. */
type ClassSourceTable = SourceTable;
/** Callback used to provide function-file source for a function name. */
type FunctionSourceProvider = SourceProvider;
/** Table of host-provided function-file sources keyed by primary function name. */
type FunctionSourceTable = SourceTable;
/** Callback used to provide script-file source for a script name. */
type ScriptSourceProvider = SourceProvider;
/** Table of host-provided script-file sources keyed by script name. */
type ScriptSourceTable = SourceTable;
/**
* Interpreter construction options.
*
* All extension points are explicit so the engine remains browser-compatible:
* callers can inject aliases, built-ins, command-form functions, and class
* sources without requiring ambient filesystem or module loading.
*/
type InterpreterConfig = {
/** Lexer/parser alias table for symbolic names. */
aliasNameTable?: AliasNameTable;
/** Additional built-in functions registered at startup. */
externalFunctionTable?: BuiltInFunctionTable;
/** Additional command-form functions registered at startup. */
externalCmdWListTable?: CommandWordListTable;
/** Unified virtual `.m` source resolver. */
sourceResolver?: SourceResolver;
/** Host predicate used by `mustBeFile` argument/property validation. */
fileExists?: (path: string) => boolean;
/** Host predicate used by `mustBeFolder` argument/property validation. */
folderExists?: (path: string) => boolean;
/** Host-provided function-file source strings. */
functionSourceTable?: FunctionSourceTable;
/** Lazy host-provided function-file source callback. */
functionSourceProvider?: FunctionSourceProvider;
/** Host-provided script-file source strings. */
scriptSourceTable?: ScriptSourceTable;
/** Lazy host-provided script-file source callback. */
scriptSourceProvider?: ScriptSourceProvider;
/** Host-provided class source strings. */
classSourceTable?: ClassSourceTable;
/** Lazy host-provided class source callback. */
classSourceProvider?: ClassSourceProvider;
/**
* Compatibility alias for early class-loader experiments. Prefer
* `classSourceTable` for browser/host-provided class sources.
*/
externalClassSourceTable?: Record<string, string>;
/**
* Compatibility alias for early function-loader experiments. Prefer
* `functionSourceTable` for browser/host-provided function sources.
*/
externalFunctionSourceTable?: Record<string, string>;
/**
* Compatibility alias for early script-loader experiments. Prefer
* `scriptSourceTable` for browser/host-provided script sources.
*/
externalScriptSourceTable?: Record<string, string>;
};
/**
* Increment and decrement operator handler type.
*/
type IncDecOperator = (tree: NodeExpr, scope: Scope) => NodeInput;
/**
* Full parse/evaluate/unparse bundle returned by `Interprets`.
*/
type InterpretsResult = {
/** Original input string. */
input: string;
/** AST produced from the original input. */
inputParsed: NodeInput;
/** Textual unparse of the evaluated input. */
inputUnparsed: string;
/** MathML rendering of the evaluated input. */
inputUnparsedMathML: string;
/** Evaluated runtime value or AST result. */
evaluated: NodeInput;
/** Textual unparse of the evaluated result. */
evaluatedUnparsed: string;
/** MathML rendering of the evaluated result. */
evaluatedUnparsedMathML: string;
};
/**
* Interpreter instance interface.
*/
interface InterpreterInterface {
/** Whether debug diagnostics and fallback tracing are enabled. */
debug: boolean;
/** Runtime context owned by this interpreter. */
context: Context;
/** Last public execution status. */
exitStatus: ExitStatus;
/** Operator precedence table used by unparsers. */
precedenceTable: {
[key: string]: number;
};
/** Parse source text into an AST/runtime node. */
Parse(input: string): NodeInput;
/** Reset runtime state while preserving constructor-level configuration defaults. */
Restart(): void;
/** Clear variables/functions, or reset the interpreter when no names are supplied. */
Clear(...names: string[]): void;
/** Evaluate one AST/runtime node in a scope. */
Evaluator(tree: NodeInput, scope?: Scope): NodeInput;
/** Evaluate one parsed AST from the public top-level entry point. */
Evaluate(tree: NodeInput): NodeInput;
/** Parse and evaluate source text in one call. */
Execute(input: string): NodeInput;
/** Convert a runtime/AST node back to normalized source-like text. */
Unparse(tree: NodeInput, parentPrecedence?: number): string;
/** Convert a runtime/AST node to a MathML fragment. */
UnparserMathML(tree: NodeInput, parentPrecedence: number): string;
/** Convert a runtime/AST node to a complete MathML string. */
UnparseMathML(tree: NodeInput, display: 'inline' | 'block' | 'none'): string;
/** Parse source text and render its AST as MathML. */
ToMathML(input: string, display: 'inline' | 'block' | 'none'): string;
/** Return parsed/evaluated/unparsed forms for host diagnostics and demos. */
Interprets(input: string, display: 'inline' | 'block' | 'none'): InterpretsResult;
}
/**
* MATLAB/Octave-like parser, evaluator, unparser, and host integration point.
*
* `Interpreter` owns the ANTLR parser pipeline, runtime context, built-in
* tables, command-form functions, class loading contracts, and display
* unparsers. Most semantic helpers are delegated to smaller modules; this
* class coordinates them around one active `Context`.
*/
declare class Interpreter implements InterpreterInterface {
/** MATLAB-compatible maximum identifier length exposed by `namelengthmax`. */
private static readonly nameLengthMax;
/** Sorted language keywords as recognized by the lexer. */
private static readonly keywordNames;
/** Keyword lookup set used by `iskeyword` and `isvarname`. */
private static readonly keywordNameSet;
/** Public MATLAB validator functions backed by the `arguments` validator engine. */
private static readonly publicArgumentValidators;
/**
* After run `Evaluate` method, the `exitStatus` property will contains
* exit state of evaluation.
*/
static readonly response: ExitStatusValues;
/**
* Private debug flag.
*/
private _debug;
/**
* `debug` getter.
*/
get debug(): boolean;
/**
* `debug` setter.
*/
set debug(value: boolean);
/**
* Interpreter context.
*/
context: Context;
/**
* Command word list table.
*/
private commandWordListTable;
private commandWordListNameSet;
private assignmentSensitiveCommandNameSet;
/** Operators that introduce or update assignment targets. */
private static readonly assignmentOperatorNames;
/**
* Unified virtual source resolver for browser/host-provided `.m` files.
*/
private sourceResolver;
/** Host path predicates used by MATLAB-style file/folder validators. */
private pathValidationCallbacks;
/**
* Refresh lexer-facing command-name sets after command table changes.
*/
private refreshCommandWordListNames;
/**
* Function names currently being loaded, used to avoid recursive loader loops.
*/
private loadingFunctionNames;
/**
* Class names currently being loaded, used to avoid recursive loader loops.
*/
private loadingClassNames;
/**
* Class method names currently being loaded, used to avoid recursive loader loops.
*/
private loadingClassMethodNames;
/**
* Nesting level of host-provided script execution.
*
* A script is not a function frame, but MATLAB/Octave still allow `return`
* to stop the current script. Keeping that state in the interpreter lets
* interactive/top-level `return` remain invalid while scripts loaded
* through the browser-safe source APIs can exit early.
*/
private scriptExecutionDepth;
/**
* Virtual source identities for currently executing scripts.
*
* Script-local functions are ordinary function definitions registered
* temporarily in the caller workspace; this stack lets that registration
* attach the surrounding script's browser-hosted source identity.
*/
private scriptSourceNameStack;
/**
* Interpreter exit status.
*/
private _exitStatus;
/**
* Last uncaught public evaluation error, exposed through `lasterror`.
*/
private lastError?;
/**
* Last warning state exposed through `lastwarn`.
*
* Warning emission is still intentionally conservative, but keeping the
* state here gives the public API a stable MATLAB/Octave-like contract.
*/
private lastWarning;
/**
* Global warning state used by `warning("on"|"off"|"error")`.
*/
private globalWarningState;
/**
* Per-identifier warning emission overrides.
*/
private warningIdentifierStates;
/**
* Interpreter exit status getter.
*/
get exitStatus(): ExitStatus;
/**
* Increment and decrement operator
* @param pre `true` if prefixed. `false` if postfixed.
* @param operation Operation (`'plus'` or `'minus'`).
* @returns Operator function that updates an assignable expression.
*/
private incDecOpFactory;
/**
* Operator table.
*/
private readonly opTable;
private static readonly binaryOperatorMethodTable;
private static readonly unaryOperatorMethodTable;
/**
* Precedence definitions.
*/
private static readonly precedence;
/**
* Operator precedence table.
*/
precedenceTable: {
[key: string]: number;
};
/**
* Get tree node precedence.
* @param tree Tree node.
* @returns Node precedence.
*/
private nodePrecedence;
/**
* User functions.
*/
private functionArityCallable;
private functionArgumentArity;
private functionOutputArity;
/**
* Parse or resolve a textual function-handle source.
*/
private functionHandleFromString;
/**
* Resolve a runtime symbol through the interpreter-owned lookup facade.
*
* Keeping this indirection inside `Interpreter` prevents parser/evaluator
* code from depending directly on the exact `Context.resolveSymbol` option
* shape and gives lookup-sensitive features one place to evolve.
*
* @param name Name requested by source text.
* @param scope Lookup scope.
* @param options Resolution switches.
* @returns Structured symbol resolution, if any.
*/
private resolveRuntimeSymbol;
/** Resolve a function-like runtime symbol without considering variables or classes. */
private resolveRuntimeFunction;
/** Resolve a class runtime symbol without considering variables or functions. */
private resolveRuntimeClass;
/**
* Create a named function handle using the current structured lookup layer.
*
* Qualified names and aliases are normalized to their runtime spelling.
* Simple imported names keep their source spelling and rely on the captured
* import table, matching MATLAB/Octave display behavior for `@name`.
* When requested, user-function handles keep a lexical overlay so returned
* handles remain bound to local/nested functions and in-scope imports.
*
* @param name Function name supplied by source text or a character string.
* @param scope Lookup scope used to resolve imports and local functions.
* @param parent Optional AST parent for the new handle.
* @param captureLexical Whether to capture a lexical overlay for user functions.
* @returns Named function handle.
*/
private createResolvedFunctionHandle;
private localFunctionHandles;
/**
* Copy and validate one captured workspace value before exposing it through
* the MATLAB/Octave `functions(handle).workspace` metadata struct.
*/
private functionHandleWorkspaceValue;
private functionHandleWorkspaceInfo;
private staticMethodInfo;
private dbstackResult;
/**
* Return the MATLAB/Octave `mfilename` value for the current function.
*
* When a browser-hosted source provides a virtual path, plain `mfilename`
* reports the file basename without the `.m` suffix while
* `mfilename("fullpath")` keeps the complete virtual identity.
*/
private currentMFilename;
/**
* Return the MATLAB/Octave `mfilename("fullpath")` identity.
*
* For browser-hosted code, "fullpath" means the complete virtual source
* identity supplied by the host resolver. Unlike plain `mfilename`, this
* intentionally keeps the configured `.m`-like suffix because source
* metadata, `functions`, and stack display share that identity.
*/
private currentMFilenameFullPath;
/**
* Return the best virtual source identity for a handle created now.
*/
private currentHandleSourceName;
/**
* Return the class context that should be captured by a handle created now.
*/
private currentHandleClassName;
/**
* Convert a native or interpreter error into the struct shape used by
* MATLAB/Octave-style `catch ME` and `lasterror`.
*
* `InterpreterError.stackFrames` stores the most recent frame first, while
* `dbstackResult` expects the live call-stack order and reverses it during
* formatting. The local reversal preserves the captured thrown stack instead
* of rebuilding it from the current catch/evaluation context.
*
* @param error Error object or thrown value.
* @returns Structure with `message`, `identifier`, and `stack` fields.
*/
private exceptionToStruct;
/**
* Return the current `lasterror` value.
*
* MATLAB/Octave keep the last uncaught error until it is replaced or the
* interpreter state is reset. When no error has escaped yet, the empty
* structure uses the same fields so callers can index it without special
* casing the initial state.
*
* @returns MATLAB-like last-error structure.
*/
private lastErrorStruct;
/**
* Return the default `lasterror` structure.
*/
private emptyLastErrorStruct;
/**
* Reset `lasterror` to its initial state.
*/
private resetLastError;
/**
* Store an error as the current MATLAB/Octave last-error state.
*
* Caught errors must be visible to `lasterr`/`lasterror` while the `catch`
* block executes, matching Octave's documented try/catch behavior and the
* legacy MATLAB diagnostic APIs.
*/
private rememberLastError;
/**
* Normalize a user-provided error structure for storage in `lasterror`.
*
* MATLAB/Octave accept structures with any subset of the public fields and
* fill missing fields with defaults. Present `message` and `identifier`
* fields must still be character values because they are consumed by
* `rethrow` and catch-state introspection.
*/
private normalizeLastErrorStruct;
/**
* Implement `lasterror`, `lasterror("reset")`, and `lasterror(err)`.
*/
private lastErrorResult;
/**
* Implement `lasterr`, the message/id companion to `lasterror`.
*/
private lastErrorMessageResult;
/**
* Store the warning state returned by `lastwarn`.
*
* @param message Warning message.
* @param identifier Optional warning identifier.
*/
private setLastWarning;
/**
* Reset warning state to the MATLAB/Octave default.
*/
private resetWarningState;
/**
* Return the effective warning state for an identifier.
*/
private warningState;
/**
* Test whether a string is a supported warning state.
*/
private isWarningState;
/**
* Build the structure returned by `warning("query", id)`.
*/
private warningStateStruct;
/**
* Build a MATLAB/Octave warning-state snapshot.
*
* The first element always represents the global `all` state. Additional
* entries record warning identifiers that differ from the global default or
* that were explicitly modified during this interpreter session, matching
* the save/restore workflow of `s = warning; warning(s)`.
*/
private warningStateSnapshot;
/**
* Read a MATLAB/Octave warning-state structure.
*/
private warningStateStructParts;
/**
* Restore one warning state entry.
*/
private restoreWarningState;
/**
* Restore warning state from a MATLAB/Octave-style structure scalar or array.
*/
private restoreWarningStateStruct;
/**
* Apply `warning` state/query commands when the argument pattern matches.
*/
private warningControlResult;
/**
* Split diagnostic arguments into optional identifier, format, and values.
*
* A leading string containing `:` is treated as a message identifier when a
* second string is present. Otherwise the first string is the message format.
*/
private diagnosticMessageParts;
/**
* Convert command-form diagnostic words to function-form arguments.
*
* `warning id:tag message words` and `error id:tag message words` map to
* identifier/message calls, while ordinary words map to one message string.
*/
private diagnosticCommandArguments;
/**
* Implement the public `warning` built-in subset.
*
* The current browser-first runtime records warning state instead of
* writing to a console or warning manager. This supports the common message
* and identifier/message forms, a small diagnostic formatting subset, and
* the common `on`/`off`/`query` state controls.
*
* @param args Evaluated built-in arguments.
* @returns Void node because warnings do not produce expression output.
*/
private warningResult;
/**
* Implement the public `error` built-in subset.
*
* Supported MATLAB/Octave forms are `error(message)`,
* `error(identifier, message)`, and formatted variants of those forms. The
* thrown error keeps the current call stack through `Context.throwEvalError`,
* and the optional identifier is attached for `catch ME` and `lasterror`.
*
* @param args Evaluated error arguments.
*/
private errorResult;
/**
* Decide whether an `assert` call is the condition/message form.
*/
private assertUsesDiagnosticForm;
/**
* Extract numeric elements for tolerance-based `assert` comparison.
*/
private assertNumericElements;
/**
* Test numerical equality using Octave-style absolute/relative tolerance.
*/
private assertValuesEqualWithinTolerance;
/**
* Split comparison-form `assert` arguments into comparison and diagnostic
* parts.
*/
private assertComparisonParts;
/**
* Implement `assert(actual, expected[, tolerance][, message...])`.
*/
private assertComparisonResult;
/**
* Implement the public `assert` built-in subset.
*
* MATLAB/Octave treat a false condition as an error and pass the remaining
* arguments through the same identifier/format pipeline used by `error`.
*/
private assertResult;
/**
* Extract MATLAB text-list arguments accepted by validation functions.
*
* The documented APIs accept a character vector, string scalar, string
* array, or cell array of character vectors. The interpreter stores each as
* `CharString` elements, so this helper normalizes the public forms without
* losing order.
*/
private validationTextList;
/**
* Extract one text item from a mixed MATLAB validation cell array.
*/
private validationTextItem;
/**
* Return raw validation-list items, preserving non-text parameters.
*/
private validationListItems;
/**
* Implement MATLAB's unique-prefix, case-insensitive `validatestring`.
*/
private validatestringResult;
/**
* Build the optional function/variable context used by `validatestring`.
*/
private validatestringDiagnosticPrefix;
/**
* Map public `validateattributes` attribute names to shared validator keys.
*/
private validateattributesValidator;
/**
* Return dimensions as `validateattributes` should see them.
*
* The runtime stores both character vectors and string scalars in
* `CharString`; MATLAB treats string scalars as `1x1`, while character
* vectors remain `1xN`.
*/
private validateattributesDimensions;
/**
* Return real numeric elements for attributes that inspect values directly.
*/
private validateattributesRealNumericElements;
/**
* Extract a real numeric scalar used as a `validateattributes` parameter.
*/
private validateattributesNumericScalar;
/**
* Extract a real numeric vector used by `validateattributes('size', ...)`.
*/
private validateattributesNumericVector;
/**
* Test all numeric elements of a value against a scalar comparison.
*/
private validateattributesNumericComparison;
/**
* Test MATLAB/Octave monotonic attributes independently for each stored
* column. `MultiArray` stacks pages in the physical row axis, so each
* page-stride row group represents the rows of one logical page.
*/
private validateattributesMonotonicColumns;
/**
* Test non-parameterized `validateattributes` attributes not covered by the
* shared validator table.
*/
private validateattributesSpecialAttribute;
/**
* Test one shared `validateattributes` validator with public string-scalar
* shape semantics.
*/
private validateattributesMatchesValidator;
/**
* Apply one parameterized `validateattributes` attribute.
*/
private validateattributesParameterizedAttribute;
/**
* Build the subject text used by `validateattributes` diagnostics.
*/
private validateattributesSubject;
/**
* Test a `validateattributes` class constraint against runtime values.
*/
private validateattributesMatchesClass;
/**
* Implement the common MATLAB/Octave `validateattributes` forms.
*
* The browser runtime has no sparse storage type; sparse-compatible APIs are
* kept explicit through the shared validator, where `sparse` always fails
* and `nonsparse` always succeeds.
*/
private validateattributesResult;
/**
* Return supported public `mustBe*` call arity limits.
*/
private mustBeArity;
/**
* Implement public MATLAB `mustBe*` validator functions.
*/
private mustBeResult;
/**
* Build registry entries for public `mustBe*` validators.
*/
private mustBeFunctionEntries;
/**
* Normalize command-form results returned by host-provided integrations.
*
* External command handlers often return plain JavaScript primitives. The
* interpreter boundary converts those values into ordinary runtime nodes so
* command-form parsing can be used safely by browser-hosted commands such
* as `help`.
*/
private commandWordListResult;
/**
* Implement `rethrow(ME)` for MATLAB/Octave-style caught error structs.
*
* The current runtime represents `catch ME` as a structure with `message`,
* `identifier`, and `stack` fields. `rethrow` validates that shape and
* raises a new evaluation error while preserving the public message and
* identifier fields used by subsequent `catch` blocks and `lasterror`.
*
* @param errorStruct Error structure captured by a `catch` identifier.
*/
private rethrowResult;
/**
* Implement `lastwarn` getter/setter behavior.
*
* With no arguments it returns the current message and identifier. With one
* or two string arguments it updates the stored warning state before
* returning it, matching the MATLAB/Octave convention used by tests and
* user code.
*
* @param args Optional message and identifier setter arguments.
* @returns Comma-separated return list `[message, identifier]`.
*/
private lastWarningResult;
/**
* Implement MATLAB/Octave `deal` output distribution.
*
* With one input, every requested output receives that value. With multiple
* inputs, a scalar-output call returns the first value; multiple-output
* calls must match the input count and distribute values positionally.
*/
private dealResult;
/**
* Read one positive integer index for output-selection helpers.
*/
private positiveIntegerIndex;
/**
* Read scalar or vector output indexes for `nthargout`.
*/
private nthargoutIndexes;
/**
* Resolve the callable argument accepted by `nthargout`.
*/
private nthargoutCallable;
/**
* Implement Octave-compatible `nthargout`.
*/
private nthargoutResult;
/**
* Validate one evaluated value before exposing it as an ordinary expression.
*/
private expressionValue;
/**
* Validate an evaluated value that must be stored in runtime data
* containers such as structures.
*/
private runtimeExpressionValue;
/**
* Evaluate an expression, reduce return-list carriers, and validate the
* resulting value before it crosses an interpreter expression boundary.
*/
private evaluatedExpressionValue;
/**
* Evaluate one executable AST node and normalize lazy return-list carriers.
*
* This is intentionally broader than `evaluatedExpressionValue`: block and
* top-level execution may legitimately produce `LIST`, `VOID`, or control
* carrier nodes that are not ordinary expression values.
*/
private evaluatedExecutionResult;
/**
* Read a scope entry and validate it before reusing it as an expression.
*/
private scopedExpressionValue;
/**
* Read a scope entry that must contain a native array value.
*/
private scopedMultiArrayValue;
/**
* Validate evaluated variadic call arguments before forwarding them.
*
* @param values Runtime arguments after ordinary evaluator reduction.
* @param prefix Diagnostic prefix used to identify the failing argument.
* @returns Arguments narrowed to expression values.
*/
private callArgumentValues;
/**
* Validate a built-in control argument that must be a character string.
*
* @param value Candidate argument.
* @param name Diagnostic role name.
* @returns Validated character string.
*/
private charControlArgument;
/**
* Validate a list whose elements must all be character strings.
*
* MATLAB Set/Get APIs accept property-name cell arrays. This helper keeps
* the cell-content validation explicit after `MultiArray.linearize`.
*
* @param values Candidate cell contents.
* @param name Diagnostic role name.
* @returns The same values narrowed to character strings.
*/
private charStringList;
/**
* Validate a built-in control argument that must be a function handle.
*
* @param value Candidate argument.
* @param name Diagnostic role name.
* @returns Validated function handle.
*/
private functionHandleControlArgument;
/**
* Validate an optional boolean-like control argument.
*
* @param value Candidate argument.
* @param name Diagnostic role name.
* @returns JavaScript boolean following MATLAB/Octave truthiness.
*/
private booleanControlArgument;
/**
* Validate worker-count expressions accepted by sequential parallel fallbacks.
*
* MATLAB requires `parfor(..., M)` to use a nonnegative integer worker
* limit. `spmd(n)` and `spmd(m,n)` use the same numeric count shape, with
* zero selecting local execution in environments without workers.
*
* @param value Evaluated worker-count expression.
* @param name Diagnostic role name.
* @returns Validated worker count.
*/
private workerCountControlArgument;
/**
* Validate runtime values before forwarding them to user-defined class methods.
*/
private classMethodArgumentValues;
/**
* Invoke one class instance method and reduce lazy return-list carriers at
* the class-dispatch boundary.
*/
private reducedClassMethodResult;
/**
* Invoke one class method with an explicit output count and reduce the
* scalar result expected by helper protocols such as `numArgumentsFromSubscript`.
*/
private reducedClassMethodResultWithOutputCount;
/**
* Validate the object returned by class `subsasgn` overloads.
*/
private classSubsasgnResult;
/**
* Normalize a value produced by assignment RHS evaluation before storing it
* into a name, field, or object property.
*/
private reducedAssignmentValue;
/**
* Normalize and validate an assignment RHS before storing it in a runtime
* structure field.
*/
private structureAssignmentValue;
/**
* Store a field-assignment value, scattering compound structure-array
* results when the operation produced one value per target element.
*/
private assignStructureFieldValue;
/**
* Reduce values produced by scalar indexing/dispatch paths before checking
* their runtime shape or class.
*/
private reducedIndexingResult;
/**
* Validate and linearize values before assigning them to object arrays.
*/
private assignmentValues;
/**
* Prepare a value for distribution across selected object-property paths.
*
* A tail descriptor means the assignment targets an indexed value inside
* each selected property. In that position `[]` is a scalar deletion value
* to apply per target, not a zero-length list to distribute.
*/
private classPropertyPathAssignmentValues;
/**
* Validate a sequence before storing it in an AST expression list.
*/
private expressionList;
/**
* Validate and linearize an expression value without crossing the generic
* `MathObject` operation surface.
*/
private linearExpressionValues;
/**
* Validate and copy one expression value through the runtime copy protocol.
*/
private copyExpressionValue;
/**
* Expand a `for` loop expression into the sequence assigned to the target.
*
* MATLAB/Octave `for` assignment iterates over columns. Numeric row vectors
* and scalars produce scalar loop values, while matrices and cell arrays
* produce one column value per iteration. Cell columns remain cell arrays;
* their contents are not unwrapped by the loop assignment.
*
* @param value Evaluated loop expression.
* @param target Loop assignment target.
* @returns Values assigned on each loop iteration.
*/
private forLoopValues;
/**
* Build the value assigned by one `for` iteration.
*
* Scalar targets receive a copied expression value. Row-vector targets use
* a lazy return list so multi-target loop assignments can request each
* element independently, matching the same comma-separated-list machinery
* used elsewhere in the interpreter.
*
* @param target Loop assignment target.
* @param value Iteration value to assign.
* @returns Scalar assignment value or lazy return-list carrier.
*/
private forLoopAssignmentValue;
/**
* Validate the subset of MATLAB `parfor` semantics that remains meaningful
* for the browser's sequential fallback execution.
*
* Unlike ordinary `for`, MATLAB `parfor` uses a simple loop variable and a
* consecutive integer iteration vector. The runtime still executes
* sequentially, but it rejects shapes that would not be valid parallel loop
* headers.
*
* @param target Loop assignment target from the parser.
* @param value Evaluated loop expression.
*/
private validateParforHeader;
/**
* Validate `parfor` body restrictions that can be checked from the AST.
*
* The sequential browser fallback keeps execution deterministic, but the
* accepted source must still respect MATLAB `parfor` structural rules so
* code does not become valid here and invalid in MATLAB/Octave-compatible
* environments.
*
* @param body Loop body to inspect.
* @param loopVariable Simple loop variable name.
*/
private validateParforBody;
/**
* Validate `spmd` body restrictions that remain relevant for the browser's
* single-worker fallback.
*
* MATLAB rejects several control-flow and parallel constructs inside
* `spmd` blocks because workers execute separately from the client
* workspace. MathJSLab executes the block sequentially, but preserving the
* structural restrictions prevents non-portable code from being accepted.
*
* @param body SPMD body to inspect before execution.
*/
private validateSpmdBody;
/**
* Clone an assignment target while preserving only expression-compatible shapes.
*
* Assignment lowering can duplicate identifiers, indexing chains, indirect
* references, and runtime values before the actual write occurs. Every
* cloned branch is routed back through the expression boundary so malformed
* statement/control-flow nodes cannot enter the assignment pipeline.
*
* @param target Assignment target or runtime value to clone.
* @returns Copied target constrained to expression position.
*/
private cloneAssignmentTarget;
/**
* Validate values before exposing them through an interpreter-owned comma
* separated return list.
*/
private returnListValue;
/**
* Create a lazy comma-separated return list from already evaluated values.
*
* Values are validated only when selected so the return list can honor the
* caller-requested output count while still rejecting non-expression values
* before they cross an expression boundary.
*
* @param values Candidate output values.
* @returns Lazy comma-separated return list.
*/
private valueReturnList;
/**
* Convert comma-separated values into a row vector for scalar operations.
*
* Native brace and structure-field descriptor chains may return a lazy
* comma-separated list. Compound assignments need an expression value that
* can participate in `+`, `-`, etc., so the selected list is materialized in
* the same row-vector shape used by explicit concatenation contexts.
*/
private compoundAssignmentOperand;
/**
* Read the assigned value from an internal assignment-result list.
*/
private nestedAssignmentValue;
/**
* Parse and evaluate source text in a specific scope.
*
* This is shared by `eval`/`evalin` and deliberately creates a transient
* call-stack frame so introspection and argument helpers observe the scope
* in which the string is evaluated.
*
* @param source Source code to parse.
* @param scope Scope used for evaluation.
* @returns Evaluated result tree or runtime value.
*/
private evalStringInScope;
/**
* Temporarily reject dynamic variable creation in static function workspaces.
*
* MATLAB static workspaces allow `eval`/script code to update variables that
* appear in function text, but reject brand-new variable names. Normal parsed
* statement execution does not enable this guard.
*
* @param scope Workspace that will run dynamic code.
* @returns Restorer for the previous guard state.
*/
private pushDynamicNameCreationGuard;
/**
* Determine whether an error can be handled by an `eval` catch string.
*
* MATLAB/Octave control-flow signals must propagate through `eval`; only
* ordinary runtime errors are catchable by the optional catch source.
*
* @param error Error or control-flow signal thrown by evaluation.
* @returns `true` when the catch string may handle the error.
*/
private isEvalCatchableError;
/**
* Evaluate source like `eval` while returning captured display text first.
*
* MATLAB `evalc` returns command-window output in the first result and the
* evaluated expression outputs in subsequent result slots. The engine has
* no separate command-window stream, so capture uses the same textual
* representation that top-level evaluation would expose through `Unparse`.
*
* @param source Source code to parse and evaluate.
* @param catchSource Optional catch source evaluated after ordinary errors.
* @returns Captured output string, optionally followed by evaluated outputs.
*/
private evalcResult;
/**
* Extract top-level class definitions from a parsed source tree.
*
* Host-provided class sources are parsed as ordinary snippets; this helper
* isolates classdef nodes without executing unrelated statements.
*
* @param tree Parsed source tree.
* @returns Top-level class definitions in source order.
*/
private topLevelClassDefinitions;
/**
* Extract top-level function definitions from a parsed source tree.
*
* This is used by function-file loading and script-local function
* pre-registration, keeping MATLAB/Octave function discovery separate from
* statement execution.
*
* @param tree Parsed source tree.
* @returns Top-level function definitions in source order.
*/
private topLevelFunctionDefinitions;
/**
* Parse a host-provided function-file source.
*
* The selected primary function is renamed to the requested canonical name
* so package/import aliases can load source supplied under a fully
* qualified runtime name while preserving MATLAB/Octave function-file
* lookup behavior.
*
* @param name Canonical function name requested by lookup.
* @param source Source text containing one primary function and optional subfunctions.
* @returns Primary function plus private subfunctions.
*/
private parseFunctionSource;
/**
* Resolve function-file source through the configured host tables/providers.
*
* @param name Canonical function name requested by lookup.
* @returns Normalized source entry, if the host can supply one.
*/
private resolveFunctionSource;
/**
* Test whether a semantically valid host-provided function source exists.
*
* The probe parses and validates the source without registering it, so
* introspection such as `exist` and `which` cannot mutate the runtime.
*
* @param name Function name requested by lookup.
* @returns `true` when a loadable function source is available.
*/
private hasFunctionSource;
/**
* Resolve and validate a function source without registering it.
*
* This mirrors the static checks performed by lazy function loading:
* primary-function matching, declaration placement, signature validation,
* `arguments` blocks, and duplicate subfunction names.
*
* @param name Function name requested by lookup.
* @returns Normalized source entry, or `undefined` when unavailable/invalid.
*/
private validFunctionSource;
/**
* Validate a parsed function file before it is reported or registered.
*
* Host probes and lazy loading both use this single gate so externally
* supplied primary functions, subfunctions, and class method files obey the
* same signature and `arguments`-block rules.
*
* @param primary Primary function selected from the file.
* @param subfunctions Private top-level subfunctions from the same source.
* @param duplicateContext Source label used in duplicate-function diagnostics.
*/
private validateFunctionFileDefinitions;
/**
* Register a parsed function-file definition in a target scope.
*
* The primary function is visible from the caller scope. Subfunctions are
* stored in the primary function's file scope so they remain private to the
* loaded function file, which matches MATLAB/Octave file scoping.
*
* @param primary Primary function definition.
* @param subfunctions Private top-level subfunctions from the same source.
* @param scope Scope receiving the primary function.
* @returns Registered primary function definition.
*/
private registerFunctionFileDefinition;
/**
* Load a MATLAB/Octave-like function file from host-provided source text.
*
* The primary function is exported to the target scope. Additional
* top-level function definitions become private subfunctions visible only
* through the primary function's file scope.
*
* @param name Canonical primary function name.
* @param source Source text containing the function file.
* @param scope Scope that receives the primary function.
* @returns Registered primary function definition.
*/
LoadFunctionFile(name: string, source: string, scope?: Scope, sourceName?: string): NodeFunctionDefinition;
/**
* Resolve and register a function definition through host-provided sources.
*
* @param name Function name requested by lookup.
* @param scope Scope that should receive the loaded primary function.
* @returns Registered function definition, or `undefined` when unavailable.
*/
loadFunctionDefinition(name: string, scope: Scope): NodeFunctionDefinition | undefined;
/**
* Resolve script source through the configured host tables/providers.
*
* @param name Script name requested by lookup.
* @returns Normalized source entry, if the host can supply one.
*/
private resolveScriptSource;
/**
* Test whether a semantically valid host-provided script source exists.
*
* The script is parsed and checked for declaration-placement violations,
* but it is not executed and script-local functions are not registered.
*
* @param name Script name requested by lookup.
* @returns `true` when a runnable script source is available.
*/
private hasScriptSource;
/**
* Resolve and validate a script source without executing it.
*
* @param name Script name requested by lookup.
* @returns Normalized source entry, or `undefined` when unavailable/invalid.
*/
private validScriptSource;
/**
* Execute a parsed script while temporarily exposing script-local functions.
*
* @param tree Parsed script source tree.
* @param scope Workspace where script statements execute.
* @returns Evaluated script result.
*/
private executeScriptTree;
/**
* Execute MATLAB/Octave-like script source in a workspace.
*
* Script-local functions are visible while the script executes and hidden
* afterward. Function handles created by the script keep captured closures,
* so they remain callable even after the temporary function table is
* restored.
*
* @param name Script name used for diagnostics.
* @param source Source text containing the script.
* @param scope Workspace where script statements execute.
* @param sourceName Optional virtual source identity for script-local functions.
* @returns Evaluated script result.
*/
LoadScriptFile(name: string, source: string, scope?: Scope, sourceName?: string): NodeInput;
/**
* Resolve and execute a host-provided script file by name.
*
* @param name Script name or `.m` filename.
* @param scope Workspace where script statements execute.
* @returns Evaluated script result.
*/
RunScriptFile(name: string, scope?: Scope): NodeInput;
/**
* Parse a host-provided class source and select the requested classdef.
*
* @param name Canonical class name requested by lookup.
* @param source Source text containing the classdef.
* @returns Classdef AST node with canonical runtime name.
*/
private parseClassSource;
/**
* Parse a class source if it contains the requested classdef.
*
* @param name Canonical class name requested by lookup.
* @param source Source text containing a possible classdef.
* @returns Matching classdef AST node, or `undefined` when the source is not a classdef file.
*/
private tryParseClassSource;
/**
* Test whether source text looks like a function/method file rather than a classdef file.
*
* Class lookup probes can reach sibling `@Class/method.m` files while
* resolving qualified member chains. Function-only sources should decline
* class loading quietly so the shorter class prefix can be selected.
*
* @param source Source text to inspect.
* @returns `true` when the source contains top-level functions and no classdef.
*/
private isFunctionOnlySource;
/**
* Parse a host-provided class method source selected by a classdef prototype.
*
* MATLAB/Octave allow classdef files to declare method signatures while
* concrete bodies live in sibling `@Class/method.m` files. The primary
* function is stored under the prototype method name so class metadata and
* stack traces keep the source-level method spelling.
*
* @param className Canonical class name that owns the prototype.
* @param methodName Method name declared in the classdef prototype.
* @param sourceName Canonical source entry name resolved by the host.
* @param source Source text containing one method function and optional private subfunctions.
* @returns Primary method plus private subfunctions.
*/
private parseClassMethodSource;
/**
* Resolve class source through the configured host tables/providers.
*
* @param name Canonical class name requested by lookup.
* @returns Normalized source entry, if the host can supply one.
*/
private resolveClassSource;
/**
* Test whether a host class source is available without parsing/registering it.
*
* Lookup helpers such as `exist` and `which` should report browser-provided
* class sources without mutating the runtime class registry, otherwise a
* metadata query can change later function/class precedence.
*
* @param name Canonical class name requested by lookup.
* @returns `true` when the configured resolver can provide class source.
*/
private hasClassSource;
/**
* Resolve and validate a class source without registering it.
*
* The check is intentionally local: it rejects malformed classdef metadata
* while avoiding superclass resolution, dependency loading, and mutations
* to the class registry.
*
* @param name Class name requested by lookup.
* @returns Normalized source entry, or `undefined` when unavailable/invalid.
*/
private validClassSource;
/**
* Attach a virtual source identity to methods declared inside a loaded classdef.
*
* External `@Class/method.m` files receive their own identity when they are
* materialized. Inline methods in a host-provided classdef share the class
* file identity, matching MATLAB/Octave source-level introspection.
*/
private attachClassDefinitionSourceName;
/**
* Resolve and register a class definition through host-provided sources.
*
* @param name Class name requested by lookup.
* @param scope Scope used to resolve superclass dependencies.
* @returns Loaded class definition, or `undefined` when unavailable.
*/
loadClassDefinition(name: string, scope: Scope): ClassDefinition | undefined;
/**
* Resolve a concrete method body for a classdef prototype.
*
* The lookup key is `ClassName.methodName`, which maps naturally to
* browser-hosted paths such as `+pkg/@Class/method.m` through the shared
* class-source resolver.
*
* @param className Canonical class name.
* @param methodName Method prototype name.
* @param scope Scope used as parent for the method-file private scope.
* @returns Loaded method body, or `undefined` when no external method file exists.
*/
loadClassMethodDefinition(className: string, methodName: string, scope: Scope): NodeFunctionDefinition | undefined;
/**
* Convert a dotted identifier chain into name parts when it is purely symbolic.
*
* @param tree Dotted reference node.
* @returns Qualified name parts, or `undefined` for dynamic field access.
*/
private qualifiedReferenceParts;
/**
* Resolve static class members, constants, and enumeration members.
*
* @param definition Class definition that matched the qualified prefix.
* @param fields Remaining field chain after the class name.
* @param scope Evaluation scope for constant defaults and enumeration arguments.
* @returns Runtime value selected by the member chain.
*/
private resolveClassDefinitionMemberChain;
/**
* Resolve a symbolic dotted chain as a package/class-qualified access.
*
* The resolver classifies the qualified prefix without evaluating ordinary
* dot indexing. Local variables intentionally block package/class
* interpretation of the same first component, preserving MATLAB/Octave
* precedence for expressions such as `pkg.field` when `pkg` is a variable.
*
* @param tree Dotted reference node.
* @param scope Lookup scope.
* @returns Structured qualified access result, if the chain is symbolic.
*/
private resolveQualifiedAccess;
/**
* Resolve package/class-qualified names before ordinary dot indexing.
*
* MATLAB/Octave allow expressions such as `pkg.Class.staticMethod`,
* `Class.Constant`, and fully qualified function handles. This helper
* recognizes those symbolic chains while leaving normal struct/object field
* indexing to the evaluator.
*
* @param tree Dotted reference node.
* @param scope Lookup scope.
* @returns Resolved runtime value, or `undefined` when the reference is ordinary dot indexing.
*/
private resolveQualifiedNameAccess;
private hasConcreteName;
/**
* Resolve a simple imported name as a static class method.
*
* This supports MATLAB-style declarations such as
* `import pkg.Class.method`, allowing `method(args)` to dispatch through
* the same `ClassStaticMethod` path used by `pkg.Class.method(args)`.
*
* @param name Simple method name being called.
* @param scope Scope whose import table should be searched.
* @returns Static method wrapper, or `undefined` when no import resolves.
*/
resolveImportedStaticMethod(name: string, scope: Scope): ClassStaticMethod | undefined;
/**
* Resolve a static method by fully qualified name or by visible imports.
*
* Direct dotted calls such as `pkg.Class.method()` already resolve through
* `resolveQualifiedNameAccess`. Named handles and textual calls (`@...`,
* `str2func`, `feval`, `nargin`, `nargout`) need the same dispatch decision
* without first building a dotted AST node.
*
* @param name Method name written in source text.
* @param scope Scope used for class lookup and simple-name imports.
* @returns Bound static method, or `undefined` when the name is not a static method.
*/
resolveStaticMethod(name: string, scope: Scope): ClassStaticMethod | undefined;
private importedStaticMethodCandidate;
/**
* Detect whether an indexing expression contains a resolvable qualified name.
*
* @param tree Expression subtree to inspect.
* @param scope Lookup scope.
* @returns `true` when a dotted operand resolves as a package/class-qualified symbol.
*/
private hasQualifiedNameAccessOperand;
/**
* Resolve a `?ClassName` metaclass literal, including meta-object fields.
*
* @param className Class or meta-object field chain from the literal.
* @param scope Lookup scope.
* @returns Meta-class object or selected meta-object field.
*/
private resolveMetaclassLiteral;
/**
* Create a runtime `meta.class` object with lazy property default
* evaluation.
*
* Parsed class metadata keeps default expressions as AST. Runtime meta
* access should expose evaluated default values, so the provider evaluates
* the default only when `meta.property.DefaultValue` or validation metadata
* asks for it.
*
* @param definition Class metadata to wrap.
* @param scope Scope used to evaluate property default expressions.
* @returns Runtime meta-class object.
*/
private createClassMetaClass;
/**
* Create a runtime `meta.property` object with the same lazy default
* evaluation used by `meta.class.PropertyList`.
*
* @param property Property metadata to wrap.
* @param scope Scope used to evaluate property default expressions.
* @returns Runtime meta-property object.
*/
private createClassMetaProperty;
/**
* Return the MATLAB diagnostic for one argument-count mismatch.
*/
private functionCountMessage;
/**
* Classify an argument-count check without deciding how to report it.
*/
private functionCountStatus;
/**
* Implement `narginchk` and the throwing two-argument form of `nargoutchk`.
*/
private checkFunctionCount;
/**
* Build the message-return forms shared by `nargchk` and `nargoutchk`.
*/
private functionCountMessageResult;
/**
* Implement all supported `nargoutchk` forms.
*/
private nargoutchkResult;
/**
* Implement legacy MATLAB/Octave `nargchk`.
*/
private nargchkResult;
private lookupImportedSourceResolution;
private lookupClassSourceResolution;
private lookupFunctionSourceResolution;
private lookupScriptSourceResolution;
/**
* Resolve browser-hosted virtual source directories for `exist`/`which`.
*/
private lookupDirectorySourceResolution;
private resolveLookupSymbol;
private existCode;
private whichResult;
private isClassName;
private valueIsRuntimeClass;
private valueMatchesValidationClass;
private classIntrospectionArgument;
private metaclassArgument;
private eventData;
private propertyEventData;
private isEventDataObject;
private prepareEventDataObject;
private propertyEventKey;
private validateClassEventAccess;
private validatePropertyEventAccess;
private propertyListenerName;
private propertyListenerNameList;
private addClassPropertyListenerArray;
private addClassListenerForSource;
private addClassListener;
private createClassEventListenerForSource;
private createClassEventListener;
private createClassPropertyListener;
private notifyClassEventForSource;
private notifyClassEvent;
private dispatchClassEvent;
private dispatchClassPropertyEvent;
private resolveClassEventDataField;
private setClassEventDataField;
private resolveClassEventListenerField;
private removeClassEventListenerRegistration;
private addClassEventListenerRegistration;
private setClassEventListenerEventName;
private setClassEventListenerSource;
private setClassEventListenerField;
/**
* Resolve a property name passed to MATLAB's Set/Get mixin methods.
*
* Exact-name classes require an exact property name. Other SetGet classes
* accept full case-insensitive names before considering partial matches,
* where the lowest `PartialMatchPriority` value wins ambiguous prefixes.
*/
private resolveSetGetProperty;
private isSetGetSettableProperty;
private assertSetGetSettableProperty;
private setGetObject;
private setGetArrayRepresentative;
/**
* Build the scalar structure returned by `get(obj)` for one Set/Get object.
*
* Only visible public readable properties are exposed, matching the subset
* of MATLAB's `matlab.mixin.SetGet` behavior implemented by the runtime.
*
* @param instance Set/Get-compatible object instance.
* @returns Structure whose fields are public property values.
*/
private setGetStructure;
/**
* Build the column structure array returned by `get(objArray)`.
*
* @param array Object array containing Set/Get-compatible instances.
* @returns Column vector with one property structure per object.
*/
private setGetStructureArray;
/**
* Normalize a property-name argument accepted by `get` and `set`.
*
* @param value Character name or cell array of character names.
* @param functionName Built-in name used for diagnostics.
* @returns Property names in linear cell order.
*/
private setGetPropertyNames;
/**
* Evaluate `get(objArray, propertyNamesCell)`.
*
* MATLAB returns a cell array whose rows correspond to objects and columns
* correspond to requested properties.
*
* @param target Scalar object or object array.
* @param properties Resolved readable property definitions.
* @returns Cell array of property values.
*/
private getSetGetPropertyCell;
/**
* Apply `set(objArray, propertyNamesCell, propertyValuesCell)`.
*
* The value cell array must have one row per object and one column per
* property name, matching MATLAB's Set/Get table assignment form.
*
* @param target Scalar object or object array to mutate.
* @param propertyNames Row cell array of property names.
* @param propertyValues Cell array of assigned values.
*/
private setSetGetPropertyCell;
/**
* Assign one Set/Get property on a scalar object or every object in an array.
*
* @param target Scalar object or object array.
* @param name Property name.
* @param value Value to assign.
*/
private assignSetGetProperty;
/**
* Build the structure returned by `set(obj)` listing assignable properties.
*
* @param instance Set/Get-compatible object instance.
* @returns Structure with one empty cell field per settable property.
*/
private setGetSettableStructure;
/**
* Implement the public `get` built-in for Set/Get-compatible objects.
*
* @param args Evaluated built-in arguments.
* @returns Property structure, scalar property value, or cell value table.
*/
private getSetGetProperty;
/**
* Implement the public `set` built-in for Set/Get-compatible objects.
*
* The supported forms cover query mode (`set(obj)`), property query mode
* (`set(obj, name)`), scalar name/value assignment, structure assignment,
* and the MATLAB table form with property-name and property-value cells.
*
* @param args Evaluated built-in arguments.
* @returns Void for assignment forms, or a structure/cell query result.
*/
private setSetGetProperties;
private readonly functions;
/**
* Special functions MathML unparser.
*/
private readonly unparseMathMLFunctions;
/**
* Load or reload the interpreter runtime state.
*
* When `config` is supplied, host-provided aliases, functions, command-word
* entries, and source providers are installed. A reload without `config`
* resets those extension tables to the default browser-safe state.
*
* @param config Optional host integration/configuration.
*/
private loadInterpreter;
/**
* Create an interpreter.
*
* Use `Interpreter.Create` for public construction. The private constructor
* wires operator aliases, precedence aliases, context ownership, and host
* extension tables in one place.
*
* @param config Optional host integration/configuration.
* @param context Optional pre-built runtime context.
*/
private constructor();
/**
* Creates an instance of the `Interpreter` object.
* @param config Optional interpreter configuration.
* @param context Optional pre-built interpreter context.
* @returns New interpreter instance.
*/
static readonly Create: (config?: InterpreterConfig, context?: Context) => Interpreter;
/**
* Parse MATLAB/Octave-like source text into the normalized AST.
*
* The lexer receives the current command-word list so command syntax can be
* recognized without hard-coding host-provided command names in the grammar.
*
* @param input Source text to parse.
* @returns Root AST node.
*/
Parse(input: string): NodeInput;
/**
* Native name table factory.
* @returns Native name table with actual `Complex` facade.
*/
private static readonly nativeNameTableFactory;
/**
* Reset the interpreter to a fresh default runtime context.
*
* This clears workspaces, loaded functions/classes, host extension tables,
* and diagnostic state such as `lasterror` and `lastwarn`.
*/
Restart(): void;
/**
* Clear workspace variables, imports, classes, or user-defined functions.
*
* With no names, this clears ordinary variables in the current workspace.
* The special name `all` clears variables, globals, imports, classes, and
* user functions while preserving host source providers. `functions`,
* `classes`, `global`, `import`, and `variables` map to narrower
* MATLAB/Octave-like workspace categories.
*
* @param names Variable/function names to clear in the current scope.
*/
Clear(...names: string[]): void;
/**
* Clear every category covered by MATLAB/Octave `clear all`.
*/
private clearAllWorkspaceCategories;
/**
* Normalize command-form `clear` options before applying them.
*
* Octave permits long options without a dash except for `exclusive`, so
* `clear regexp x` is accepted while bare `exclusive` remains a target.
*
* @param names Command-form words following `clear`.
* @returns Normalized options, or `undefined` when the command was fully handled.
*/
private clearCommandOptions;
/**
* Apply normalized `clear` options to the selected workspace category.
*
* @param options Normalized command options.
*/
private clearCommandCategory;
/**
* Clear visible variables, functions, and classes with exact or pattern targets.
*
* @param options Normalized command options.
*/
private clearVisibleSymbols;
/**
* Test whether a clear target uses MATLAB/Octave wildcard syntax.
*
* @param pattern User-supplied clear target.
* @returns `true` when wildcard expansion is required.
*/
private clearPatternHasWildcards;
/**
* Convert a MATLAB/Octave clear wildcard pattern to a JavaScript regexp.
*
* The supported syntax follows Octave `clear`: `*`, `?`, and bracket
* character classes. Other regexp metacharacters are matched literally.
*
* @param pattern Clear wildcard pattern.
* @returns Anchored regular expression.
*/
private clearPatternRegExp;
/**
* Normalize leading clear pattern options.
*
* @param patterns Raw clear pattern arguments.
* @param initial Initial mode flags selected by the caller.
* @returns Remaining patterns and normalized flags.
*/
private clearPatternOptions;
/**
* Test one candidate against one clear pattern.
*
* @param candidate Visible name.
* @param pattern User-supplied pattern.
* @param regexp Whether `pattern` is a JavaScript-style regular expression.
* @returns `true` when the candidate matches.
*/
private clearPatternMatches;
/**
* Select names matched by clear patterns against a candidate name list.
*
* Exact names are preserved even when they are not currently present, so
* the normal exact-name clear path can still apply aliases and imports.
*
* @param patterns User-supplied clear targets.
* @param candidates Names visible for wildcard expansion.
* @param initial Initial mode flags selected by the caller.
* @returns Expanded names in input order without duplicates.
*/
private selectClearPatternMatches;
/**
* Return ordinary variable names that can be matched by clear patterns.
*/
private clearVariableCandidates;
/**
* Return ordinary variables visible to workspace-introspection commands.
*
* `who` and `whos` report variables from the active workspace. Class
* definitions are stored in the same low-level table, so they are filtered
* out to keep the result aligned with MATLAB/Octave user variables.
*/
private visibleWorkspaceVariableEntries;
/**
* Normalize MATLAB/Octave workspace listing options.
*/
private workspaceListingOptions;
/**
* Select workspace variable names by MATLAB/Octave wildcard or regexp patterns.
*/
private workspaceVariableNamesByPatterns;
/**
* Build a MATLAB-like cellstr column vector for `who`.
*/
private whoResult;
/**
* Build `who` output from already-normalized command or function patterns.
*/
private whoResultFromPatterns;
/**
* Return dimensions reported by `whos` for a runtime value.
*/
private whosValueSize;
/**
* Return a stable, approximate byte count for `whos` metadata.
*/
private whosValueBytes;
/**
* Test whether a value contains complex numeric data for `whos`.
*/
private whosValueIsComplex;
/**
* Build a struct array describing current workspace variables.
*/
private whosResult;
/**
* Build `whos` output from already-normalized command or function patterns.
*/
private whosResultFromPatterns;
/**
* Build a cell column vector with the current lexer keyword list.
*/
private keywordListResult;
/**
* Apply a scalar text predicate to a scalar string or text array.
*/
private textNamePredicateResult;
/**
* MATLAB/Octave language keyword predicate.
*/
private isKeywordResult;
/**
* MATLAB-compatible variable-name predicate.
*/
private isVarNameResult;
/**
* Test whether a name is currently declared global.
*/
private isGlobalName;
/**
* MATLAB/Octave workspace global-name predicate.
*/
private isGlobalResult;
/**
* Return user-defined function names that can be matched by clear patterns.
*/
private clearFunctionCandidates;
/**
* Return visible user-defined function names in shadowing order.
*
* Function scopes can execute `clear functions` while the cached
* function-file definitions live in a parent scope. Walking the visible
* chain keeps command-form clear semantics aligned with runtime
* resolution without touching built-ins or host-registered native
* functions.
*/
private visibleUserFunctionNames;
/**
* Test whether a visible function-table entry is a user function.
*
* @param name Function or imported alias candidate.
* @returns `true` when clearing this name may remove a user function.
*/
private hasVisibleUserFunction;
/**
* Remove a visible user function from the current scope chain.
*
* @param name Function-table key to remove.
* @returns `true` when a user function was visible for this name.
*/
private clearVisibleUserFunction;
/**
* Return loaded class names that can be matched by clear patterns.
*/
private clearClassCandidates;
/**
* Return every visible loaded name category supported by clear patterns.
*/
private clearVisibleCandidates;
/**
* Clear class definitions by selected names, or all loaded classes.
*
* @param names Optional loaded class names to clear.
*/
private clearClassDefinitions;
/**
* Clear one exact name or wildcard pattern from visible variables/functions.
*
* @param pattern Exact clear target or wildcard pattern.
*/
private clearNamedPattern;
/**
* Clear one visible symbol with MATLAB/Octave shadowing precedence.
*
* A variable shadows a function of the same name, so `clear name` removes
* the variable first. Calling `clear name` again can then remove the
* now-visible user function. Class definitions are stored as names and are
* cleared through the same name path.
*
* @param name User-supplied symbol or imported alias to clear.
*/
private clearNamedSymbol;
/**
* Remove user-defined functions from visible function tables.
*
* Built-ins and operator functions are registered separately and remain
* available after `clear functions` or `clear all`.
*/
private clearUserFunctions;
/**
* Validate left side of assignment node.
* @param tree Left side of assignment node.
* @param shallow True if tree is a left root of assignment.
* @returns An object with four properties: `left`, `id`, `args` and `field`.
*/
private validateAssignment;
/**
* Convert an evaluated expression to a boolean condition.
* @param tree Evaluated expression.
* @returns Boolean truth value.
*/
private toBoolean;
/**
* Convert a scalar complex/logical value to a JavaScript condition flag.
*
* @param value Numeric or logical scalar.
* @returns `true` when either numeric component is nonzero.
*/
private complexConditionValue;
/**
* Evaluate a control-flow condition using MATLAB/Octave truth rules.
*
* In condition contexts, MATLAB treats `&` and `|` as short-circuit
* operators, matching `&&` and `||`. Ordinary expression evaluation keeps
* `&` and `|` element-wise, so the special handling stays local to control
* predicates.
*
* @param tree Condition expression.
* @param scope Scope used while evaluating operands.
* @param name Human-readable expression name for diagnostics.
* @returns Boolean condition value.
*/
private evaluatedCondition;
/**
* Evaluate a condition expression, preserving conditional short-circuiting.
*
* @param tree Condition expression.
* @param scope Scope used while evaluating operands.
* @param name Human-readable expression name for diagnostics.
* @returns Evaluated condition value.
*/
private evaluatedConditionExpression;
/**
* Evaluate a logical operator inside a control-flow condition.
*
* @param tree Logical binary operation.
* @param scope Scope used while evaluating operands.
* @returns Logical scalar result.
*/
private evaluateConditionalLogicalOperation;
private switchComparableValue;
private switchCaseMatches;
private switchCandidateMatches;
private classDefinitionForOperatorValue;
private classNameForOperatorValue;
private classDeclaresInferior;
private classBinaryOperatorMethod;
private hasClassInstanceElement;
private classBinaryOperatorArray;
private evaluateBinaryOperatorWithClassDispatch;
private classVariadicOperatorMethod;
private evaluateColonWithClassDispatch;
/**
* Dispatch MATLAB/Octave concatenation overloads for class operands.
*
* Used both by function-form calls (`horzcat(a,b)`) and by array literals
* (`[a,b]`, `[a;b]`) through the runtime container hook.
*/
concatenateOverload(name: 'cat' | 'horzcat' | 'vertcat', values: unknown[], parent: NodeInput): NodeInput | undefined;
/**
* Dispatch a functional operator call such as `plus(a,b)` or `colon(a,b)`.
*
* Function-form operator calls use the same overload opportunity as their
* symbolic counterparts. The method also performs the native fallback with
* the already evaluated arguments, avoiding duplicate evaluation for calls
* such as `plus(f(), g())`.
*/
callFunctionalOperatorOverload(node: NodeBuiltInFunction, args: CallArgumentValue[], parent: NodeInput): NodeInput | undefined;
private requireBinaryOperation;
private requirePrefixOperation;
private requirePostfixOperation;
private evaluateBinaryOperation;
/**
* Evaluate MATLAB/Octave scalar short-circuit logical operators.
*
* Unlike `&` and `|`, `&&` and `||` decide whether the right-hand operand is
* evaluated from the truth value of the left-hand operand. The resulting
* value is always a logical scalar.
*
* @param tree Operation node for `&&` or `||`.
* @param scope Scope used while evaluating operands.
* @returns Logical scalar result.
*/
private evaluateShortCircuitOperation;
private classUnaryOperatorMethod;
private classUnaryOperatorArray;
private evaluateUnaryOperation;
private resolveClassInstanceField;
private assertCanReadClassProperty;
private assertCanWriteClassProperty;
/**
* Test whether an `AbortSet` property assignment can be skipped.
*
* MATLAB skips observable set work when a stored non-dependent property is
* assigned an equal value. The comparison delegates to shared `isequal`
* semantics.
*
* @param instance Target object.
* @param property Property being assigned.
* @param value New value.
* @returns `true` when assignment side effects should be suppressed.
*/
private shouldAbortClassPropertySet;
private assignClassInstanceField;
private assignNestedClassInstanceField;
private assignClassArrayField;
private assignNestedClassArrayField;
private assignClassArrayIndexedField;
private assignClassArrayIndexedNestedField;
private assignClassArrayDescriptorField;
/**
* Evaluate AST subscript expressions and narrow them to native index values.
*/
private evaluatedIndexArguments;
/**
* Evaluate one dynamic field-name expression and normalize it to text.
*/
private evaluatedDynamicFieldName;
/**
* Evaluate a receiver in a context that preserves comma-separated lists.
*
* Chained access such as `C{:}.field` or `C{:}(idx)` must apply the
* following subscript to every comma-list element instead of reducing the
* receiver to its first value.
*/
private evaluatedCommaSeparatedReceiver;
/**
* Return a chained comma-list result in the form expected by the caller.
*/
private chainedCommaListResult;
/**
* Apply one chained call/index operation while building a comma-separated list.
*
* Each item in constructs such as `C{:}.method()` contributes one value to
* the outer comma-separated list, even when the surrounding assignment asks
* for multiple outputs.
*/
private chainedCommaItemApply;
/**
* Find the prefix of a dotted chain that expands to a comma-separated list.
*
* For `S.obj.method()`, the comma list may be produced by `S.obj` rather
* than by the first receiver `S`. Returning the remaining field suffix lets
* the caller apply `method` to every expanded object.
*/
private dottedCommaReceiver;
/**
* Apply a dot-field chain to one already evaluated receiver.
*/
private resolveDotFieldChain;
private resolveClassArrayField;
private resolveClassFieldChain;
/**
* Evaluate arguments passed to inherited handle pseudo-methods.
*/
private evaluatedCallArguments;
/**
* Test whether a value is an array containing only class instances.
*/
private isClassInstanceArray;
/**
* Test whether a value is an array containing only event listeners.
*/
private isClassEventListenerArray;
/**
* Implement inherited methods supplied by MATLAB's `handle` base class.
*
* Classdef method tables contain only user-declared methods. Plain handle
* subclasses still inherit public operations such as `delete`, `isvalid`,
* `notify`, and `addlistener`, so dotted calls need a bridge to the same
* runtime implementations used by the functional forms.
*/
private inheritedHandleMethodCall;
private resolveNestedClassInstanceIndexedField;
private resolveClassArrayDescriptorIndexedField;
private resolveStructureLikeField;
private createSubscriptDescriptor;
private createSubsrefDescriptor;
private createDotSubscriptDescriptor;
private createSubscriptDescriptorArray;
private numericScalarToNumber;
private callClassInstanceMethodWithOutputCount;
private callClassNumArgumentsFromSubscript;
private callClassSubsrefMethod;
private callClassSubsref;
private callClassSubsrefDescriptors;
private callClassDotSubsref;
private collectClassSubsrefChain;
private collectSubsasgnAssignmentTarget;
private indexedAssignmentRhs;
private readNativeSubscriptDescriptor;
/**
* Validate subscript descriptor payloads before native indexing consumes them.
*/
private descriptorSubscripts;
/**
* Normalize a public `substruct` descriptor argument into descriptor
* structures stored in linear order.
*
* @param descriptor Public `substruct` scalar or structure array.
* @param functionName Built-in name used in diagnostics.
* @returns Descriptor structures ready for native or class dispatch.
*/
private subscriptDescriptorStructures;
/**
* Apply a public `subsref` descriptor chain to a native runtime value.
*
* Intermediate `.` and `{}` descriptors may produce MATLAB/Octave
* comma-separated lists. When that happens, the following descriptor must
* be applied to each expanded element instead of reducing the list to its
* first value.
*
* @param target Value being indexed.
* @param nativeDescriptors Descriptor chain already normalized from a
* public `substruct` structure array.
* @returns Referenced value.
*/
private nativeSubsrefNativeDescriptors;
private nativeSubsrefDescriptors;
/**
* Apply the final public `.` descriptor and preserve structure-array
* comma-list results.
*
* @param target Structure scalar or array being indexed.
* @param descriptor Final dot descriptor.
* @returns A scalar field value or a comma-separated return list.
*/
private nativeDotSubsrefResult;
/**
* Apply the final public `{}` descriptor and preserve comma-list results.
*
* @param target Cell array being indexed.
* @param descriptor Final brace descriptor.
* @returns A scalar cell content or a comma-separated return list.
*/
private nativeBraceSubsrefResult;
/**
* Apply the final public `()` descriptor and preserve cell-array
* parenthesis indexing as a cell array result.
*
* @param target Array or character string being indexed.
* @param descriptor Final parenthesis descriptor.
* @returns Indexed value, array, cell array, or character string.
*/
private nativeParenSubsrefResult;
private numericCodeToCharString;
private charStringAssignmentElement;
private charStringAssignmentRhs;
/**
* Select a scalar class instance from an object array using the first
* public subscript descriptor.
*
* @param target Candidate object array.
* @param descriptors Public descriptor chain.
* @returns Selected scalar object when the first descriptor selects one.
*/
private publicObjectArraySubscriptTarget;
/**
* Apply one native descriptor for an internal selection probe.
*
* These probes only decide whether a public descriptor chain should route
* to class overloads. They must not inherit the caller's multi-output
* request, because helper calls such as `subsindex` are scalar protocols.
*/
private singleOutputNativeSubscriptScalar;
/**
* Select a scalar class instance from cell-content public descriptors.
*
* A public descriptor chain may reach an object through `C{i}.field` or
* through a selected sub-cell such as `C(idx){j}.field`. The cell indexing
* belongs to the container, so any class overload receives only the
* remaining object descriptors while assignment later reinserts the updated
* object into the original cell shape.
*/
private publicCellContentSubscriptSelection;
private dotDescriptorFieldChain;
private classPropertyDescriptorChain;
private classPropertyDescriptorPath;
private indexedClassPropertyValue;
private assignNestedClassInstanceIndexedField;
private resolveClassSubsrefDescriptors;
private assignClassArrayDescriptorIndexedField;
private resolveClassArrayPropertyPath;
private resolveClassCellContentPropertyPath;
/**
* Test whether a cell-content descriptor selects only class instances.
*
* Public `subsref/subsasgn` for cells must leave structures and other native
* values to the native descriptor path. The class shortcut is valid only for
* cell contents that are actually objects.
*/
private selectedCellContentsAreClassInstances;
private assignClassInstancePropertyPath;
private assignClassArrayPropertyPath;
private assignClassCellContentPropertyPath;
private assignClassSubsasgnDescriptors;
private resolveClassCellSubsrefDescriptors;
/**
* Public `subsref` built-in implementation.
*
* @param target Value being indexed.
* @param descriptor Public `substruct` descriptor scalar or array.
* @returns Referenced value, or a class overload result.
*/
private subsrefResult;
/**
* Public `subsasgn` built-in implementation.
*
* @param target Value being assigned into.
* @param descriptor Public `substruct` descriptor scalar or array.
* @param value Value to store.
* @returns Updated value.
*/
private subsasgnResult;
private nativeDescriptorIndexList;
private nativeSubscriptScalar;
private setNativeIndexedValue;
private blankNativeSubsasgnValue;
private nativeSubscriptScalarForAssignment;
private assignNativeSubsasgnNativeDescriptors;
private assignNativeSubsasgnDescriptors;
private shouldUseNativeChainedSubsasgn;
private callClassSubsasgn;
private callClassSubsasgnDescriptors;
private createSubsasgnDescriptor;
private callClassDotSubsasgn;
private callClassEnd;
private callClassSubsindex;
private zeroBasedSubsindexValue;
/**
* Convert class objects used as native array indices through `subsindex`.
*
* MATLAB/Octave `subsindex` returns zero-based indices; MathJSLab's native
* indexing core consumes ordinary one-based MATLAB indices, so this helper
* validates the method result and shifts it by one at the boundary.
*/
convertIndexArgument(value: NodeInput, parent: NodeInput): NodeInput;
/**
* Re-evaluate expressions waiting for a newly defined forward reference.
* @param id Identifier that may unblock pending references.
* @param scope Scope that stores the pending references.
* @param resolving Resolution chain used to detect recursive cycles.
*/
private solveUndefined;
/**
* A forward reference is recoverable only when it was raised in the
* currently executing callable. Errors propagated from deeper calls must
* keep their original stack trace and should not be registered as local
* pending assignments.
*/
private isLocalUndefinedReference;
private registerFunctionDefinition;
/**
* Test whether a parsed declaration sits inside an executable control
* block rather than directly in a script, function, or class section body.
*
* MATLAB/Octave declarations are not statements that can be conditionally
* introduced by `if`, `for`, `try`, and similar blocks. The parser can
* still build these shapes because command lists are intentionally generic;
* the interpreter rejects them before registration.
*/
private isNodeInsideExecutableBlock;
/**
* Validate declaration placement for a parsed tree before execution.
*
* Command lists are intentionally generic so the parser can preserve rich
* MATLAB/Octave syntax and parent links. This semantic pass rejects
* definition/declaration placements that are structurally invalid even when
* the containing branch would not run at runtime.
*
* @param tree Parsed AST to validate.
*/
private validateDeclarationPlacement;
private preregisterScriptLocalFunctions;
private getArgumentValidationName;
private getNameValueArgumentTarget;
private getArgumentValidationDisplayName;
private validateFunctionArgumentsBlocks;
private validateFunctionSignatureList;
private validateFunctionSignature;
private validateAnonymousFunctionSignature;
/**
* Extract the declared name from a `global` or `persistent` list entry.
*
* @param declaration Declaration list element.
* @param declarationKind Display name for diagnostics.
* @returns Declared identifier.
*/
private declarationName;
/**
* Return the non-ignored names declared by one function signature list.
*
* @param nodes Function parameters or returns.
* @returns Set of declared names.
*/
private signatureNameSet;
/**
* Collect identifier references from a subtree without following parent links.
*
* @param node AST fragment to inspect.
* @param names Accumulator receiving referenced identifier names.
*/
private collectIdentifierReferences;
/**
* Validate MATLAB/Octave restrictions for function declarations.
*
* Global and persistent variables must not reuse formal input/output names,
* and the first declaration must appear before any previous reference to the
* same local name in the function body.
*
* @param func Function definition to validate.
* @param functionDisplayName Human-readable function name.
*/
private validateFunctionDeclarations;
private getValueClassName;
private objectArrayClassName;
private getArgumentValidationEntry;
private validateArgumentValidation;
private classPropertyValidationNode;
private validateClassPropertyValue;
validateClassInstancePropertyDefaults(instance: ClassInstance, scope: Scope): void;
private validateFunctionArguments;
validateFunctionInputArguments(func: NodeFunctionDefinition, scope: Scope): void;
validateFunctionRepeatingArguments(func: NodeFunctionDefinition, scope: Scope, values: ExpressionBoundaryValue[]): void;
getFunctionNameValueParameters(func: NodeFunctionDefinition): Set<string>;
private getFunctionNameValueDeclarations;
splitFunctionCallNameValueArguments(func: NodeFunctionDefinition, args: ExpressionBoundaryValue[]): {
positional: ExpressionBoundaryValue[];
named: Map<string, ExpressionBoundaryValue>;
};
bindFunctionNameValueArguments(func: NodeFunctionDefinition, scope: Scope, values: Map<string, ExpressionBoundaryValue>): void;
registerNestedFunctions(func: NodeFunctionDefinition, scope: Scope): void;
/**
* Configure MATLAB static-workspace metadata for function calls.
*
* Workspaces for nested functions, and functions that contain nested
* functions, cannot receive brand-new variable names from dynamic code such
* as `eval`, `evalin`, `assignin`, or scripts. The allowlist is derived from
* names that appear textually in the function signature/body.
*
* @param func Function definition being called.
* @param scope Fresh call scope associated with the function.
*/
configureFunctionWorkspace(func: NodeFunctionDefinition, scope: Scope): void;
/**
* Test whether a function body declares nested functions directly.
*/
private functionContainsNestedDefinitions;
/**
* Collect variable names that are visible in function text.
*/
private staticWorkspaceTextNames;
/**
* Walk a statement tree and collect assignment/declaration root names.
*/
private collectStaticWorkspaceTextNames;
/**
* Collect assignment root names from one left-hand-side shape.
*/
private collectStaticAssignmentTargetNames;
/**
* Preprocess imports that belong to a script or function body scope.
*
* MATLAB applies imports to the whole script/function scope, including
* statements that appear textually before the `import` command. Execution
* still visits the `IMPORT` nodes later, but re-registering the same import
* is harmless because `Scope` deduplicates entries.
*
* @param tree Script/function statement tree to scan.
* @param scope Scope receiving the imports.
*/
applyScopedImports(tree: NodeInput, scope: Scope): void;
validateFunctionOutputArguments(func: NodeFunctionDefinition, scope: Scope, requestedOutputCount: number, outputMask?: boolean[]): void;
getFunctionInputArgumentDefaults(func: NodeFunctionDefinition): Map<string, NodeExpr>;
getFunctionOutputRepeatingName(func: NodeFunctionDefinition): string | undefined;
/**
* Expression tree recursive interpreter.
* @param tree Expression to evaluate.
* @param scope Scope of execution.
* @returns Expression `tree` evaluated.
*/
Evaluator(tree: NodeInput, scope?: Scope): NodeInput;
/**
* Evaluate a parsed AST from the top-level entry point.
*
* This method resets `exitStatus`, detaches the root parent pointer, and
* converts loop-control signals that escaped their valid context into
* user-facing evaluation errors.
*
* @param tree AST node to evaluate.
* @returns Evaluated runtime value or AST result.
*/
Evaluate(tree: NodeInput): NodeInput;
/**
* Parse and evaluate source text in one call.
*
* @param input Source text to execute.
* @returns Evaluated runtime value or AST result.
*/
Execute(input: string): NodeInput;
/**
* Convert an AST/runtime value back to MathJSLab source-like text.
*
* The unparser is intentionally normalized rather than source-preserving:
* it reflects the AST contract used by tests, diagnostics, and display
* output, not the exact whitespace/comments of the original input.
*
* @param tree AST/runtime value to unparse.
* @param parentPrecedence Parent operator precedence.
* @returns Normalized source-like text.
*/
Unparse(tree: NodeInput, parentPrecedence?: number): string;
/**
* Convert an AST/runtime value to a MathML fragment.
*
* This method returns only the inner fragment. Use `UnparseMathML` when the
* caller needs the full `<math>` wrapper and display-mode handling.
*
* @param tree AST/runtime value to render.
* @param parentPrecedence Parent operator precedence.
* @returns MathML fragment.
*/
UnparserMathML(tree: NodeInput, parentPrecedence?: number): string;
/**
* Wrap a MathML fragment for display.
*
* @param tree AST/runtime value to render.
* @param display MathML display mode.
* @returns Full MathML string.
*/
UnparseMathML(tree: NodeInput, display?: 'inline' | 'block' | 'none'): string;
/**
* Generate MathML for parsed input without evaluating it.
*
* @param input Source text to parse.
* @param display MathML display mode.
* @returns MathML rendering of the parsed input.
*/
ToMathML(input: string, display?: 'inline' | 'block' | 'none'): string;
/**
* Parse, evaluate, unparse, and MathML-render source text.
*
* This convenience API is useful for demos and diagnostics that need every
* stage of the interpreter pipeline at once.
*
* @param input Source text to process.
* @param display MathML display mode for the evaluated result.
* @returns Bundle containing parse, evaluation, unparse, and MathML results.
*/
Interprets(input: string, display?: 'inline' | 'block' | 'none'): InterpretsResult;
}
export type { ClassSource, ClassSourceProvider, ClassSourceTable, FunctionSource, FunctionSourceProvider, FunctionSourceTable, InterpreterConfig, IncDecOperator, ScriptSource, ScriptSourceProvider, ScriptSourceTable, SourceResolver, };
export type { BuiltinCallable, Callable, FunctionDefinitionCallable, LambdaCallable } from './Callable';
export { ManifestSourceResolver, TableSourceResolver } from './SourceResolver';
export { Scope, CallFrame, InterpreterError, EvalError, ReferenceError, UndefinedReferenceError, CircularReferenceError, SyntaxError, Context, Interpreter };
declare const _default: {
Scope: typeof Scope;
CallFrame: typeof CallFrame;
InterpreterError: typeof InterpreterError;
EvalError: typeof EvalError;
ReferenceError: typeof ReferenceError;
UndefinedReferenceError: typeof UndefinedReferenceError;
CircularReferenceError: typeof CircularReferenceError;
SyntaxError: typeof SyntaxError;
Context: typeof Context;
Interpreter: typeof Interpreter;
};
export default _default;