From 3c513ddda7903c95da80ec49d6ee3e79a89b0e0c Mon Sep 17 00:00:00 2001 From: Chris Tate Date: Sun, 29 Nov 2026 08:48:05 +0000 Subject: [PATCH] Answer typeof for declared-only globals like Node (#4235) * Answer typeof for declared-only globals like Node - typeof on a name that is only declared (declare global namespace, declare class, declare enum) with no runtime value returns "undefined" instead of throwing or refusing. - A differential test covers each declaration form against Node. * Answer typeof for ambient declarations of Node globals * Answer a Node global's kind under a computed global write --- .../frontend/lowering/expressions/typeof.ts | 67 +++++++++++++++--- .../src/frontend/lowering/lower-namespaces.ts | 58 ++++++++++++++++ .../src/frontend/lowering/static-typeof.ts | 32 +++++---- .../typeof-erased-global-declarations.ts.json | 4 ++ .../typeof-erased-global-declarations.ts | 68 +++++++++++++++++++ .../typeof-erased-global-declarations.ts.json | 1 + 6 files changed, 205 insertions(+), 25 deletions(-) create mode 100644 packages/compiler/test/ts7/baselines/order-parity/tests/corpus/typeof-erased-global-declarations.ts.json create mode 100644 tests/corpus/typeof-erased-global-declarations.ts create mode 100644 tests/harness/corpus-costs/typeof-erased-global-declarations.ts.json diff --git a/packages/compiler/src/frontend/lowering/expressions/typeof.ts b/packages/compiler/src/frontend/lowering/expressions/typeof.ts index 6729992786..9dbde9549a 100644 --- a/packages/compiler/src/frontend/lowering/expressions/typeof.ts +++ b/packages/compiler/src/frontend/lowering/expressions/typeof.ts @@ -43,9 +43,8 @@ import { varRef } from "../../../ir/build.js"; import { isExecExceptionType, refuseExecExceptionCode } from "../builtins/errors.js"; import { InternalCompilerError } from "../../../errors.js"; import { + ambientErasedValueSymbolOf, ambientTypesOnlyGlobalSymbolOf, - ambientUndefinedFnSymbolOf, - ambientUndefinedVarSymbolOf, isNodeUndefinedGlobalRoot, nodeUndefinedGlobalProperty, } from "../lower-namespaces.js"; @@ -448,17 +447,63 @@ function lowerTypeofAnswer( if (isNodeUndefinedGlobalRoot(lowerer, tested, sym)) { return { kind: "strLit", value: "undefined", type: STRING, loc }; } - // A name the program declares ambiently but nothing defines - // (`declare const Bun`, `declare function f(): void`): Node erases the - // declaration, so typeof answers "undefined" without reading it, where - // a read throws ReferenceError. + // A name the program only DECLARES — an initializer-less ambient + // variable or body-less function, a `declare class`, `declare + // namespace` (a `declare global` augmentation included), a `declare + // enum`, or a global only a types-only package declares — has no + // runtime binding: typeof an unresolvable reference answers + // "undefined" and never throws, so no value read (and certainly no + // ReferenceError) may be emitted. A program that may have installed + // the name on the global object answers that property at run time + // instead, because an unbound identifier read consults the global + // object. if ( - ambientUndefinedVarSymbolOf(lowerer, tested) || - ambientUndefinedFnSymbolOf(lowerer, tested) || - (ambientTypesOnlyGlobalSymbolOf(lowerer, tested) && - !programMayWriteGlobalName(lowerer, tested.text, tested)) + ambientErasedValueSymbolOf(lowerer, tested) || + ambientTypesOnlyGlobalSymbolOf(lowerer, tested) ) { - return { kind: "strLit", value: "undefined", type: STRING, loc }; + // The erased declaration leaves the identifier to the global object + // at run time. A name Node's global object defines answers that + // value's kind (`declare class Buffer {}` still names Node's global + // Buffer); only a name the global object lacks is unresolvable. + const kind = nodeGlobalKind(tested.text); + const answer = kind === null ? null : kind.kind === "function" ? "function" : kind.type; + // An accessor that throws or a platform-dependent value has no static + // typeof answer; the runtime read below answers it. + const staticAnswer = + answer === null || answer === "throws" || answer === "platform" ? null : answer; + if (!programMayWriteGlobalName(lowerer, tested.text, tested)) { + if (staticAnswer !== null) + return { kind: "strLit", value: staticAnswer, type: STRING, loc }; + if (kind === null) return { kind: "strLit", value: "undefined", type: STRING, loc }; + } + const name: IrExpr = { kind: "strLit", value: tested.text, type: STRING, loc }; + const installed: IrExpr = { + kind: "libCall", + fn: "dyn.typeof", + args: [{ kind: "libCall", fn: "global.bindingValue", args: [name], type: DYN, loc }], + type: STRING, + loc, + }; + // The program may install the name on the global object — an unrelated + // computed write can name any property, so the census cannot rule it + // out — and a property it installed answers that value. A property it + // did not install leaves the identifier to Node's global object, which + // answers its kind rather than "undefined". + if (staticAnswer === null) return installed; + return { + kind: "ternary", + cond: { + kind: "libCall", + fn: "global.bindingHas", + args: [name], + type: BOOL, + loc, + }, + then: installed, + else_: { kind: "strLit", value: staticAnswer, type: STRING, loc }, + type: STRING, + loc, + }; } // `const { inspect } = require("util")` / `import { inspect } from // "node:util"`: a binding of a builtin module's exported function, diff --git a/packages/compiler/src/frontend/lowering/lower-namespaces.ts b/packages/compiler/src/frontend/lowering/lower-namespaces.ts index 172069efa4..acaa14d874 100644 --- a/packages/compiler/src/frontend/lowering/lower-namespaces.ts +++ b/packages/compiler/src/frontend/lowering/lower-namespaces.ts @@ -1117,6 +1117,64 @@ export function nsUndefRead( }; } +/** The symbol of a NAME whose declarations are all AMBIENT value forms + * TypeScript erases and nothing implements — `declare class`, + * `declare namespace` (including a `declare global { … }` augmentation), + * `declare enum`, or an initializer-less `declare let/var/const` / + * body-less `declare function` in a declaration file. Node has no binding + * for such a name, so `typeof ` answers "undefined" (typeof an + * unresolvable reference never throws, ECMA-262), even though the checker + * types the name. Null for the standard library and Node's own types, + * imports and aliases, island bindings, and any declaration that carries + * a runtime value or implementation. */ +export function ambientErasedValueSymbolOf( + lowerer: Lowerer, + ident: ts.Identifier, +): ts.Symbol | null { + if (lowerer.isStdlibSymbol(lowerer.checker.getSymbolAtLocation(ident))) return null; + if (NODE_GLOBALS_WITHOUT_NATIVE.has(ident.text)) return null; + if (isIslandImportBinding(lowerer, ident)) return null; + const checkerSym = lowerer.checker.getSymbolAtLocation(ident); + if (checkerSym === undefined || (checkerSym.flags & ts.SymbolFlags.Alias) !== 0) return null; + const sym = lowerer.resolveValueSymbol(ident); + if (!sym) return null; + // The variable and function forms keep their own narrower predicates + // (they exclude package-shim intrinsics and define the exact message). + if (ambientUndefinedVarSymbolOf(lowerer, ident) || ambientUndefinedFnSymbolOf(lowerer, ident)) + return sym; + let sawErased = false; + for (const d of sym.declarations) { + // Type-world partners of a value declaration declare no value. + if (ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d)) continue; + if (!ambientDeclarationNode(d)) return null; + if (ts.isModuleDeclaration(d) || ts.isClassDeclaration(d) || ts.isEnumDeclaration(d)) { + sawErased = true; + continue; + } + if (ts.isVariableDeclaration(d) && d.initializer === undefined) { + sawErased = true; + continue; + } + if (ts.isFunctionDeclaration(d) && d.body === undefined) { + sawErased = true; + continue; + } + return null; + } + return sawErased ? sym : null; +} + +/** Whether a declaration is AMBIENT in TypeScript's sense: it carries the + * `declare` modifier itself or an ancestor does (`declare global { … }` + * passes it down), or it lives in a declaration file. */ +function ambientDeclarationNode(declaration: ts.Node): boolean { + for (let node: ts.Node | undefined = declaration; node !== undefined; node = node.parent) { + if ((ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Ambient) !== 0) return true; + if (ts.isSourceFile(node)) return node.isDeclarationFile; + } + return false; +} + /** True when `node` executes during module INIT (top-level statement * position — namespace bodies included — not inside any function-like * body). Class static blocks and field initializers count as init-time: diff --git a/packages/compiler/src/frontend/lowering/static-typeof.ts b/packages/compiler/src/frontend/lowering/static-typeof.ts index 2600cb9d01..86b1f4ae0e 100644 --- a/packages/compiler/src/frontend/lowering/static-typeof.ts +++ b/packages/compiler/src/frontend/lowering/static-typeof.ts @@ -6,11 +6,8 @@ import { hostGlobalNameOfIdentifier } from "./host-globals.js"; import { undeclaredGlobalTypeof } from "./global-object-names.js"; import { erasedGlobalBindingOf, programMayWriteGlobalName } from "./global-object-writes.js"; import { isUnresolvedCjsExports } from "./cjs-exports-object.js"; -import { - ambientTypesOnlyGlobalSymbolOf, - ambientUndefinedFnSymbolOf, - ambientUndefinedVarSymbolOf, -} from "./lower-namespaces.js"; +import { ambientErasedValueSymbolOf, ambientTypesOnlyGlobalSymbolOf } from "./lower-namespaces.js"; +import { nodeGlobalKind } from "./node-values.js"; /** The answer `typeof ` gives without evaluating anything, for * the global-detection idioms (`typeof window < "u"`, `typeof global !== @@ -52,15 +49,22 @@ export function staticTypeofAnswer(lowerer: Lowerer, operand: ts.Expression): st if (erasedGlobalBindingOf(lowerer, e) && programMayWriteGlobalName(lowerer, e.text, e)) return null; // A name the program declares ambiently but nothing defines (`declare - // const Bun`): undeclared at run time. - if ( - ambientUndefinedVarSymbolOf(lowerer, e) || - ambientUndefinedFnSymbolOf(lowerer, e) || - // A name the program installs on the global object answers at run time - // (typeof.ts reads it), so no static answer folds. - (ambientTypesOnlyGlobalSymbolOf(lowerer, e) && !programMayWriteGlobalName(lowerer, e.text, e)) - ) - return "undefined"; + // const Bun`, `declare namespace`, `declare class`, `declare enum`): + // TypeScript erases it, so the reference is unresolvable at run time and + // typeof answers "undefined" — unless Node's global object defines the + // name, which the erased declaration leaves the identifier to + // (`declare class Buffer {}` still names Node's global Buffer). A name + // the program installs on the global object answers at run time + // (typeof.ts reads it), so no static answer folds. + if (ambientErasedValueSymbolOf(lowerer, e) || ambientTypesOnlyGlobalSymbolOf(lowerer, e)) { + if (programMayWriteGlobalName(lowerer, e.text, e)) return null; + const kind = nodeGlobalKind(e.text); + if (kind === null) return "undefined"; + const answer = kind.kind === "function" ? "function" : kind.type; + // An accessor that throws or a platform-dependent value has no static + // answer; typeof.ts reads it at run time. + return answer === "throws" || answer === "platform" ? null : answer; + } return null; } diff --git a/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/typeof-erased-global-declarations.ts.json b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/typeof-erased-global-declarations.ts.json new file mode 100644 index 0000000000..8103be7928 --- /dev/null +++ b/packages/compiler/test/ts7/baselines/order-parity/tests/corpus/typeof-erased-global-declarations.ts.json @@ -0,0 +1,4 @@ +{ + "order": ["/tests/corpus/typeof-erased-global-declarations.ts"], + "diags": [] +} diff --git a/tests/corpus/typeof-erased-global-declarations.ts b/tests/corpus/typeof-erased-global-declarations.ts new file mode 100644 index 0000000000..3522b31372 --- /dev/null +++ b/tests/corpus/typeof-erased-global-declarations.ts @@ -0,0 +1,68 @@ +// Names a program only DECLARES for their types — an ambient namespace, class, +// enum, function or variable, in a `declare global` augmentation or at the +// file's top level — have no runtime binding. `typeof` on an unresolvable +// reference answers "undefined" and never throws (ECMA-262), so the erased +// declaration must not lower to a value read that throws Node's ReferenceError. +export {}; + +declare global { + var __scrTypedVar: string; + function __scrTypedFn(): void; + class __scrTypedClass { + x: number; + } + namespace __scrTypedNs { + const y: number; + } + enum __scrTypedEnum { + A, + } +} + +declare class __scrLocalClass { + x: number; +} +declare enum __scrLocalEnum { + A, +} +declare namespace __scrLocalNs { + const z: number; +} + +// These erase too, but the names are Node's own globals: the identifier +// still resolves to the global object at run time, so typeof answers what +// Node has there (`declare class Buffer {}` names Node's Buffer). +declare class Buffer {} +declare function fetch(input: string): Promise; +declare const process: { env: Record }; +declare const navigator: { userAgent: string }; + +console.log( + typeof __scrTypedVar, + typeof __scrTypedFn, + typeof __scrTypedClass, + typeof __scrTypedNs, + typeof __scrTypedEnum, +); +console.log(typeof __scrLocalClass, typeof __scrLocalEnum, typeof __scrLocalNs); +console.log(typeof Buffer, typeof fetch, typeof process, typeof navigator); +if (typeof Buffer === "undefined") console.log("buffer absent"); +else console.log("buffer present"); +if (typeof __scrTypedNs === "undefined") console.log("namespace absent"); +const absent = typeof __scrTypedClass !== "undefined"; +console.log(absent, typeof __scrTypedClass === "function"); + +// A program that installs one of these names on the global object answers +// that property, because an unbound identifier read consults the global +// object. +(globalThis as Record).__scrTypedClass = 7; +(globalThis as Record).__scrTypedNs = "installed"; +(globalThis as Record).__scrLocalEnum = "local"; +console.log(typeof __scrTypedClass, typeof __scrTypedNs, typeof __scrLocalEnum); + +// A computed write can name any global property, so the program-wide census +// cannot rule a name out. A name the program never installs still leaves the +// identifier to Node's global object, which answers its kind rather than +// "undefined". +(globalThis as Record)["__scr" + "UnrelatedWrite"] = 1; +console.log(typeof Buffer); diff --git a/tests/harness/corpus-costs/typeof-erased-global-declarations.ts.json b/tests/harness/corpus-costs/typeof-erased-global-declarations.ts.json new file mode 100644 index 0000000000..a7f6459a76 --- /dev/null +++ b/tests/harness/corpus-costs/typeof-erased-global-declarations.ts.json @@ -0,0 +1 @@ +{ "plain": 2800, "san": 4500 }