forked from cflmy/deepseek-harness
fix(infra): resolve Cordis root bindings through scopes and symbols
This commit is contained in:
1 parent
a29dafde97
commit
531d65f938
5 files changed
+194
-52
No files matched your search
@@ -9,11 +9,11 @@
|
||||
en: c6935cb7ef54f299
|
||||
zh: 214ed828b3201539
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context/decision:
|
||||
en: 9b3238a642603e28
|
||||
zh: a4b5601157f621b7
|
||||
en: f44b447ba08b8572
|
||||
zh: 18347eed362c62d8
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context/alternatives-considered:
|
||||
en: 81d959fa34f3e682
|
||||
zh: 861f22528134e255
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context/consequences:
|
||||
en: d85154ce0a279c1f
|
||||
zh: 7672ff57971ef221
|
||||
en: 6067864f7a2ff1c8
|
||||
zh: df4c9af26a1abd5d
|
||||
@@ -12,7 +12,7 @@ The repository contains such reads across boot, host, preset, protocol, experime
|
||||
|
||||
## Decision
|
||||
|
||||
New reads of the Cordis root context are prohibited in first-party JavaScript and TypeScript, including tests, fixtures, and scripts. The [checker](../../../../scripts/verify-cordis-root.ts), exposed as `pnpm run verify-cordis-root`, uses the TypeScript syntax tree. A read is `Context.root`, `Context['root']`, or a destructured `root` on a value binding of `Context` imported from `@deepseek-ai/cordis`, including renamed and namespace imports, and any string literal whose value is exactly `cordis.root`, the key behind `Symbol.for('cordis.root')`. Type positions, comments, other strings, and source text embedded in a template are not reads.
|
||||
New reads of the Cordis root context are prohibited in first-party JavaScript and TypeScript, including tests, fixtures, and scripts. The [checker](../../../../scripts/verify-cordis-root.ts), exposed as `pnpm run verify-cordis-root`, uses the TypeScript syntax tree and a type checker over each file alone. A read names the root symbol through a Cordis value binding of `Context` or `symbols`: `.root`, `['root']`, or `root` destructured in a declaration, a parameter default, or an assignment. A binding comes from `@deepseek-ai/cordis` or one of its subpaths through a static import, including renamed, default, namespace, and `import =` forms, or through a destructured or namespace `import()` or `require()` result; a local that shadows the import is not a binding. Any string literal whose value is exactly `cordis.root`, the key behind `Symbol.for('cordis.root')`, is also a read. Type positions, interfaces, type aliases, ambient declarations, comments, other strings, and source text embedded in a template are not reads.
|
||||
|
||||
Existing reads have an exact baseline in `scripts/cordis-root.baseline.json`, kept by [the shared inventory module](../../../../scripts/baseline-inventory.ts) under the rules of the [unknown-cast inventory](2026-09-19-no-unknown-casts.md): baseline edits only delete entries or decrease counts, `--prune` removes retired entries and refuses to write while new reads exist, and no command adds an allowance. A read's fingerprint covers the tokens of the element access whose key is the root symbol, so a recorded read moved to another receiver is a new finding.
|
||||
|
||||
@@ -28,4 +28,4 @@ Files that exercise the root contract itself are listed with a reason in `CORDIS
|
||||
|
||||
## Consequences
|
||||
|
||||
Owners must remove a recorded read before changing its receiver or moving it into an unlisted file, and prune its entry after removal. Passing the check establishes that no unlisted syntactic root read exists. It does not detect a root context obtained through another value, such as a stored reference, a service that returns it, or code assembled from strings at runtime.
|
||||
Owners must remove a recorded read before changing its receiver or moving it into an unlisted file, and prune its entry after removal. Passing the check establishes that no unlisted syntactic root read exists. It does not detect a root context obtained through another value, such as a stored reference, an alias of `Context`, a service that returns it, or code assembled from strings at runtime.
|
||||
@@ -12,7 +12,7 @@ Status: implemented
|
||||
|
||||
## 决定
|
||||
|
||||
第一方 JavaScript 和 TypeScript(包括测试、fixture 和脚本)禁止新增对 Cordis 根上下文的读取。[检查器](../../../../scripts/verify-cordis-root.ts)通过 `pnpm run verify-cordis-root` 运行,使用 TypeScript 语法树。读取指:对从 `@deepseek-ai/cordis` 导入的 `Context` 值绑定(包括重命名导入和命名空间导入)的 `Context.root`、`Context['root']` 或解构出的 `root`,以及值恰为 `cordis.root` 的任何字符串字面量,即 `Symbol.for('cordis.root')` 背后的键。类型位置、注释、其他字符串以及嵌入模板中的源码文本不算读取。
|
||||
第一方 JavaScript 和 TypeScript(包括测试、fixture 和脚本)禁止新增对 Cordis 根上下文的读取。[检查器](../../../../scripts/verify-cordis-root.ts)通过 `pnpm run verify-cordis-root` 运行,使用 TypeScript 语法树,并对每个文件单独建立类型检查器。读取指通过 `Context` 或 `symbols` 的 Cordis 值绑定访问根符号:`.root`、`['root']`,或在声明、参数默认值或赋值中解构出的 `root`。绑定来自 `@deepseek-ai/cordis` 或其子路径,可以是静态导入(包括重命名、默认、命名空间和 `import =` 形式),也可以是解构或整体接收的 `import()` 或 `require()` 结果;遮蔽导入的局部变量不是绑定。值恰为 `cordis.root` 的任何字符串字面量也算读取,即 `Symbol.for('cordis.root')` 背后的键。类型位置、接口、类型别名、ambient 声明、注释、其他字符串以及嵌入模板中的源码文本不算读取。
|
||||
|
||||
现有读取使用 `scripts/cordis-root.baseline.json` 中的精确基线记录,由[共享清单模块](../../../../scripts/baseline-inventory.ts)按 [unknown 类型断言清单](2026-09-19-no-unknown-casts.zh.md)的规则维护:基线修改只能删除条目或减少次数,`--prune` 删除已失效的条目并在存在新读取时拒绝写入,且没有任何命令可以添加放行。读取的指纹覆盖以根符号为键的元素访问的 token,因此把已记录的读取换到另一个接收者上会产生新的检查发现。
|
||||
|
||||
@@ -28,4 +28,4 @@ Status: implemented
|
||||
|
||||
## 影响
|
||||
|
||||
所有者在更换已记录读取的接收者或将其移入未登记的文件之前,必须先移除该读取,并在移除后裁剪其条目。通过此检查表明不存在未登记的语法层面的根读取。它无法检测通过其他值获得的根上下文,例如保存的引用、返回根上下文的服务,或运行时由字符串拼装的代码。
|
||||
所有者在更换已记录读取的接收者或将其移入未登记的文件之前,必须先移除该读取,并在移除后裁剪其条目。通过此检查表明不存在未登记的语法层面的根读取。它无法检测通过其他值获得的根上下文,例如保存的引用、`Context` 的别名、返回根上下文的服务,或运行时由字符串拼装的代码。
|
||||
@@ -44,6 +44,23 @@ describe('Cordis root read syntax', () => {
|
||||
['a symbol key held in a constant', "const key = 'cordis.root'", 1],
|
||||
['several reads', `${header}ctx[Context.root].on('a', f); ctx[Context.root].on('b', g)`, 2],
|
||||
['a TSX expression', `${header}export const view = <View ctx={ctx[Context.root]} />`, 1],
|
||||
['the symbols table', "import { symbols } from '@deepseek-ai/cordis'\nctx[symbols.root]", 1],
|
||||
['a renamed symbols table', "import { symbols as cordisSymbols } from '@deepseek-ai/cordis'\nctx[cordisSymbols['root']]", 1],
|
||||
['the symbols table of a namespace', "import * as cordis from '@deepseek-ai/cordis'\nctx[cordis.symbols.root]", 1],
|
||||
['root destructured from the symbols table', "import { symbols } from '@deepseek-ai/cordis'\nconst { root } = symbols", 1],
|
||||
['a subpath import', "import { Context } from '@deepseek-ai/cordis/src/index.ts'\nctx[Context.root]", 1],
|
||||
['a default import', "import cordis from '@deepseek-ai/cordis'\nctx[cordis.Context.root]", 1],
|
||||
['an import-equals namespace', "import cordis = require('@deepseek-ai/cordis')\nctx[cordis.Context.root]", 1],
|
||||
['a destructured dynamic import', "const { Context } = await import('@deepseek-ai/cordis')\nctx[Context.root]", 1],
|
||||
['a renamed destructured dynamic import', "const { Context: C } = await import('@deepseek-ai/cordis')\nctx[C.root]", 1],
|
||||
['a namespace dynamic import', "const cordis = await import('@deepseek-ai/cordis')\nctx[cordis.Context.root]", 1],
|
||||
['a destructured require', "const { Context } = require('@deepseek-ai/cordis')\nctx[Context.root]", 1],
|
||||
['a destructuring assignment', `${header}let key; ({ root: key } = Context)`, 1],
|
||||
['a shorthand destructuring assignment', `${header}let root; ({ root } = Context)`, 1],
|
||||
['a parameter default', `${header}function f({ root } = Context) { return root }`, 1],
|
||||
['a nested binding default', `${header}const { a: { root } = Context } = value`, 1],
|
||||
['a computed class member', `${header}class Holder { [Context.root] = undefined }`, 1],
|
||||
['a class extends clause', `${header}class Holder extends mixin(Context.root) {}`, 1],
|
||||
])('finds %s', (_name, text, count) => {
|
||||
expect(findCordisRootReads('input.tsx', text)).toHaveLength(count)
|
||||
})
|
||||
@@ -60,10 +77,31 @@ describe('Cordis root read syntax', () => {
|
||||
['another static of Context', `${header}ctx[Context.isolate]`],
|
||||
['a root member of another value', `${header}const dir = project.root`],
|
||||
['a destructured root of another value', `${header}const { root } = project`],
|
||||
['a parameter that shadows the import', `${header}function f(Context: { root: string }) { return Context.root }`],
|
||||
['a local that shadows the import', `${header}{ const Context = project; Context.root }`],
|
||||
['a parameter that shadows a namespace', "import * as cordis from '@deepseek-ai/cordis'\nfunction f(cordis: any) { return cordis.Context.root }"],
|
||||
['an interface member', `${header}interface Holder { [Context.root]: Context }`],
|
||||
['a type literal member', `${header}type Holder = { [Context.root]: Context }`],
|
||||
['an ambient class member', `${header}declare class Holder { [Context.root]: Context }`],
|
||||
['an ambient module member', `${header}declare module 'x' { const key: typeof Context.root; export const value = Context.root }`],
|
||||
['an ambient class field', `${header}class Holder { declare [Context.root]: Context }`],
|
||||
['an implements clause', `${header}class Holder implements Base<typeof Context.root> {}`],
|
||||
['another member of the symbols table', "import { symbols } from '@deepseek-ai/cordis'\nctx[symbols.original]"],
|
||||
['a dynamic import of another module', "const { Context } = await import('./context.ts')\nctx[Context.root]"],
|
||||
['a destructuring assignment of another member', `${header}let isolate; ({ isolate } = Context)`],
|
||||
])('ignores %s', (_name, text) => {
|
||||
expect(findCordisRootReads('input.ts', text)).toEqual([])
|
||||
})
|
||||
|
||||
it('resolves bindings in JavaScript modules', () => {
|
||||
expect(findCordisRootReads('input.mjs', "const { Context } = await import('@deepseek-ai/cordis')\nctx[Context.root]")).toHaveLength(1)
|
||||
expect(findCordisRootReads('input.cjs', "const { symbols } = require('@deepseek-ai/cordis')\nfunction f(symbols) { return symbols.root }")).toEqual([])
|
||||
})
|
||||
|
||||
it('skips declaration files', () => {
|
||||
expect(findCordisRootReads('input.d.ts', `${header}export declare const key: typeof Context.root\nexport const value = Context.root`)).toEqual([])
|
||||
})
|
||||
|
||||
it('reports normalized paths and the read line', () => {
|
||||
const [found] = findCordisRootReads('packages\\example\\index.ts', `${header}\nctx[Context.root]`)
|
||||
expect(found).toMatchObject({ file: 'packages/example/index.ts', line: 3 })
|
||||
|
||||
+148
-44
@@ -1,10 +1,18 @@
|
||||
/**
|
||||
* Reject new reads of the Cordis root context, retiring the recorded existing reads.
|
||||
*
|
||||
* A read is `Context.root`, `Context['root']`, or a destructured `root` on a value binding of
|
||||
* `Context` imported from `@deepseek-ai/cordis`, including a renamed or namespace import, and any
|
||||
* string literal whose value is exactly `cordis.root`, the global symbol key behind
|
||||
* `Symbol.for('cordis.root')`. Type positions such as `typeof Context.root` are not reads.
|
||||
* A read names the root symbol through a Cordis value binding: `Context.root` or `symbols.root`,
|
||||
* their `['root']` forms, or `root` destructured from either in a declaration, a parameter default,
|
||||
* or an assignment. A binding comes from `@deepseek-ai/cordis` or one of its subpaths through a
|
||||
* static import, including renamed and namespace imports, or through a destructured or namespace
|
||||
* `import()` or `require()` result. References resolve through the file's own scopes, so a local
|
||||
* that shadows the import is not a binding. Any string literal whose value is exactly `cordis.root`,
|
||||
* the global symbol key behind `Symbol.for('cordis.root')`, is also a read. Type positions,
|
||||
* interfaces, type aliases, and ambient declarations are erased and contain no reads.
|
||||
*
|
||||
* The check is syntactic: a root context reached through another value, such as a stored
|
||||
* reference, an alias of `Context`, a service that returns it, or source text assembled at run
|
||||
* time, is outside it.
|
||||
*
|
||||
* A finding's identity covers the syntax tokens of the access to the root: the element access whose
|
||||
* key is the root symbol when one encloses it, otherwise the read itself. Existing reads are
|
||||
@@ -27,12 +35,15 @@ import {
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
|
||||
/** Module that exports the Cordis `Context` class. */
|
||||
/** Package that exports the Cordis `Context` class and the `symbols` table. */
|
||||
const CORDIS_MODULE = '@deepseek-ai/cordis'
|
||||
|
||||
/** Global symbol key of `Context.root`. */
|
||||
const ROOT_SYMBOL_KEY = 'cordis.root'
|
||||
|
||||
/** Cordis exports that hold the root symbol as their `root` member. */
|
||||
const ROOT_HOLDERS = new Set(['Context', 'symbols'])
|
||||
|
||||
/**
|
||||
* Files that exercise the root context itself, keyed by repository path, with the reason each needs
|
||||
* it. A key whose file no longer reads the root fails the gate.
|
||||
@@ -55,37 +66,111 @@ export interface CordisRootRead {
|
||||
fingerprint: string
|
||||
}
|
||||
|
||||
/** Local names that refer to the Cordis `Context` value or to the Cordis module namespace. */
|
||||
/** Declared symbols that refer to a Cordis root holder or to the Cordis module namespace. */
|
||||
interface CordisBindings {
|
||||
context: Set<string>
|
||||
namespace: Set<string>
|
||||
checker: ts.TypeChecker
|
||||
holders: Set<ts.Symbol>
|
||||
namespaces: Set<ts.Symbol>
|
||||
}
|
||||
|
||||
function cordisBindings(source: ts.SourceFile): CordisBindings {
|
||||
const bindings: CordisBindings = { context: new Set(), namespace: new Set() }
|
||||
for (const statement of source.statements) {
|
||||
if (!ts.isImportDeclaration(statement) || statement.importClause === undefined) continue
|
||||
if (!ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== CORDIS_MODULE) continue
|
||||
const clause = statement.importClause
|
||||
if (clause.phaseModifier === ts.SyntaxKind.TypeKeyword || clause.namedBindings === undefined) continue
|
||||
if (ts.isNamespaceImport(clause.namedBindings)) {
|
||||
bindings.namespace.add(clause.namedBindings.name.text)
|
||||
continue
|
||||
function isCordisSpecifier(node: ts.Node | undefined): boolean {
|
||||
return node !== undefined && ts.isStringLiteralLike(node)
|
||||
&& (node.text === CORDIS_MODULE || node.text.startsWith(`${CORDIS_MODULE}/`))
|
||||
}
|
||||
|
||||
/** Whether an initializer evaluates to the Cordis module: `import()`, `await import()`, or `require()`. */
|
||||
function loadsCordis(node: ts.Expression): boolean {
|
||||
if (ts.isParenthesizedExpression(node) || ts.isAwaitExpression(node)) return loadsCordis(node.expression)
|
||||
if (!ts.isCallExpression(node) || node.arguments.length === 0) return false
|
||||
const callee = node.expression
|
||||
const loader = callee.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(callee) && callee.text === 'require')
|
||||
return loader && isCordisSpecifier(node.arguments[0])
|
||||
}
|
||||
|
||||
function propertyText(name: ts.PropertyName | ts.BindingName): string | undefined {
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) return name.text
|
||||
if (ts.isComputedPropertyName(name) && ts.isStringLiteralLike(name.expression)) return name.expression.text
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Type-check one file in isolation, so references resolve through its own scopes only. */
|
||||
function isolatedChecker(source: ts.SourceFile): ts.TypeChecker {
|
||||
const options: ts.CompilerOptions = { allowJs: true, noLib: true, noResolve: true, types: [] }
|
||||
const host: ts.CompilerHost = {
|
||||
getSourceFile: fileName => (fileName === source.fileName ? source : undefined),
|
||||
getDefaultLibFileName: () => 'lib.d.ts',
|
||||
writeFile: () => undefined,
|
||||
getCurrentDirectory: () => '/',
|
||||
getCanonicalFileName: fileName => fileName,
|
||||
useCaseSensitiveFileNames: () => true,
|
||||
getNewLine: () => '\n',
|
||||
fileExists: fileName => fileName === source.fileName,
|
||||
readFile: () => undefined,
|
||||
}
|
||||
return ts.createProgram({ rootNames: [source.fileName], options, host }).getTypeChecker()
|
||||
}
|
||||
|
||||
function cordisBindings(source: ts.SourceFile): CordisBindings | undefined {
|
||||
if (!source.text.includes(CORDIS_MODULE)) return undefined
|
||||
const checker = isolatedChecker(source)
|
||||
const bindings: CordisBindings = { checker, holders: new Set(), namespaces: new Set() }
|
||||
const add = (set: Set<ts.Symbol>, name: ts.Identifier): void => {
|
||||
const symbol = checker.getSymbolAtLocation(name)
|
||||
if (symbol !== undefined) set.add(symbol)
|
||||
}
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (ts.isImportDeclaration(node) && isCordisSpecifier(node.moduleSpecifier)) {
|
||||
const clause = node.importClause
|
||||
if (clause === undefined || clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return
|
||||
if (clause.name !== undefined) add(bindings.namespaces, clause.name)
|
||||
if (clause.namedBindings !== undefined && ts.isNamespaceImport(clause.namedBindings)) {
|
||||
add(bindings.namespaces, clause.namedBindings.name)
|
||||
} else {
|
||||
for (const element of clause.namedBindings?.elements ?? []) {
|
||||
if (!element.isTypeOnly && ROOT_HOLDERS.has((element.propertyName ?? element.name).text)) {
|
||||
add(bindings.holders, element.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
for (const element of clause.namedBindings.elements) {
|
||||
if (!element.isTypeOnly && (element.propertyName ?? element.name).text === 'Context') {
|
||||
bindings.context.add(element.name.text)
|
||||
if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference)
|
||||
&& isCordisSpecifier(node.moduleReference.expression)) {
|
||||
add(bindings.namespaces, node.name)
|
||||
return
|
||||
}
|
||||
if (ts.isVariableDeclaration(node) && node.initializer !== undefined && loadsCordis(node.initializer)) {
|
||||
if (ts.isIdentifier(node.name)) add(bindings.namespaces, node.name)
|
||||
else if (ts.isObjectBindingPattern(node.name)) {
|
||||
for (const element of node.name.elements) {
|
||||
const exported = propertyText(element.propertyName ?? element.name)
|
||||
if (exported !== undefined && ROOT_HOLDERS.has(exported) && ts.isIdentifier(element.name)) {
|
||||
add(bindings.holders, element.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
return bindings
|
||||
visit(source)
|
||||
return bindings.holders.size + bindings.namespaces.size === 0 ? undefined : bindings
|
||||
}
|
||||
|
||||
function isContextValue(node: ts.Expression, bindings: CordisBindings): boolean {
|
||||
if (ts.isParenthesizedExpression(node)) return isContextValue(node.expression, bindings)
|
||||
if (ts.isIdentifier(node)) return bindings.context.has(node.text)
|
||||
return ts.isPropertyAccessExpression(node) && node.name.text === 'Context'
|
||||
&& ts.isIdentifier(node.expression) && bindings.namespace.has(node.expression.text)
|
||||
function refersTo(node: ts.Identifier, set: Set<ts.Symbol>, bindings: CordisBindings): boolean {
|
||||
const symbol = bindings.checker.getSymbolAtLocation(node)
|
||||
return symbol !== undefined && set.has(symbol)
|
||||
}
|
||||
|
||||
/** Whether an expression evaluates to `Context` or `symbols` from Cordis. */
|
||||
function isRootHolder(node: ts.Expression, bindings: CordisBindings): boolean {
|
||||
if (ts.isParenthesizedExpression(node)) return isRootHolder(node.expression, bindings)
|
||||
if (ts.isIdentifier(node)) return refersTo(node, bindings.holders, bindings)
|
||||
const member = ts.isPropertyAccessExpression(node) ? node.name.text
|
||||
: ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) ? node.argumentExpression.text
|
||||
: undefined
|
||||
if (member === undefined || !ROOT_HOLDERS.has(member)) return false
|
||||
const namespace = (node as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression
|
||||
return ts.isIdentifier(namespace) && refersTo(namespace, bindings.namespaces, bindings)
|
||||
}
|
||||
|
||||
function isRootKey(node: ts.Expression): boolean {
|
||||
@@ -93,21 +178,42 @@ function isRootKey(node: ts.Expression): boolean {
|
||||
}
|
||||
|
||||
function bindsRoot(pattern: ts.ObjectBindingPattern): boolean {
|
||||
return pattern.elements.some((element) => {
|
||||
const name = element.propertyName ?? element.name
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) return name.text === 'root'
|
||||
return ts.isComputedPropertyName(name) && isRootKey(name.expression)
|
||||
return pattern.elements.some(element => propertyText(element.propertyName ?? element.name) === 'root')
|
||||
}
|
||||
|
||||
function assignsRoot(pattern: ts.ObjectLiteralExpression): boolean {
|
||||
return pattern.properties.some((property) => {
|
||||
if (ts.isShorthandPropertyAssignment(property)) return property.name.text === 'root'
|
||||
return ts.isPropertyAssignment(property) && propertyText(property.name) === 'root'
|
||||
})
|
||||
}
|
||||
|
||||
function readsRoot(node: ts.Node, bindings: CordisBindings): boolean {
|
||||
if (ts.isPropertyAccessExpression(node)) return node.name.text === 'root' && isContextValue(node.expression, bindings)
|
||||
if (ts.isElementAccessExpression(node)) return isRootKey(node.argumentExpression) && isContextValue(node.expression, bindings)
|
||||
if (ts.isVariableDeclaration(node)) {
|
||||
function readsRoot(node: ts.Node, bindings: CordisBindings | undefined): boolean {
|
||||
if (ts.isStringLiteralLike(node)) return node.text === ROOT_SYMBOL_KEY
|
||||
if (bindings === undefined) return false
|
||||
if (ts.isPropertyAccessExpression(node)) return node.name.text === 'root' && isRootHolder(node.expression, bindings)
|
||||
if (ts.isElementAccessExpression(node)) return isRootKey(node.argumentExpression) && isRootHolder(node.expression, bindings)
|
||||
if (ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isBindingElement(node)) {
|
||||
return node.initializer !== undefined && ts.isObjectBindingPattern(node.name) && bindsRoot(node.name)
|
||||
&& isContextValue(node.initializer, bindings)
|
||||
&& isRootHolder(node.initializer, bindings)
|
||||
}
|
||||
return ts.isStringLiteralLike(node) && node.text === ROOT_SYMBOL_KEY && !ts.isLiteralTypeNode(node.parent)
|
||||
return ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken
|
||||
&& ts.isObjectLiteralExpression(node.left) && assignsRoot(node.left) && isRootHolder(node.right, bindings)
|
||||
}
|
||||
|
||||
/** Whether a subtree is erased from the emitted program, so it contains no reads. */
|
||||
function isErased(node: ts.Node): boolean {
|
||||
if (ts.isSourceFile(node)) return node.isDeclarationFile
|
||||
if (ts.canHaveModifiers(node) && ts.getModifiers(node)?.some(modifier => modifier.kind === ts.SyntaxKind.DeclareKeyword)) {
|
||||
return true
|
||||
}
|
||||
if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return true
|
||||
// A class `extends` clause evaluates its expression; every other type node is erased.
|
||||
if (ts.isExpressionWithTypeArguments(node)) {
|
||||
return !(ts.isHeritageClause(node.parent) && node.parent.token === ts.SyntaxKind.ExtendsKeyword
|
||||
&& ts.isClassLike(node.parent.parent))
|
||||
}
|
||||
return ts.isTypeNode(node)
|
||||
}
|
||||
|
||||
/** The expression whose tokens identify a read: an element access keyed by the root, or the read. */
|
||||
@@ -125,26 +231,24 @@ function accessOf(node: ts.Node): ts.Node {
|
||||
* Find reads of the Cordis root context.
|
||||
* @param file - repository-relative source path; its extension selects TS or TSX parsing.
|
||||
* @param text - source contents.
|
||||
* @returns reads in AST traversal order; comments, type positions, and strings other than the
|
||||
* exact root symbol key do not match.
|
||||
* @returns reads in AST traversal order; comments, erased type syntax, shadowed names, and strings
|
||||
* other than the exact root symbol key do not match.
|
||||
*/
|
||||
export function findCordisRootReads(file: string, text: string): CordisRootRead[] {
|
||||
const normalized = file.replaceAll('\\', '/')
|
||||
const source = ts.createSourceFile(normalized, text, ts.ScriptTarget.Latest, true)
|
||||
const source = ts.createSourceFile(`/${normalized}`, text, ts.ScriptTarget.Latest, true)
|
||||
const bindings = cordisBindings(source)
|
||||
const reads: CordisRootRead[] = []
|
||||
const record = (node: ts.Node): void => {
|
||||
const access = accessOf(node)
|
||||
reads.push({
|
||||
file: normalized,
|
||||
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
|
||||
fingerprint: syntaxFingerprint(access, source),
|
||||
fingerprint: syntaxFingerprint(accessOf(node), source),
|
||||
})
|
||||
}
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (isErased(node)) return
|
||||
if (readsRoot(node, bindings)) record(node)
|
||||
// A type query names `Context.root` without reading it.
|
||||
if (ts.isTypeQueryNode(node)) return
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(source)
|
||||
|
||||
Reference in new issue
Block a user