@sema-agent/core
Version:
Stateless, task-oriented AI agent core
682 lines • 57.6 kB
TypeScript
/**
* THE BINDING RULE — which shell names a command text binds, and to what, read off the one lexer's facts and the
* program read model's roles. A word that expands a name (`"$F"`, `${F}`, a `~` reading `HOME`) names a path only
* through what the text bound that name to; this module answers "what may `F` hold here", and nothing else.
*
* Two halves:
* · {@link bindingEffectOf} — what ONE segment does to the names: binds a name to a value (an assignment statement, a
* declaration builtin's `NAME=value`, a `for` list), makes a name unknown (a builtin whose operand role binds a name,
* an assigning expansion `${N:=…}`, an arithmetic assignment, a code body that runs later), gives a name an ATTRIBUTE
* (integer, a case change, an array, read-only: a later assignment to it stores something other than its text, or
* nothing), or makes EVERY name unknown (a name reference, `eval`, `source`, a computed name, an unquoted
* here-document `${`), and resets every name to the state it starts the text in (a function body: it runs at its
* call, against that table);
* · {@link BindingThread} — the effects threaded through the segments the way the plan threads the working directory
* (`shell-read-plan.ts`), in their ORDERED state: a binding is one for a reader only where it may run before the
* reader in the same shell — not one written after it, inside a subshell the reader is not in (a closed `( … )`, a
* pipeline member that is not the last, a background job) or in a function body (it runs at a call: a call the plan
* sees makes every name a body binds unknown from there). A value bound in a segment that may not have run before
* a reader (an `&&` / `||` run, a branch, a loop body, the last pipeline member) joins the values the name held
* before instead of replacing them. A reader in a function body loses every name another body binds — unless the
* body declared it with a plain `local`. `PWD` / `OLDPWD` start from what the working-directory thread says.
* An attribute and a name reference hold for every segment they may RUN before: a later one, one in a function body
* (it runs at its call), one in the same loop body (a later beat).
*
* A name the text does not settle is UNKNOWN, and a word expanding an unknown name stays a word the shell rewrites (its
* read cannot be established). `HOME` is an ordinary name whose state at the start of a text is the declared home.
* The shell's own variables (the ones bash sets, holds read-only or evaluates itself) are never bound from text.
*/
import { type LexedRedirect, type LexedSegment, type LexedToken, type LexedWord, type WordPiece } from "../../shell/lex.js";
import { readProgramPosition } from "./bash-program-position.js";
import { type DeclaredAttribute } from "./program-read-model.js";
import { type InputText, type TextSource } from "./shell-reentry-text.js";
import { type BuiltinState } from "./shell-read-builtins.js";
/** A value a name may hold — the text the program receives ({@link spelled}: what a shell re-parsing it reads), literal
* throughout, or a PATTERN whose matches are the values (a `for` list word the shell globs before the loop binds it;
* `spelled` is then the pattern as the program receives it where it matches nothing): `glob`, with its `parts` — the
* value in runs: a literal run (quoted or literal text, a settled value) and a pattern run (glob pieces as written,
* quoting kept, and as a reader judges them — {@link WordExpansion.pattern}). The one producer is the piece walk
* ({@link valueOf}). */
export type BoundValue = {
readonly spelled: string;
readonly glob?: never;
readonly parts?: never;
readonly fields?: readonly string[];
} | {
readonly spelled: string;
readonly glob: true;
readonly parts: readonly ValuePart[];
readonly fields?: never;
};
/** One run of a pattern {@link BoundValue}: literal text, or a pattern — the shell expands its characters — `text` as
* written (what a shell re-reading it matches by), `judged` as a reader judges the names it matches. */
export type ValuePart = {
readonly text: string;
readonly pattern: false;
} | {
readonly text: string;
readonly pattern: true;
readonly judged: string;
};
/** A spelling the deny judge alone reads ({@link Binding.floor}, {@link wordFloorValues}): a value, or a word as written
* where its names are unknown — nothing re-reads it, so a pattern says no more than that it is one. */
export interface FloorValue {
readonly spelled: string;
readonly glob?: true;
/** A pattern's spelling as a reader judges the names it matches, where it is not `spelled` ({@link judgedSpellingOf}). */
readonly pattern?: string;
/** A value a binding that may not have run left an unknown name (#3536, {@link BindingTable.floorOf}): it yields to the
* floor reader's bound before any other ({@link wordFloorValues}). */
readonly held?: true;
/** A spelling of one PIECE of a word, not of the word, where another piece transforms what its name stores ({@link floorCombos}),
* or one made with or cut from such a spelling ({@link sourcedFloor}): the word may spell it, but nothing says it does — the
* deny judge reads it as a spelling the shell rewrites the word into, never one the plan places (a removal judges the word). */
readonly piece?: true;
}
/** A pattern value's names as a reader judges them, where that is not its spelling: its runs, a class the judge widens
* as `?` (the lexer's `WordExpansion.pattern.judged`), a leading `~` the literal tilde it is. */
export declare function judgedSpellingOf(v: BoundValue): string | undefined;
/** A value as a deny-floor spelling, its judged spelling with it. */
export declare function floorOf(v: BoundValue): FloorValue;
/** The values a binding gives its name as deny-floor spellings — what it holds where the text spells it, and its own floor —
* the spellings a kill of that name carries where the binding may have run before the reader ({@link BindingThread.kill}). */
export declare function bindingValues(b: Binding): WordFloor;
/** What bindings give their names ({@link bindingValues}), joined name by name. */
export declare function bindingFloors(bindings: Iterable<Binding>): Map<string, WordFloor>;
/** The values a name may hold where the text settles it. */
export type NameValues = readonly BoundValue[];
/** What a name holds at one point of a text: its possible values, or `"unknown"`. (The values are a NAMED arm: the
* release manifest reads a union that spells a word as a vocabulary, and a `readonly …[]` arm beside the word is a shape
* it cannot enumerate — it would then publish the set unreadable.) */
export type NameState = NameValues | "unknown";
/**
* The variables bash keeps itself — it sets them (`PWD`, `REPLY`, `OPTARG`, `BASH_REMATCH`, …), holds them read-only
* (`SHELLOPTS`, `BASHOPTS`, `BASH_VERSINFO`: an assignment to one is refused), or evaluates every value assigned to them
* as ARITHMETIC (the integer variables: `OPTIND`, `RANDOM`, `LINENO`, `HISTCMD`, `BASHPID`, …; the reference
* implementation's table of them, `zsh`'s included, is read whole: a member that is not one in this shell costs a
* question, never a read). Their value is never the text that bound it.
*/
export declare const SHELL_INTEGER_VARIABLES: ReadonlySet<string>;
/** Is this a variable bash keeps itself ({@link SHELL_INTEGER_VARIABLES}, or one it sets)? The working-directory names
* ({@link WORKING_DIRECTORY_NAMES}) are not: their value is the working-directory thread's ({@link WorkingDirectoryState}). */
export declare function shellKeepsName(name: string): boolean;
/** The names bash sets when the working directory moves: `PWD` (where the shell stands, as the move spelled it) and
* `OLDPWD` (the `PWD` it stood in before the last move — `cd -` goes there). A text may assign them too. */
export declare const WORKING_DIRECTORY_NAMES: readonly ["PWD", "OLDPWD"];
export type WorkingDirectoryName = (typeof WORKING_DIRECTORY_NAMES)[number];
/** What the working-directory thread (`shell-read-plan.ts`) says the two names hold at one segment, before anything the
* text assigns them: the bases it may stand in (`PWD`) and the ones it stood in before its last move (`OLDPWD`) —
* `unknown` where it lost track, the move's spelling is not the base (a physical move), or the shell inherited it. */
export type WorkingDirectoryState = {
readonly [K in WorkingDirectoryName]: NameState;
} & {
/** The last segment before the reader whose move the thread applied or lost track at (-1: none in this text). */
readonly movedAt: number;
/** The places each name may hold all the same — where the thread lost track, `PWD` where the text stood then and where the
* moves after it go from there, `OLDPWD` where it stood before the last of them (the reading a relative word past the loss
* gets); else what the thread holds, `OLDPWD` the place a move left where a binding that may not have run may have changed
* what `PWD` held. The names' floor ({@link BindingTable.floorOf}); never a value. `DIRSTACK`: by index, the entries of the
* stack the thread holds (`PWD`, then what the text pushed). */
readonly floor?: {
readonly [K in WorkingDirectoryName]: readonly string[];
} & {
readonly DIRSTACK?: readonly (readonly string[])[];
};
};
/** The POSIX special builtins: a prefix assignment to one stays after it, and one runs before a function of its name
* (in POSIX mode, which an inherited environment can turn on unseen). */
export declare const SPECIAL_BUILTINS: ReadonlySet<string>;
export declare const functionKey: (name: string) => string;
/** What a function name is at a reader: `defined` — it certainly is one; `absent` — it certainly is not; `maybe` — a branch,
* a loop, a body that may not have run, a removal that may not have found it. */
export type FunctionState = "defined" | "maybe" | "absent";
/** The function names a segment exports to child shells — the `-f` function flag with export (`export` always exports;
* `declare` / `typeset` need `-x`), its bare-name operands. A child `bash -c` inherits them as functions
* ({@link inheritedExportedFunctions}); their definitions are text this reader does not hold, so a call to one shadows
* the builtin of the name (#1628). */
export declare function exportedFunctionNames(argv: readonly LexedWord[]): string[];
/** A function the CHILD inherits through its ENVIRONMENT: bash exports a function as a `BASH_FUNC_<name>%%` variable
* (older bashes `BASH_FUNC_<name>()`), and a child reading that variable from its environment defines `<name>` as a
* function whose body the engine cannot read. Delivered on a child's env by `env BASH_FUNC_x%%=… cmd` (env's own
* assignment grammar accepts the `%%` name the shell's does not). Each such assignment word of a segment names an
* inherited function — the same law as {@link exportedFunctionNames}, a different delivery; a value the shell rewrites
* (`env "BASH_FUNC_$n%%=…"`) names a function the text cannot settle and is not tracked (KL-1628-a). */
export declare function envFunctionNames(argv: readonly LexedWord[]): string[];
/** Whether the BODY of a function a child shell inherits is text the engine read: `read` — the text (or a shell above it)
* defines the function it exports (`f(){ …; }; export -f f`, `declare -fx f`), so the body's segments are read where it
* is defined; `unread` — delivered on an environment (`BASH_FUNC_f%%=…`, {@link envFunctionNames}), or exported with no
* definition the text holds (one a `source` or an `eval` made): a body nobody read. */
export type InheritedBody = "read" | "unread";
/** The functions a text's child shells inherit, each with its {@link InheritedBody}: what the shell running the text
* inherited; then each name the text exports — `read` where the text defines it, else what it was inherited as, else
* `unread`; then each name it delivers on an environment, `unread` whatever else holds it. */
export declare function inheritedFunctionsOf(segments: readonly {
readonly argv: readonly LexedWord[];
readonly defines: readonly string[];
}[], inherited: ReadonlyMap<string, InheritedBody> | undefined): ReadonlyMap<string, InheritedBody>;
/** What a child shell (`bash -c`) inherits from a parent that EXPORTED functions ({@link exportedFunctionNames}): each
* such name is a `defined` function in the child — bash looks a function up before the builtin of its name, so
* `declare X=…` run under an exported `declare` function is the FUNCTION (it binds nothing), not the declaration
* builtin. Every other function key is `absent` (a child inherits only exported functions), every builtin enabled;
* the child holds none of their bodies, so a call to one may change any name (`bound: "all"`). The existing binding
* carrier ({@link PlanStart.names}), not a second table (#1628). */
export declare function inheritedExportedFunctions(names: ReadonlyMap<string, InheritedBody>): InheritedFunctions;
/** One binding a segment makes: a name and what it now holds (`unknown` = made unknown). `prefix`: a binding that may or
* may not take effect (a prefix assignment to a special builtin, which may or may not outlive its command; an `unset` of a
* function, which a read-only function refuses). `loopVar`: a `for` loop's variable — or the name a loop head's `read` binds
* from a literal input (#3401) — held through its body. */
export interface Binding {
readonly name: string;
readonly state: NameState;
readonly prefix?: true;
/** The binding writes PART of the name, or the bash running the text may lack it ({@link SourcedName.keeps}): it takes
* effect, and what the name held stays beside it — read later as a binding beside the earlier ones; the segment's own
* later words read what it binds. */
readonly keeps?: true;
readonly loopVar?: true;
/** `local`: a plain `local NAME…` (or `declare` / `typeset` with no option, {@link BODY_SCOPED_DECLARATIONS}) — in a
* function body the name is the body's own and never leaves it. `unread`: a
* declaration builtin with an option word (`declare -g`, `local -p`, `local -r`): which scope it binds in is not
* read, so it is neither the body's own name nor covered by an earlier `local`. */
readonly scope?: "local" | "unread";
/** Spellings the name may hold that the deny judge still reads where the name is otherwise unknown (an array's
* elements: what `${A[k]}` expands to is one of them; the whole floor of the word an assignment binds it from,
* {@link assignedFloor}). */
readonly floor?: WordFloor;
/** The name's WHOLE value as a list: the elements of a compound `NAME=(…)` every one of which is a plain literal word
* ({@link literalElementsOf}). The name stays `unknown` to every scalar reader; only the one reader of a quoted all-elements
* expansion ({@link BindingTable.arrayOf}) reads the list, and only where this binding is the name's latest. */
readonly array?: readonly BoundValue[];
}
/** An attribute a declaration gives a name — or every name (`name` absent: the declaration computed it): a later
* assignment to it is evaluated as arithmetic (`integer`), stores a case change or an array element (`transformed`), or
* is refused (`frozen`) — it binds something other than its text. */
export interface NameAttribute {
readonly name?: string;
readonly kind: Exclude<DeclaredAttribute, "reference" | "unsettled">;
}
/** What ONE segment does to the names. `all`: every name made unknown (`unknown`), or reset to its state at the start
* of the text (`reset` — a function body). `attributes`: the attributes it gives ({@link NameAttribute}). `references`:
* a name reference was declared — from here on an assignment to any name may write through it, so no name holds what
* the text assigned. `inFunction`: the builtin assigns only inside a function body (`local`) — outside one bash refuses
* the command, and its bindings hold nothing the text says. */
export interface BindingEffect {
readonly bindings: readonly Binding[];
readonly all?: "unknown" | "reset";
readonly attributes?: readonly NameAttribute[];
readonly references?: true;
readonly inFunction?: true;
}
/** How one value word reads against the table, the earlier assignments of the same segment applied (bash assigns left
* to right): its possible values, or `unknown`. */
export type ValueReader = (word: Pick<LexedWord, "pieces">, quoted: boolean, overlay: ReadonlyMap<string, NameState>) => NameState;
/** How one value word's deny floor reads against the table ({@link wordFloorValues}), the earlier assignments of the same
* segment applied — what they store (`overlay`) and the floors they hand their names (`floors`). */
export type FloorReader = (word: Pick<LexedWord, "pieces">, overlay: ReadonlyMap<string, NameState>, floors: ReadonlyMap<string, WordFloor>) => WordFloor;
/** A reader with no table: no name is read, so no word's floor says anything. */
export declare const NO_FLOOR_READER: FloorReader;
/** The floor reader of a table ({@link FloorReader}): a name the segment's earlier assignments bound reads what they bound. */
export declare function floorReaderOf(table: FloorTable): FloorReader;
/** The segment's shape the effect needs beside its words: the functions whose definition heads were dropped from it. */
export interface SegmentShape {
readonly defines: readonly string[];
}
/** The argv projection of a lexed segment: structure that names nothing that runs here is dropped — a subshell
* parenthesis, a bare `{` / `}`, a function definition's head (`NAME ()`, and `function NAME [()]` with a name of
* any spelling, {@link dropDefinitionHeads}), a `case` command's own words ({@link caseWordsOf}), and the block words
* at the head. */
export interface ProjectedSegment extends SegmentShape {
readonly argv: readonly LexedWord[];
readonly redirects: readonly LexedRedirect[];
readonly grouped: boolean;
}
/** The argv projection of every segment of one text ({@link projectSegment}): a `case` command's own words are read across
* the segments ({@link caseWordsOf}). */
export declare function projectSegments(segments: readonly LexedSegment[]): ProjectedSegment[];
/** A function definition's head names nothing that runs here and is dropped from a segment's tokens, in place:
* `NAME ( )` ({@link isDefinitionName}), and `function NAME [( )]` — a bare `function` at command position, a name of any
* spelling. The lexer puts the body's compound command back at command position after the head, so a definition
* nested in a body is dropped the same way; after a drop the token that moved up is looked at again. Answers where the
* heads stood: entry `k` names the functions whose heads were dropped right before the token now at `k` (the last entry,
* past the last token, a head whose body opens in a later segment). */
export declare function dropDefinitionHeads(tokens: LexedToken[]): readonly (readonly string[])[];
/**
* What a word holds through the names it refers to — `$NAME`, `${NAME}`, a leading `~` (the value of `HOME`): `undefined`
* where it refers to no name (it reads as written), else {@link valueOf}. `table.stateOf` is read after `overlay` (the
* names the same segment bound earlier).
*/
export declare function wordValues(word: Pick<LexedWord, "pieces">, table: BindingTable | undefined, quoted: boolean, overlay?: ReadonlyMap<string, NameState>, split?: boolean): readonly BoundValue[] | "unknown" | undefined;
/** The names a word's expansions read as values — a bare `$NAME` / `${NAME}`, and one written inside a bracket the shell
* forms its class from after expanding it ({@link valueOf}) — in the order they stand. */
export declare function namesIn(word: Pick<LexedWord, "pieces">): string[];
/**
* What a VALUE word holds (an assignment's value, a `for` list word, a word handed to a program) — THE piece walk, the one
* producer of {@link BoundValue}s: every combination of the values its pieces take, each field's pattern formed once the
* whole field has expanded ({@link formedField}) — a literal piece its text, a glob piece its pattern as written (a bracket
* holding an expansion its brackets and its body, the body's names substituted in place), `~` and `$NAME` the values the
* table gives:
* · its values — a field the shell globs makes the value a pattern;
* · `"unknown"` — a name it refers to is not settled here, it carries an expansion no name answers (a modifier, a
* substitution, a brace list, `~user`), an UNQUOTED expansion's value is no {@link READABLE_VALUE} (or holds
* whitespace outside `split`), `IFS` may have changed (`quoted` = the whole word is read as one value: an assignment's
* value, which is never split), a field is not formed or a split one forms a pattern, or it would list more than
* {@link WORD_VALUES_MAX} values.
* `split` = the word is read as the ARGUMENTS it becomes: an unquoted value is split into its words on the default `IFS`
* (a value then carries its {@link BoundValue} `fields`).
*/
export declare function valueOf(word: Pick<LexedWord, "pieces">, table: BindingTable | undefined, quoted: boolean, overlay?: ReadonlyMap<string, NameState>, split?: boolean): NameState;
/** A deny floor — a word's ({@link wordFloorValues}) or a name's ({@link BindingTable.floorOf}): the spellings, and whether a
* reader's bound let some go (`pastBound`) — the word, or the name, may then hold a value the floor no longer holds, which
* the deny judge cannot rule out. A name's floor is past its bound where a word's floor handed it on was (a call's own
* command environment, {@link BindingThread.callEnvironmentValues}): every word that reads the name is then past it too. */
export interface WordFloor {
readonly values: readonly FloorValue[];
readonly pastBound: boolean;
}
/** What a word's deny floor reads of the table: what each name holds, and each name's own floor. */
export type FloorTable = Pick<BindingTable, "stateOf" | "floorOf">;
/** No spelling, nothing let go. */
export declare const NO_FLOOR: WordFloor;
/** A floor that says nothing: no spelling, and nothing let go — no floor at all. */
export declare function isEmptyFloor(f: WordFloor): boolean;
/** Floors as one: every spelling of each, past its bound where any is. */
export declare function joinFloors(...floors: readonly WordFloor[]): WordFloor;
/**
* The spellings a word the table leaves unknown may still take through the deny floors of the names it refers to
* ({@link BindingTable.floorOf}) — `${A[k]}`, `${A[@]}`, `$A` reading an array's elements — or through their values where
* known: for the deny judge alone. Empty where some name it refers to leaves neither.
*/
export declare function wordFloorValues(word: Pick<LexedWord, "pieces">, table: FloorTable | undefined): WordFloor;
/** Where a segment's argv heads a `for` / `select` loop: the index of that bare word, at the segment's start or past the
* bare control words in front of it (`do for x in …`, `then for …` — a loop nested in a body or a branch); `undefined`
* for any other segment. */
export declare function loopListHeadAt(argv: readonly LexedWord[]): number | undefined;
/**
* What ONE segment does to the names (see the module header). `argv` = the segment's argv projection (structure
* dropped); `readValue` folds a value word against the table (a reader that answers `unknown` gives the names alone).
* `shadow`: the word the shell looks up first is a function of the text where the segment stands (`named`: it is one, the
* builtin of its name does not run — the call's effect is the body's; `maybe`: it may be one, so what the builtin binds is one
* more value its names may hold). `availability`: whether the builtin of a name runs by it where the segment stands
* ({@link BuiltinState}) — `disabled`: the word finds no command and binds nothing, `maybe`: as a function that may stand.
* `readFloor`: a value word's deny floor against the same table ({@link assignedFloor}; with no table, none).
*/
export declare function bindingEffectOf(segment: LexedSegment, argv: readonly LexedWord[], shape: SegmentShape, readValue: ValueReader, shadow?: "named" | "maybe", availability?: (builtin: string) => BuiltinState, fed?: readonly InputText[], fedByLoop?: boolean, splitUnsettled?: boolean, readFloor?: FloorReader): BindingEffect;
/** Is this segment a `trap` whose action fires only when the shell exits (every signal it names is `EXIT` / `0`)? Bash runs
* that action after the last command this shell runs — a subshell resets it — so it runs before no segment of the text. */
export declare function runsAtExitOnly(argv: readonly LexedWord[]): boolean;
/** The variables a segment marks for export — what a child shell started after it receives: `export NAME…` (not `-n`, not
* `-f`), a `declare` / `typeset` / `local` whose options turn `-x` on; `allexport` — `set -a` / `set -o allexport`, which
* exports each name assigned AFTER it (not one assigned before and left be); a name word the text computes is any name
* (`all`). `undefined`: none. */
export declare function exportsOf(argv: readonly LexedWord[]): ReadonlySet<string> | "all" | "allexport" | undefined;
/** Does this assignment store ARRAY ELEMENTS — a compound value `(…)`, or a subscripted name `a[k]=v`? Bash never exports
* an array (an element assigned to an exported scalar makes it an array, gone from every child's environment): what it
* stores reaches a program only through a word that reads an element — the element floor it leaves here ({@link
* arrayElementFloor}) — never through an environment. One predicate for both spellings. Where the shell may NOT bind the
* word (a prefix, a launcher's or a declaration builtin's operand) it is handed on as written: the read plan keeps that
* word's text a candidate. */
export declare function bindsArrayElement(a: Pick<NonNullable<LexedWord["assignment"]>, "form" | "subscript">): boolean;
/** Do a segment's leading assignment words stand alone — the shell itself binds them — rather than prefix a command whose
* environment they are? The binding rule and the read plan's environment candidates ask the same question. */
export declare function assignsAsStatement(pos: ReturnType<typeof readProgramPosition>): boolean;
/**
* A name a builtin binds from texts the command spells — a SOURCED binding: the texts that may reach it (`sources`, each one
* text that may arrive: the words it is made of and how, {@link TextSource}) and how the builtin cuts one text into the values
* the name may then hold (`cut`). The road of every builtin that binds a word to a name otherwise than as `NAME=word` — `read`
* / `mapfile` fed a here-string, a here-document or a printer's pipe, `printf -v`, `getopts`, a `for` / `select` list, a
* declaration operand the builtin does not store as written ({@link sourcedNamesOf}).
*/
export interface SourcedName {
readonly name: string;
readonly sources: readonly TextSource[];
readonly cut: (text: string) => readonly string[];
/** What the name may hold of a spelling that is only a PIECE of the text (a word the station does not make into the text,
* one value of several a word joins): `cut` where absent. */
readonly piece?: (text: string) => readonly string[];
/** The cut is not the builtin's own — the text does not settle how it splits — so the name may hold a piece the cut does
* not make: a floor with any spelling is past its bound. */
readonly loose?: true;
/** The builtin writes PART of the name — an element (`read 'b[1]'`), elements past an origin (`mapfile -O`), an entry of a
* table the shell keeps (`BASH_ALIASES`, `BASH_CMDS`) — and leaves the rest as it was, or the bash running the text may
* lack it (`mapfile` before 4, `compgen -V` before 5.3) and bind nothing: what the name held stays beside what it binds
* ({@link Binding.keeps}), as an element assignment's does. */
readonly keeps?: true;
}
/**
* THE SOURCED FLOOR — the deny floor a sourced binding ({@link SourcedName}) hands its name, the one reading `NAME=word` takes
* ({@link assignedFloor}) carried through the builtin: each source word read for every spelling it may take (`spellingsOf`:
* its values where the table settles them, else its own floor), every combination made into the source's text and cut as
* the builtin cuts a settled text — so a reader of the name reads what the sources may spell as it would read the sources.
* Where a source makes no text of some combination (a form the station does not spell, a word with no spelling), each word's
* own spellings are cut instead, never dropped (#3536's law); past the reader's bound the floor is too. What is cut of a
* word's piece spelling ({@link FloorValue.piece}), or of a text made with one, is a piece too.
*/
export declare function sourcedFloor(bound: SourcedName, spellingsOf: (word: Pick<LexedWord, "pieces">) => WordFloor): WordFloor;
/** The names a word's ASSIGNING parameter expansions (`${N=…}`, `${N:=…}`) and arithmetic expansions assign. */
export declare function assignedByPieces(pieces: readonly WordPiece[]): string[];
/**
* The names an ARITHMETIC text may assign: every identifier in a text that carries an assignment operator (`=` that is no
* comparison, `+=` and its kin, `++`, `--`) — read whole, not parsed: a name only compared there is made unknown too.
*/
export declare function arithmeticAssignedNames(text: string): string[];
/** The names a text binds anywhere (every segment, every name the binding rule reads), or `all` where it may bind any
* name — for a body that runs later. Unreadable text binds any. */
export declare function namesBoundIn(text: string): ReadonlySet<string> | "all";
/** {@link namesBoundIn}, each name with the values the text binds it to as it spells them ({@link bindingValues}) — its
* segments read as a text's own are, a value read where it is a literal ({@link valueOf} without a table): what a body
* run later may leave the name, the deny floor its binding carries. */
export declare function bindingsIn(text: string): ReadonlyMap<string, WordFloor> | "all";
/**
* Does this text bind `HOME` anywhere (or every name)? — the question a reader that spells the declared home for `~` /
* `$HOME` asks of a text it reads as ONE unit (the read-only classifier's segments). The read station asks the
* threaded question instead ({@link BindingThread}).
*/
export declare function textBindsHome(text: string): boolean;
/** What a name holds at one point of a text, asked by name ({@link BindingTable.stateOf}). */
export type NameReader = (name: string) => NameState;
/** What holds for the names where a nested text starts, given by the text around it: the attributes
* ({@link NameAttribute}) and whether a name reference was declared — a substitution body starts with what may run
* before its segment, a text run later or elsewhere (a code body, `eval`'s text, a child shell's `-c`) with all the
* text around it gives. */
export interface InheritedNames {
readonly attributes: readonly NameAttribute[];
readonly references: boolean;
/** The deny floors a name starts the text with ({@link BindingTable.floorOf}): what the words handing it this text as
* written may name there — or, for a substitution body, the floors its segment reads. */
readonly floors?: ReadonlyMap<string, WordFloor>;
/** The names something before the nested text may have changed — a change that can reach where it starts, and the
* names its own segment's command environment sets (`TMPDIR=… bash -c …`): there such a name no longer holds what the
* shell provides ({@link BindingTable.providedByShell}). `all`: any name. Absent: none. */
readonly rebound?: ReadonlySet<string> | "all";
}
/** Sets of deny floors as one, read when asked: each name's floors from each set, in order. */
export declare function joinedFloors(...sets: readonly (ReadonlyMap<string, WordFloor> | undefined)[]): ReadonlyMap<string, WordFloor>;
/** The function and builtin keys of the shell a text runs in — a literal `eval` text, a substitution body (a fork): what each key
* holds where the text starts (the outer table's answer for it), and the names a call to one of the outer functions may change. */
export interface InheritedFunctions {
readonly start: (key: string) => NameState;
readonly bound: ReadonlySet<string> | "all";
}
/** Two rebound sets as one. */
export declare function joinRebound(a: ReadonlySet<string> | "all" | undefined, b: Iterable<string> | "all" | undefined): ReadonlySet<string> | "all";
/** What the thread answers for one reader: what a name may hold, and whether a name carries the integer attribute. */
export interface BindingTable {
stateOf(name: string): NameState;
/** The elements the name holds as a LIST here — where its latest binding that exists for this reader is a compound literal that
* certainly ran ({@link Binding.array}) and nothing since may have changed it; `undefined` otherwise (and for every name that is
* no such list: the name's scalar state is `unknown` all the same). */
arrayOf(name: string): readonly BoundValue[] | undefined;
/** Values assigned to this name are evaluated as arithmetic. */
isInteger(name: string): boolean;
/** An attribute a declaration that may run before this point gave the name ({@link NameAttribute}): an assignment here stores
* something other than its text (`integer`, `transformed`), or nothing (`frozen`). */
hasAttribute(name: string, kind: NameAttribute["kind"]): boolean;
/** The text may have changed `IFS` before this point: an unquoted expansion is split on what the text does not say. */
readonly ifsTouched: boolean;
/** `HOME` may hold something other than the declared home here. */
readonly homeTouched: boolean;
/** Every spelling any binding of this name before here left for the deny judge alone ({@link Binding.floor}), and whether
* a word's floor handed on to it was past its bound ({@link WordFloor.pastBound}). */
floorOf(name: string): WordFloor;
/** What a substitution body here starts with. */
readonly inherited: InheritedNames;
/** The names a change that can reach this point touched — a binding, or a name made unknown, that may run before it in
* this shell (the thread's order: {@link BindingThread}) — and the names its start says were rebound; `all`: any. */
readonly rebound: ReadonlySet<string> | "all";
/** Does this name still hold what the shell provides here: no change that can reach this point touched it? */
providedByShell(name: string): boolean;
/** What a function of this name is here: the one ordered rule that answers a variable's value answers it
* ({@link FunctionState}). A name the text never defines is `absent` to the caller's own filter, not to this thread. */
functionState(name: string): FunctionState;
/** Whether the builtin of this name runs by it here: the same ordered rule ({@link BuiltinState}). */
builtinState(name: string): BuiltinState;
}
/**
* The effects of a text's segments, threaded the way the plan threads its working directory: a reader at segment `j`
* sees the latest binding of a name, and, where that binding may not have run before `j`, the bindings before it too.
* A binding is CERTAIN for `j` when no block holding it (a branch, a loop, a group) closes or switches branch between it
* and `j` — a block it precedes may come and go — its segment is no pipeline member, background job or prefix
* assignment, and — reached through `&&` / `||` — it lies in `j`'s own `&&` run (`andRunStart`: the same index the
* working-directory thread reads).
*
* A binding exists for a reader only where it may run before the reader IN THE SAME SHELL — the ordered state: one
* written after the reader, one inside a subshell the reader is not in (a `( … )` group that closed before it, a
* pipeline member that is not the last, a background job — a substitution body is a text of its own) and one in a
* function body is NOT a binding for it. A function body runs at its call: a call the plan can see (a program word
* naming one of the text's functions, a code body a builtin runs later, which may name one) makes every name a body
* binds unknown from that segment on ({@link functionBound}) — a kill that may not have run ({@link kill}): what the name
* held stays its deny floor; a text the plan does not read (`eval`, `source`, a computed program word) already makes every
* name unknown, the same way. The last member of a pipeline may or may not run in this
* shell: its bindings join the values before them. A body's own readers follow its own order; a reader in another body
* loses a name any other body binds ({@link Unreadable}). A name the body declares with a plain `local` (before the
* binding, where the declaration certainly ran) never leaves it.
*
* An attribute ({@link NameAttribute}) and a name reference hold for every segment they may RUN before — a later one,
* one in a function body, one in the same loop body: an assignment there binds something other than its text.
*/
export declare class BindingThread {
private readonly segments;
/** What each segment binds: its names, and a value only where it is a literal (the rest is the reader's to read). */
private readonly named;
/** The state a name starts the text in (and is reset to by a function body): the declared home for `HOME`. */
private readonly initial;
/** Names any segment of the text binds (a function body run later reads a `HOME` bound anywhere as unknown). */
private readonly boundAnywhere;
/** Each loop head's segment and its matching `done`'s. */
private readonly loops;
/** `HOME` may already hold something other than the declared home where the text starts (a substitution body
* inside a text that bound it). */
private readonly homeStartsTouched;
/** The functions the shell that runs this text (a literal `eval` text) already holds. */
private readonly inheritedFunctions?;
private readonly entries;
/** The `local` declarations the walk applied as certain ({@link apply}), each where it stands. */
private readonly localDeclarations;
/** The attributes the text gives ({@link BindingEffect.attributes}), and where — read off its names alone, before any
* reader: one given later in the text may run first. */
private readonly attributesAt;
/** Names no assignment makes readable again ({@link Unreadable}). */
private readonly unreadable;
/** The block nesting each segment moves ({@link blockStructure}). */
private readonly blocks;
/** Segments that END in a pipe or a `&`: the command that closes them is a pipeline member that is not the last, or a
* background job — a subshell of its own ({@link ownSubshellAt}: which of the segment's bindings that is). */
private readonly ownSubshell;
/** The floors the names start the text with ({@link InheritedNames.floors}). */
private readonly startFloors;
/** The names rebound where the text starts ({@link InheritedNames.rebound}). */
private readonly startRebound;
/** Where a function body runs ({@link runsBodies}): the last segment that can call one, and the command environment of each call. */
private bodyRuns;
/** The thread was told where bodies run ({@link runsBodies}): until then a body's binding may precede any reader. */
private bodiesTold;
/** A compound's closing segment that carries its redirections → the compound's opening segment ({@link SegmentBlocks.trailingTo}). */
private readonly trailing;
constructor(segments: readonly LexedSegment[],
/** What each segment binds: its names, and a value only where it is a literal (the rest is the reader's to read). */
named: readonly BindingEffect[],
/** The state a name starts the text in (and is reset to by a function body): the declared home for `HOME`. */
initial: (name: string) => NameState,
/** Names any segment of the text binds (a function body run later reads a `HOME` bound anywhere as unknown). */
boundAnywhere: (name: string) => boolean,
/** Each loop head's segment and its matching `done`'s. */
loops: ReadonlyMap<number, number>,
/** `HOME` may already hold something other than the declared home where the text starts (a substitution body
* inside a text that bound it). */
homeStartsTouched?: boolean,
/** What holds where the text starts: given before its first segment. */
inherited?: InheritedNames,
/** The functions the shell that runs this text (a literal `eval` text) already holds. */
inheritedFunctions?: InheritedFunctions | undefined);
/** What a text nested at segment `j` starts with ({@link InheritedNames}) — `j` absent: a text run later, which every
* segment may run before (in whatever shell: a later text may run inside a subshell or a body, so every change
* counts). */
inheritedAt(j?: number): InheritedNames;
/** What a name holds where the text starts: a function name unbound, a builtin enabled (what the shell around an `eval` text, a
* substitution body or a text run later holds, if it says); a variable as the plan says. */
private startOf;
/** Does any segment of this text bind the name (or every name)? */
private bindsInText;
/** What a text this one runs at some later point (a `trap` action) finds each function and builtin key: the point is not ordered
* against the segments (it may fire after any of them, inside any body or subshell), so a key holds what the text starts it with
* and every value any segment binds it ({@link InheritedFunctions}). */
heldAnywhere(): InheritedFunctions;
/** Tell the thread where function bodies run: `runs[si]` — segment `si` may run one (a call, a text the plan does not
* read); `atEnd` — a code body may run at the text's end or at any point (`trap`); `environment[si]` — what a call's own
* command environment sets. A call inside a loop may run again after a later segment of the loop. The last run point
* bounds what can precede a body: a binding after it never does. A name a body that makes a call binds — `local` too:
* the shell's scope is dynamic, the callee runs inside it — is unreadable to a reader in any other body. */
runsBodies(runs: readonly boolean[], atEnd: boolean, environment: readonly (ReadonlySet<string> | "all" | undefined)[]): void;
/** The names a reader that runs LATER than it stands may find rebound by segments after it: a reader in a function body
* runs at each call, so every segment up to the last run point (and a call's own command environment) may run before it;
* a text handed to run later (`j` absent) at any point. A reader that runs where it stands has none: the effects the walk
* has applied so far are the ones that precede it. A `local` counts like any binding: it shortens a name's life, not the
* view of a reader that runs inside its extent (a body called from there, a `trap` text it sets). */
private boundLater;
/** What call `c`'s own command environment hands the body it runs for `name` — the assignment word in front of the program
* (`p=x f`: the body reads `x`), the floor it hands the name read against the table at the call ({@link assignedFloor}, the
* one reading every road that binds a name from a word takes) — or `undefined` where that environment does not set the
* name ({@link runsBodies}' `environment`), or sets it to a value whose floor says nothing (the table's values at the call
* then stay the floor). */
private callEnvironmentValues;
/** Does a binding segment `at` makes, standing at `standing`, run in a subshell of its own — a pipeline member that is
* not the last, a background job? A segment's closing pipe or `&` ends ITS LAST command, at the depth that command
* stands: a binding that stands shallower (a function definition's head, in front of the block its body opens in the
* same segment: `f(){ ls | head; … }`) is not that member — the pipe closes a command inside the body, and the
* definition is the shell's own. */
private ownSubshellAt;
/** Is a binding segment `at` makes one no later reader may count on as certain: made in a pipeline member (it follows a
* `|`, or it is {@link ownSubshellAt}) or a background job? */
private detachedAt;
/** Can a binding segment `at` makes exist for a reader at segment `j` (`j` absent: a reader at the text's end, outside
* every body and subshell)? Not where `at` stands in a function body the reader is not in (the body runs at its call),
* runs in a subshell of its own (a pipeline member that is not the last, a background job), or stands in a `( … )`
* group the reader is not in. */
private visible;
/** Is a binding segment `at` makes, standing at `standing`, made in the shell a reader at segment `j` runs in (`j` absent: the
* text's end)? Not where it runs in a subshell of its own (a pipeline member that is not the last, a background job) or
* stands in a `( … )` group the reader is not in: nothing a subshell binds — a value, a deny floor — leaves it. (A function
* body is no subshell: what it binds reaches its callers, {@link kill}.) */
private inShellOf;
/** Where the binding `name` of segment `at` is made: the segment's own place, or — a function definition — where its head
* stands. */
private standingOf;
/** The names any of the text's function bodies binds — what a call to one of them may change — or `all` where a body
* may bind any name. A name the body keeps `local` ({@link leavesBody}) stays in it. */
functionBound(): ReadonlySet<string> | "all";
/** {@link functionBound}, each name with the values the bodies bind it to as the text spells them ({@link bindingValues}):
* what a call may leave the name, the deny floor its kill carries ({@link kill}). */
functionBindings(): ReadonlyMap<string, WordFloor> | "all";
/** The function body a binding segment `at` makes belongs to, where the name can outlive it: the body it stands in — a
* plain `local NAME` is the body's own and never leaves it (an optioned declaration, `declare -g` / `local -p`, reads no
* scope, so it can). What a reader in ANOTHER body loses ({@link unreadableBy}); a call to the body changes it unless a
* declaration the body certainly ran covers the name ({@link functionBound}). */
private bodyBinding;
/** Does what segment `at` does to this shell — a binding it makes where it stands, a move of the working directory —
* reach a reader at segment `j` (`j` absent: the text's end)? The one visibility rule ({@link visible}). */
reaches(at: number, j?: number): boolean;
/** Does segment `k` close a compound that carries redirections behind its closing word — its bindings are those
* redirections', bound where the compound opens ({@link openCompoundsAt}), not after its body? */
closesWithRedirections(k: number): boolean;
/** A compound that opens at segment `h` and carries redirections behind its closing word ({@link SegmentBlocks.trailingTo}): bash
* performs them — and the assignments their expansions make — before the compound's first command. What they bind is made
* unknown from the opening segment's own words on, a binding that may not have run (the redirection may fail), its values the
* names' deny floor; the closing segment does not bind them again ({@link closesWithRedirections}). The walk calls this before
* it threads `h`. */
openCompoundsAt(h: number): void;
/** Does segment `at` stand in a function body (it runs at a call, not here)? */
inFunctionBody(at: number): boolean;
/** The innermost function body segment `at` stands in, as an id one body's segments share (`undefined`: none). */
bodyOf(at: number): number | undefined;
/** Does segment `at` run in a subshell (a `( … )` group, a pipeline member that is not the last, a background job) or a
* function body — whatever it changes, the shell that runs the next segment may not see? */
runsApart(at: number): boolean;
/** Segment `at` hands this shell a body it runs at ANY later point (a `trap` action, an alias value): every name the
* body may bind (`all`: any) is unreadable to every reader after `at`, whatever is assigned to it in between. */
runsLater(at: number, names: ReadonlySet<string> | "all"): void;
/** What segment `at` makes unreadable: in a function body, the names it binds (a plain `local` stays in it) — every name
* where it may bind any; a name reference, every name. Read before any segment is applied, so it does not ask which
* declarations certainly ran: a name a body assigns after its own `local` is lost to a reader in another body all the same
* (more questions, never fewer). */
private unreadableBy;
/** May segment `x` run before segment `e` runs (`x` being `e`: before a later run of it): `x` comes first in the text,
* `e` stands in a function body (the body runs at its call, after any segment, and may run again), or `e` stands in a
* loop's body and `x` in that loop — its body (a later beat runs `x` again first) or its `done` (the loop's redirections
* are expanded before its first beat). */
private mayRunBefore;
/** May what segment `x` does to the shell — a binding it makes (of `name`: a function's stands where its head does), an export —
* run before segment `e`, in `e`'s shell ({@link bindsBefore}'s order)? A reader outside every function body: in the text's
* order and in its shell; made in a body the reader is not in, where a call that may run the body does. A reader in a body runs
* at its calls: anything may. */
segmentPrecedes(x: number, e: number, name?: string): boolean;
/** Does segment `x` certainly run before segment `e` does, in `e`'s shell ({@link segmentPrecedes}): outside every function
* body, not a pipeline member or a background job, held through every block up to `e` ({@link heldThrough}), and — reached
* through `&&` / `||` — only in an `&&` run that reaches `e`? */
segmentCertainlyBefore(x: number, e: number): boolean;
/** The segments that bind each name, and those that bind every name ({@link bindsBefore}). */
private binders?;
/** Does a binding of the name — or of every name (an `eval`, a call, a command the text does not settle) — exist for segment
* `e`: made where it may RUN before `e` IN `e`'s SHELL? The one order every reader that asks "may the text have rebound this
* name here" reads, and the one the value table reads ({@link tableAt}): in the text's order ({@link mayRunBefore}: a loop's
* later beat, a compound's own redirections), never out of a subshell `e` is not in, a pipeline member that is not the last or
* a background job ({@link inShellOf}); a function body's binding where a call that may run the body precedes `e` — the
* body runs at its calls, not where it is written. A reader in a function body runs at its calls, after any segment. */
bindsBefore(name: string, e: number): boolean;
/** Did the body certainly declare this name `local` before segment `at`: an earlier segment of the body, run on its own
* (no `&&` / `||`, no pipeline member or background job), in a block still open at `at`, whose declaration the walk
* APPLIED as certain — the shell ran its word as the builtin: no function of that name standing, no launcher, path or
* redirection in the way, and the builtin enabled where the body runs (what {@link bindingEffectOf} concluded, the ordered
* state of {@link BindingTable.functionState} and {@link BindingTable.builtinState}; recorded by {@link apply}). */
private declaredLocal;
/** Does the block that holds a binding's words stay open (no closing word, no switch of branch) through `j`? */
private heldThrough;
/** Apply segment `at`'s effect. `andRun`: the segment was reached through `&&` / `||`. `loopEnd`: for a loop variable,
* the index of the loop's end. `spliced`: the segment is a sourced literal's text standing in for its `source` (#3557):
* it may not have run, so every binding it makes is {@link Entry.detached} — one more value, never a certainty. */
apply(at: number, effect: BindingEffect, andRun: boolean, loopEnd?: number, spliced?: boolean): void;
/** Does a reader at segment `j` lose the name `u` makes unreadable: past a name reference it may run after, or in a
* function body other than the one that binds it? */
private lostAt;
/** Make these names unknown from segment `at` on (a loop body that binds them may have run before any of its beats; a
* call runs a body that binds them) — as a binding that may not have run, the one reading #3536 gives one: a beat may
* not come, a body's binding may sit behind a branch it does not take, the body called may not be the one that binds
* the name (the call does not name its body), so what the name held before stays its deny floor. And what the body binds
* may have run: `carried` — the values the body binds each name to ({@link bindingValues}) — joins that floor. */
kill(at: number, names: Iterable<string> | "all", carried?: ReadonlyMap<string, WordFloor>, opens?: boolean): void;
/** The table a reader at segment `j` sees; `andRunStart` = the first segment of `j`'s `&&` run; `where` = what the
* working-directory thread says `PWD` / `OLDPWD` hold there (absent: it does not say — both unknown). `asked`: the calls
* a reading of a name already reads, each name's own ({@link atCalls} — a table read at a call it asks; absent: a fresh
* reading per name). */
tableAt(j: number, andRunStart: number, where?: WorkingDirectoryState, asked?: Map<string, Set<number>>, whereAtCalls?: boolean): BindingTable;
}
/** A segment that opens with `((`: an arithmetic command (or a subshell in a subshell — the tokens are the same). */
export declare function isArithmeticCommand(segment: LexedSegment): boolean;
/** The `[[` operators whose operands the arithmetic evaluator reads (`[[ x -eq y ]]`; `[` / `test` compare integers
* without evaluating them). */
export declare const ARITHMETIC_TEST_OPERATORS: ReadonlySet<string>;
/** The substitutions a parameter expansion's body hands the arithmetic evaluator: its subscript (`${a[…]}`, `${#a[…]}`,
* `${!a[…]}`) and the offset and length of a substring expansion (`${x:off:len}` — the shell expands them, then
* evaluates them), as the lexer's one reading of the body finds them ({@link parameterArithmeticTexts}). The body's own
* text only: what a VALUE runs when the expansion re-reads it is not followed (the station asks, see its caller). */
export declare function parameterBodySubstitutions(body: string, table: BindingTable | undefined): string[];
/**
* The substitutions the shell's ARITHMETIC evaluator runs while it evaluates `text`: every `$(…)`, backquote or process
* substitution inside an array SUBSCRIPT of it (`a[$(…)]` — quoted or not: the evaluator re-reads the text it is
* handed), and — for each name the text refers to whose value the table holds — the same of that value (the evaluator
* evaluates a variable's value as arithmetic too, through any chain of names). A name the table does not settle
* contributes the literal values its bindings left (an array's elements) and nothing else: any other value is data the
* text does not hold. A name already on the chain is a cycle (bash refuses
* it). Each body is shell text the evaluator re-enters; past the reader's budget of values — or where a name's floor is
* past its own ({@link WordFloor.pastBound}: a value the text holds was let go) — the text itself is handed back as a
* body, so the segment re-enters text it did not follow (unestablished, never silent).
*/
export declare function arithmeticSubstitutions(text: string, table: BindingTable | undefined, chain?: ReadonlySet<string>, budget?: {
left: number;
}): string[];
/** The text of every `[…]` subscript in an arithmetic text (nested brackets balanced; an unclosed one runs to the end). */
export declare function subscriptsOf(text: string): string[];
/** The substitution bodies a subscript's text carries, its quotes removed first (the evaluator sees the text without
* them; `keepQuotes` = the shell expands the text as it stands); a text the lexer refuses is returned whole (a body
* nothing could read is still re-entered). */
export declare function substitutionBodies(subscript: string, keepQuotes?: boolean): string[];