✨ feat(vscode): 代码阅读把字典、对象字面量的值展开成键值树
This commit is contained in:
1 parent
51f2ef7bfa
commit
4930dc0d42
20 files changed
+578
-103
No files matched your search
@@ -85,11 +85,19 @@ export interface ImportFacts {
|
||||
items: ImportItem[]
|
||||
}
|
||||
|
||||
/** 字典 / 对象字面量里的一项,照源码顺序;注释不算。 */
|
||||
export type EntryFacts
|
||||
= | { kind: 'pair', key: Node, value: Node, entries?: EntryFacts[] } // 'a': 1、a: 1、[k]: v;TypeScript 的简写 { a } 键和值是同一个节点;entries 同 DeclaratorFacts.entries
|
||||
| { kind: 'spread', value: Node } // **other、...other:value 是展开的那个表达式
|
||||
| { kind: 'method', name: Node, node: Node, header: SourceSpan } // 对象字面量里的方法、getter、setter:node 是整个方法,header 同 BlockShape.header,只到主体开始之前
|
||||
|
||||
export interface DeclaratorFacts {
|
||||
/** 变量名;解构声明是整个模式。 */
|
||||
name: Node
|
||||
type?: Node
|
||||
value?: Node
|
||||
/** 值是字典 / 对象字面量(Python 的 dictionary、TypeScript 的 object)时是它的各项,空字面量是空数组;别的值没有。 */
|
||||
entries?: EntryFacts[]
|
||||
}
|
||||
|
||||
export interface VariableFacts {
|
||||
@@ -152,14 +160,18 @@ export type PreviewText = Segment[] | Markdown
|
||||
|
||||
/**
|
||||
* 属性表里的一行或一个子行讲的是哪个定义:定义出来的那个名字的节点(取自 facts,例如参数名、导入项的名称和别名、
|
||||
* 声明的变量名、类的泛型参数)在源码里的范围。跳到定义时,定义处落在这个范围里就只闪这一行;不填(第三方翻译插件可以不填)就闪整块。
|
||||
* 声明的变量名、类的泛型参数、字典 / 对象字面量一项的键)在源码里的范围。跳到定义时,定义处落在这个范围里就只闪这一行;不填(第三方翻译插件可以不填)就闪整块。
|
||||
*/
|
||||
export interface Defines { defines?: SourceRange }
|
||||
|
||||
/** 属性表里展开的一个子行:几列对齐的格子,例如参数的名称 / 类型 / 默认值。 */
|
||||
export interface PropertyItem extends Defines { cells: Segment[][] }
|
||||
/** 属性表里展开的一个子行:几列对齐的格子,例如参数的名称 / 类型 / 默认值、字典一项的键 / 值。 */
|
||||
export interface PropertyItem extends Defines {
|
||||
cells: Segment[][]
|
||||
/** 展开在这个子行下面的下一层子行(字典 / 对象的值又是字典 / 对象时,它的各项);一层层可以一直往下套。 */
|
||||
items?: PropertyItem[]
|
||||
}
|
||||
|
||||
/** 属性表的一行:左列属性名,右列着色的值或 Markdown 说明;items 是展开在这一行下面的子行(输入参数、导入项)。 */
|
||||
/** 属性表的一行:左列属性名,右列着色的值或 Markdown 说明;items 是展开在这一行下面的子行(输入参数、导入项、字典 / 对象的各项)。 */
|
||||
export interface PropertyRow extends Defines {
|
||||
label: string
|
||||
value: PreviewText
|
||||
|
||||
@@ -236,6 +236,35 @@ describe('python 属性表信息(facts)', () => {
|
||||
expect(found[9]).toMatchObject({ name: '_helper', access: 'private' })
|
||||
expect(found[10]).not.toHaveProperty('access')
|
||||
})
|
||||
|
||||
it('字典字面量的各项:字符串键、名字键、嵌套字典连它的各项、**展开;空字典是空数组,别的值没有;类属性也有', async () => {
|
||||
const source = [
|
||||
'_KEYS = {',
|
||||
' "published": "contests:publish",',
|
||||
' key: 1,',
|
||||
' # 注释不算一项',
|
||||
' "nested": {"a": {}, "b": [1]},',
|
||||
' **other,',
|
||||
'}',
|
||||
'EMPTY = {}',
|
||||
'ITEMS = [1]',
|
||||
'class K:',
|
||||
' labels = {"x": 1}',
|
||||
].join('\n')
|
||||
const found = await facts(source)
|
||||
expect(found[1]).toMatchObject({ access: 'private', declarators: [{ name: '_KEYS', entries: [
|
||||
{ kind: 'pair', key: '"published"', value: '"contests:publish"' },
|
||||
{ kind: 'pair', key: 'key', value: '1' },
|
||||
{ kind: 'pair', key: '"nested"', value: '{"a": {}, "b": [1]}', entries: [
|
||||
{ kind: 'pair', key: '"a"', value: '{}', entries: [] },
|
||||
{ kind: 'pair', key: '"b"', value: '[1]' },
|
||||
] },
|
||||
{ kind: 'spread', value: 'other' },
|
||||
] }] })
|
||||
expect(found[8]).toEqual({ access: 'public', declarators: [{ name: 'EMPTY', value: '{}', entries: [] }] })
|
||||
expect(found[9]).toEqual({ access: 'public', declarators: [{ name: 'ITEMS', value: '[1]' }] })
|
||||
expect(found[11]).toEqual({ access: 'public', declarators: [{ name: 'labels', value: '{"x": 1}', entries: [{ kind: 'pair', key: '"x"', value: '1' }] }] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('python 类', () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Access, BlockShape, ClassFacts, CodeBlock, FunctionFacts, ImportFacts, ImportItem, LanguageAdapter, Node, ParameterFacts, TextKind, TokenRole } from '../contract'
|
||||
import type { Access, BlockShape, ClassFacts, CodeBlock, EntryFacts, FunctionFacts, ImportFacts, ImportItem, LanguageAdapter, Node, ParameterFacts, TextKind, TokenRole } from '../contract'
|
||||
import type { CommentRules } from './shared'
|
||||
import * as path from 'node:path'
|
||||
import { children, compoundShape, leafBlock, leafShape, listBlocks, named, sameNode, syntaxChildren } from './shared'
|
||||
@@ -230,16 +230,34 @@ function expressionBlock(node: Node, scope: Scope, docstring: boolean): CodeBloc
|
||||
const type = expression.childForFieldName('type')
|
||||
if (scope === 'class' && type)
|
||||
return leafBlock('field', node)
|
||||
const value = expression.childForFieldName('right')
|
||||
return {
|
||||
kind: scope === 'module' && isConstantTarget(left) ? 'const' : 'variable',
|
||||
...leafShape(node),
|
||||
facts: {
|
||||
access: scopeAccess(left, scope),
|
||||
declarators: [{ name: left, type: type ?? undefined, value: expression.childForFieldName('right') ?? undefined }],
|
||||
declarators: [{ name: left, type: type ?? undefined, value: value ?? undefined, entries: dictionaryEntries(value) }],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 字典字面量的各项:`键: 值`(值又是字典时连它的各项)、`**other`;值不是字典字面量时没有。 */
|
||||
function dictionaryEntries(value: Node | null): EntryFacts[] | undefined {
|
||||
if (value?.type !== 'dictionary')
|
||||
return undefined
|
||||
return syntaxChildren(value).flatMap((item): EntryFacts[] => {
|
||||
if (item.type === 'dictionary_splat') {
|
||||
const [spread] = syntaxChildren(item)
|
||||
return spread ? [{ kind: 'spread', value: spread }] : []
|
||||
}
|
||||
const key = item.childForFieldName('key')
|
||||
const itemValue = item.childForFieldName('value')
|
||||
if (item.type !== 'pair' || !key || !itemValue)
|
||||
return []
|
||||
return [{ kind: 'pair', key, value: itemValue, entries: dictionaryEntries(itemValue) }]
|
||||
})
|
||||
}
|
||||
|
||||
/** elif / else 展平成紧跟 if 的兄弟块。 */
|
||||
function ifBlocks(node: Node): CodeBlock[] {
|
||||
const blocks = [bodyBlock('if', node, bodyOf(node), 'other')]
|
||||
|
||||
@@ -325,7 +325,58 @@ describe('typeScript 属性表信息(facts)', () => {
|
||||
})
|
||||
expect(env[24]).toEqual({ declarators: [{ name: 'folder', value: 'workspace.workspaceFolders?.find(f => f.uri.fsPath === workspaceRoot)' }] })
|
||||
expect(env[38]).toMatchObject({ name: 'chmodAll', access: 'private', async: true })
|
||||
expect(env[40]).toEqual({ declarators: [{ name: 'result', type: 'EnvLockResult', value: '{ total: files.length, ok: [], failed: [] }' }] })
|
||||
expect(env[40]).toEqual({ declarators: [{
|
||||
name: 'result',
|
||||
type: 'EnvLockResult',
|
||||
value: '{ total: files.length, ok: [], failed: [] }',
|
||||
entries: [
|
||||
{ kind: 'pair', key: 'total', value: 'files.length' },
|
||||
{ kind: 'pair', key: 'ok', value: '[]' },
|
||||
{ kind: 'pair', key: 'failed', value: '[]' },
|
||||
],
|
||||
}] })
|
||||
})
|
||||
|
||||
it('对象字面量的各项:各种键、简写(键和值是同一个节点)、展开、方法(头部到主体之前)、嵌套对象连它的各项;空对象是空数组,别的值没有', async () => {
|
||||
const source = [
|
||||
'const o = {',
|
||||
' a: 1,',
|
||||
' \'b-c\': x,',
|
||||
' [k]: 2,',
|
||||
' s,',
|
||||
' ...rest,',
|
||||
' // 注释不算一项',
|
||||
' async load(id: string): Promise<void> {',
|
||||
' await run(id)',
|
||||
' },',
|
||||
' get size() { return 1 },',
|
||||
' n: { d: 4, e: {} },',
|
||||
'}',
|
||||
'const empty = {}',
|
||||
'const list = [1]',
|
||||
].join('\n')
|
||||
const at = (text: string): number => source.indexOf(text)
|
||||
const found = await facts(source)
|
||||
expect(found[1]).toMatchObject({ declarators: [{ entries: [
|
||||
{ kind: 'pair', key: 'a', value: '1' },
|
||||
{ kind: 'pair', key: '\'b-c\'', value: 'x' },
|
||||
{ kind: 'pair', key: '[k]', value: '2' },
|
||||
{ kind: 'pair', key: 's', value: 's' },
|
||||
{ kind: 'spread', value: 'rest' },
|
||||
{
|
||||
kind: 'method',
|
||||
name: 'load',
|
||||
node: 'async load(id: string): Promise<void> {\n await run(id)\n }',
|
||||
header: { startIndex: at('async load'), endIndex: at(' {\n await'), startRow: 7, endRow: 7 },
|
||||
},
|
||||
{ kind: 'method', name: 'size', header: { startIndex: at('get size'), endIndex: at(' { return 1'), startRow: 10, endRow: 10 } },
|
||||
{ kind: 'pair', key: 'n', value: '{ d: 4, e: {} }', entries: [
|
||||
{ kind: 'pair', key: 'd', value: '4' },
|
||||
{ kind: 'pair', key: 'e', value: '{}', entries: [] },
|
||||
] },
|
||||
] }] })
|
||||
expect(found[14]).toEqual({ access: 'private', declarators: [{ name: 'empty', value: '{}', entries: [] }] })
|
||||
expect(found[15]).toEqual({ access: 'private', declarators: [{ name: 'list', value: '[1]' }] })
|
||||
})
|
||||
|
||||
it('导入:默认导入、* as、仅类型、副作用导入、require', async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Access, BaseFacts, BlockShape, ClassFacts, CodeBlock, DeclaratorFacts, FunctionFacts, ImportFacts, ImportItem, LanguageAdapter, Node, ParameterFacts, TextKind, TokenRole } from '../contract'
|
||||
import type { Access, BaseFacts, BlockShape, ClassFacts, CodeBlock, DeclaratorFacts, EntryFacts, FunctionFacts, ImportFacts, ImportItem, LanguageAdapter, Node, ParameterFacts, TextKind, TokenRole } from '../contract'
|
||||
import type { CommentRules } from './shared'
|
||||
import * as path from 'node:path'
|
||||
import { children, compoundShape, extendHeader, leafBlock, leafShape, listBlocks, named, sameNode, syntaxChildren } from './shared'
|
||||
import { children, compoundShape, extendHeader, headerSpan, leafBlock, leafShape, listBlocks, named, nodeSpan, sameNode, syntaxChildren } from './shared'
|
||||
|
||||
const GRAMMARS: Record<string, string> = {
|
||||
typescript: 'tree-sitter-typescript.wasm',
|
||||
@@ -205,13 +205,43 @@ function parameterFacts(param: Node): ParameterFacts {
|
||||
}
|
||||
|
||||
function declaratorFacts(declarator: Node): DeclaratorFacts {
|
||||
const value = declarator.childForFieldName('value')
|
||||
return {
|
||||
name: declarator.childForFieldName('name') ?? declarator,
|
||||
type: annotatedType(declarator.childForFieldName('type')),
|
||||
value: declarator.childForFieldName('value') ?? undefined,
|
||||
value: value ?? undefined,
|
||||
entries: objectEntries(value),
|
||||
}
|
||||
}
|
||||
|
||||
/** 对象字面量的各项:`键: 值`(值又是对象时连它的各项)、简写 `{ a }`、`...other`、方法;值不是对象字面量时没有。 */
|
||||
function objectEntries(value: Node | null): EntryFacts[] | undefined {
|
||||
if (value?.type !== 'object')
|
||||
return undefined
|
||||
return syntaxChildren(value).flatMap((member): EntryFacts[] => {
|
||||
switch (member.type) {
|
||||
case 'pair': {
|
||||
const key = member.childForFieldName('key')
|
||||
const memberValue = member.childForFieldName('value')
|
||||
return key && memberValue ? [{ kind: 'pair', key, value: memberValue, entries: objectEntries(memberValue) }] : []
|
||||
}
|
||||
case 'shorthand_property_identifier':
|
||||
return [{ kind: 'pair', key: member, value: member }]
|
||||
case 'spread_element': {
|
||||
const [spread] = syntaxChildren(member)
|
||||
return spread ? [{ kind: 'spread', value: spread }] : []
|
||||
}
|
||||
case 'method_definition': {
|
||||
const name = member.childForFieldName('name')
|
||||
const body = member.childForFieldName('body')
|
||||
return name ? [{ kind: 'method', name, node: member, header: body ? headerSpan(member, body.startIndex) : nodeSpan(member) }] : []
|
||||
}
|
||||
default:
|
||||
return []
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** import 语句:默认导入、`* as x`、`{ a as b }`、`import x = require('m')`;`import type` 只导入类型。 */
|
||||
function importFacts(node: Node): ImportFacts {
|
||||
const require = named(node).find(child => child.type === 'import_require_clause')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BlockKind, CodeBlock, LanguageAdapter, PreviewText, PropertyRow, Segment } from './contract'
|
||||
import type { BlockKind, CodeBlock, LanguageAdapter, PreviewText, PropertyItem, PropertyRow, Segment } from './contract'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import * as path from 'node:path'
|
||||
import { Node } from '@vscode/tree-sitter-wasm'
|
||||
@@ -54,12 +54,13 @@ export function previewText(text: PreviewText): string {
|
||||
return 'markdown' in text ? text.markdown : segmentText(text)
|
||||
}
|
||||
|
||||
/** 属性表写成文字:每行 `名称: 值`,展开的子行缩进两格、各列用 ` | ` 隔开。 */
|
||||
/** 属性表写成文字:每行 `名称: 值`,展开的子行比上一层多缩进两格、各列用 ` | ` 隔开。 */
|
||||
export function propertyLines(rows: PropertyRow[]): string[] {
|
||||
return rows.flatMap(row => [
|
||||
`${row.label}: ${previewText(row.value)}`,
|
||||
...(row.items ?? []).map(item => ` ${item.cells.map(segmentText).join(' | ')}`),
|
||||
const itemLines = (items: PropertyItem[] | undefined, indent: string): string[] => (items ?? []).flatMap(item => [
|
||||
`${indent}${item.cells.map(segmentText).join(' | ')}`,
|
||||
...itemLines(item.items, `${indent} `),
|
||||
])
|
||||
return rows.flatMap(row => [`${row.label}: ${previewText(row.value)}`, ...itemLines(row.items, ' ')])
|
||||
}
|
||||
|
||||
/** 语法树节点换成它的源码,没填的可选字段去掉。 */
|
||||
|
||||
@@ -80,6 +80,7 @@ export const pythonZhTranslator: Translator = createZhTemplateTranslator({
|
||||
operators: { '==': '等于', '!=': '不等于' },
|
||||
operatorParents: ['comparison_operator'],
|
||||
emptyLiterals: { list: '空列表', dictionary: '空字典' },
|
||||
mapLiterals: { dictionary: '字典' },
|
||||
stringNodes: ['string'],
|
||||
commentText,
|
||||
// `a if c else b` 的三个具名子节点依次是 a、c、b,语法没给它们起字段名
|
||||
|
||||
@@ -85,7 +85,8 @@ export const typescriptZhTranslator: Translator = createZhTemplateTranslator({
|
||||
isTypePosition: leaf => leaf.parent?.type === 'predefined_type',
|
||||
operators: { '===': '全等', '!==': '不全等', '==': '等于', '!=': '不等于', '&&': '并且', '||': '或者', '!': '非' },
|
||||
operatorParents: ['binary_expression', 'unary_expression'],
|
||||
emptyLiterals: { array: '空数组' },
|
||||
emptyLiterals: { array: '空数组', object: '空对象' },
|
||||
mapLiterals: { object: '对象' },
|
||||
stringNodes: ['string', 'template_string', 'regex'],
|
||||
commentText,
|
||||
nodeTemplates: {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LanguageAdapter, PropertyRow, Segment, Translator } from '../contract'
|
||||
import type { LanguageAdapter, PropertyItem, PropertyRow, Segment, Translator } from '../contract'
|
||||
import type { ZhTable } from './zhTemplate'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createPythonAdapter } from '../languages/python'
|
||||
@@ -362,7 +362,7 @@ describe('属性表', () => {
|
||||
expect(env[15]).toEqual(['名称: ENV_PATTERN', '访问级别: 私有', '值: \'**/.env*\''])
|
||||
expect(env[27]).toEqual(['名称: include', '初始值: 新建 RelativePattern(folder, ENV_PATTERN)'])
|
||||
expect(env[28]).toEqual(['名称: uris', '初始值: 等待 workspace.findFiles(include, EXCLUDE_PATTERN)'])
|
||||
expect(env[40]).toEqual(['名称: result', '类型: EnvLockResult', '初始值: { total: files.length, ok: 空数组, failed: 空数组 }'])
|
||||
expect(env[40]).toEqual(['名称: result', '类型: EnvLockResult', '初始值: 对象 3 项', ' total | files.length', ' ok | 空数组', ' failed | 空数组'])
|
||||
expect(issue[1]).toEqual(['来源: \'../gitea/types\'', '仅类型: 是', '导入项: 1 个', ' Issue'])
|
||||
expect(issue[14]).toEqual(['名称: issue', '初始值: issues.find(i => i.number 全等 issueNumber)'])
|
||||
expect(routes[19]).toEqual([
|
||||
@@ -620,6 +620,86 @@ describe('属性表', () => {
|
||||
expect(rows[1]).toEqual(['名称: i', '访问级别: 私有', '初始值: 0', '名称: n', '访问级别: 私有', '类型: 数值', '初始值: 无'])
|
||||
expect(rows[3]).toEqual(['名称: v', '初始值: useMemo(() =>'])
|
||||
})
|
||||
|
||||
it('字典:值写「字典 N 项」,每项一个子行「键 | 值」,嵌套的字典一层层往下展开;**展开的键写「展开」,空字典照旧一行', async () => {
|
||||
const source = [
|
||||
'_CONTEST_STATUS_KEYS = {',
|
||||
' "published": "contests:publish",',
|
||||
' "ended": "contests:end",',
|
||||
' "draft": "contests:update",',
|
||||
'}',
|
||||
'CONFIG = {"db": {"host": host, "opts": {}}, **defaults, 1: await load()}',
|
||||
'EMPTY = {}',
|
||||
].join('\n')
|
||||
const rows = rowTexts(await describeAll(py, 'python', pythonZhTranslator, source))
|
||||
expect(rows[1]).toEqual([
|
||||
'名称: _CONTEST_STATUS_KEYS',
|
||||
'访问级别: 私有',
|
||||
'初始值: 字典 3 项',
|
||||
' "published" | "contests:publish"',
|
||||
' "ended" | "contests:end"',
|
||||
' "draft" | "contests:update"',
|
||||
])
|
||||
expect(rows[6]).toEqual([
|
||||
'名称: CONFIG',
|
||||
'访问级别: 公共',
|
||||
'值: 字典 3 项',
|
||||
' "db" | 字典 2 项',
|
||||
' "host" | host',
|
||||
' "opts" | 空字典',
|
||||
' 展开 | defaults',
|
||||
' 1 | 等待 load()',
|
||||
])
|
||||
expect(rows[7]).toEqual(['名称: EMPTY', '访问级别: 公共', '值: 空字典'])
|
||||
})
|
||||
|
||||
it('对象:值写「对象 N 项」,键照源码写法(计算属性名照常翻),简写的值就是它自己,方法的值是它的头部,嵌套的一层层往下展开;空对象一行「空对象」', async () => {
|
||||
const source = [
|
||||
'export const handlers = {',
|
||||
' total: files.length,',
|
||||
' \'x-y\': await load(),',
|
||||
' [key]: !ok,',
|
||||
' files,',
|
||||
' ...rest,',
|
||||
' async load(id: string): Promise<void> {',
|
||||
' await run(id)',
|
||||
' },',
|
||||
' nested: { a: [], b: { c: 1 } },',
|
||||
'}',
|
||||
'let none = {}',
|
||||
].join('\n')
|
||||
const described = await describeAll(ts, 'typescript', typescriptZhTranslator, source)
|
||||
const rows = rowTexts(described)
|
||||
expect(rows[1]).toEqual([
|
||||
'名称: handlers',
|
||||
'访问级别: 公共',
|
||||
'值: 对象 7 项',
|
||||
' total | files.length',
|
||||
' \'x-y\' | 等待 load()',
|
||||
' [key] | 非 ok',
|
||||
' files | files',
|
||||
' 展开 | rest',
|
||||
' load | 异步 load(id: 字符串): Promise<无>',
|
||||
' nested | 对象 2 项',
|
||||
' a | 空数组',
|
||||
' b | 对象 1 项',
|
||||
' c | 1',
|
||||
])
|
||||
expect(rows[12]).toEqual(['名称: none', '访问级别: 私有', '初始值: 空对象'])
|
||||
|
||||
const value = colors(described.get(1) ?? []).find(row => row.label === '值')
|
||||
expect(value?.value).toEqual([{ text: '对象 7 项', role: 'hint' }])
|
||||
expect(value?.items?.map(item => item.cells[0])).toEqual([
|
||||
[{ text: 'total', role: 'variable' }],
|
||||
[{ text: '\'x-y\'', role: 'string' }],
|
||||
[{ text: '[', role: 'plain' }, { text: 'key', role: 'variable' }, { text: ']', role: 'plain' }],
|
||||
[{ text: 'files', role: 'variable' }],
|
||||
[{ text: '展开', role: 'hint' }],
|
||||
[{ text: 'load', role: 'function' }],
|
||||
[{ text: 'nested', role: 'variable' }],
|
||||
])
|
||||
expect(value?.items?.[6].cells[1]).toEqual([{ text: '对象 2 项', role: 'hint' }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('源码下标(跳到定义用)', () => {
|
||||
@@ -633,7 +713,8 @@ describe('源码下标(跳到定义用)', () => {
|
||||
}
|
||||
|
||||
function propertySegments(rows: PropertyRow[]): Segment[] {
|
||||
return rows.flatMap(row => [...('markdown' in row.value ? [] : row.value), ...(row.items ?? []).flatMap(item => item.cells.flat())])
|
||||
const itemSegments = (items: PropertyItem[] | undefined): Segment[] => (items ?? []).flatMap(item => [...item.cells.flat(), ...itemSegments(item.items)])
|
||||
return rows.flatMap(row => [...('markdown' in row.value ? [] : row.value), ...itemSegments(row.items)])
|
||||
}
|
||||
|
||||
it('python:点分模块名每一节、导入项、别名各自带下标,点号不带;前面有中文注释也对得上', async () => {
|
||||
@@ -723,6 +804,37 @@ describe('源码下标(跳到定义用)', () => {
|
||||
expect(marked(tsSource, tsRows.get(3))).toEqual(['名称: i', '名称: j'])
|
||||
})
|
||||
|
||||
it('字典 / 对象字面量:键和值里的名字、字符串带下标,嵌套的也是;每项标出它讲的定义是键,展开没有', async () => {
|
||||
const source = [
|
||||
'const o = {',
|
||||
' total: files.length,',
|
||||
' "k": v,',
|
||||
' inner: { deep: x },',
|
||||
' ...rest,',
|
||||
' load() {},',
|
||||
'}',
|
||||
].join('\n')
|
||||
const at = (word: string): number => source.indexOf(word)
|
||||
const items = (await describeAll(ts, 'typescript', typescriptZhTranslator, source)).get(1)?.find(row => row.label === '值')?.items ?? []
|
||||
expect(items.map(item => item.cells.map(linked))).toEqual([
|
||||
[[['total', at('total')]], [['files', at('files')], ['length', at('length')]]],
|
||||
[[['"k"', at('"k"')]], [['v', at('v,')]]],
|
||||
[[['inner', at('inner')]], []],
|
||||
[[], [['rest', at('rest')]]],
|
||||
[[['load', at('load')]], [['load', at('load')]]],
|
||||
])
|
||||
expect(items[2].items?.map(item => item.cells.map(linked))).toEqual([[[['deep', at('deep')]], [['x', at('x }')]]]])
|
||||
expect(items.map(item => item.defines && source.slice(item.defines.startIndex, item.defines.endIndex))).toEqual(['total', '"k"', 'inner', undefined, 'load'])
|
||||
expect(items[2].items?.[0].defines).toEqual({ startIndex: at('deep'), endIndex: at('deep') + 'deep'.length })
|
||||
|
||||
const pySource = 'X = {"a": b, **c}'
|
||||
const pyItems = (await describeAll(py, 'python', pythonZhTranslator, pySource)).get(1)?.find(row => row.label === '值')?.items ?? []
|
||||
expect(pyItems.map(item => item.cells.map(linked))).toEqual([
|
||||
[[['"a"', pySource.indexOf('"a"')]], [['b', pySource.indexOf('b')]]],
|
||||
[[], [['c', pySource.indexOf('c')]]],
|
||||
])
|
||||
})
|
||||
|
||||
it('类:名称、类型参数、父类、实现的接口里的名字带下标;只有「类型参数」一行标出它讲的定义(这几个泛型参数),名称是块自己的名字、不标', async () => {
|
||||
const source = 'export class Repo<K, T extends Entity> extends Base<T> implements Loader<K>, Disposable {}'
|
||||
const at = (word: string): number => source.indexOf(word)
|
||||
@@ -789,6 +901,7 @@ describe('中文模板引擎', () => {
|
||||
operators: {},
|
||||
operatorParents: [],
|
||||
emptyLiterals: {},
|
||||
mapLiterals: {},
|
||||
stringNodes: [],
|
||||
commentText: node => node.text,
|
||||
nodeTemplates: {},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Access, ClassFacts, Defines, FactBlock, FunctionFacts, ImportFacts, ImportItem, Markdown, Node, PreviewText, PropertyRow, Segment, SourceSpan, TextBlock, TokenRole, Translator, VariableBlock } from '../contract'
|
||||
import type { Access, ClassFacts, Defines, EntryFacts, FactBlock, FunctionFacts, ImportFacts, ImportItem, Markdown, Node, PreviewText, PropertyItem, PropertyRow, Segment, SourceSpan, TextBlock, TokenRole, Translator, VariableBlock } from '../contract'
|
||||
import { commonIndent, splitLines } from '../editText'
|
||||
|
||||
/** 按所在语法节点区分译法的关键字,例如 Python 的 else:if 后「否则」,for / while 后「未中断时」。 */
|
||||
@@ -36,8 +36,10 @@ export interface ZhTable {
|
||||
/** 翻成文字的运算符:只认父节点在 operatorParents 里的运算符节点(TS 的非空断言 `x!` 不算)。 */
|
||||
operators: Record<string, string>
|
||||
operatorParents: string[]
|
||||
/** 空字面量(没有具名子节点)整个换成一个词:空数组 / 空列表 / 空字典。 */
|
||||
/** 空字面量(没有具名子节点)整个换成一个词:空数组 / 空列表 / 空字典 / 空对象。 */
|
||||
emptyLiterals: Record<string, string>
|
||||
/** 字典 / 对象字面量(语言插件给了 entries 的值)的叫法,按节点类型查:属性表里的值写成「字典 3 项」,各项展开成子行。 */
|
||||
mapLiterals: Record<string, string>
|
||||
/** 整段原样照抄、按字符串着色的节点。 */
|
||||
stringNodes: string[]
|
||||
/** 注释(或 docstring)节点去掉注释符号后的原文,可以多行。 */
|
||||
@@ -283,17 +285,17 @@ export function createZhTemplateTranslator(table: ZhTable): Translator {
|
||||
|
||||
function describe(block: FactBlock, source: string): PropertyRow[] {
|
||||
const { header } = block
|
||||
// 值里带语句块主体的回调(useMemo(() => { … }))只翻到主体开始之前,和块头部一致
|
||||
const within = (node: Node, part: SourceSpan): Segment[] => {
|
||||
const span = part.endIndex > header.endIndex ? { ...part, endIndex: header.endIndex, endRow: header.endRow } : part
|
||||
return joinTokens(tokensIn(node, span, source))
|
||||
}
|
||||
const phrases: Phrases = {
|
||||
// 值里带语句块主体的回调(useMemo(() => { … }))只翻到主体开始之前,和块头部一致
|
||||
translated: (node) => {
|
||||
const clipped = node.endIndex > header.endIndex
|
||||
const span = {
|
||||
startIndex: node.startIndex,
|
||||
endIndex: clipped ? header.endIndex : node.endIndex,
|
||||
startRow: node.startPosition.row,
|
||||
endRow: clipped ? header.endRow : node.endPosition.row,
|
||||
}
|
||||
return joinTokens(tokensIn(node, span, source))
|
||||
translated: node => within(node, { startIndex: node.startIndex, endIndex: node.endIndex, startRow: node.startPosition.row, endRow: node.endPosition.row }),
|
||||
within,
|
||||
entryCount: (literal, size) => {
|
||||
const name = table.mapLiterals[literal.type]
|
||||
return [hint(name ? `${name} ${size} 项` : `${size} 项`)]
|
||||
},
|
||||
verbatim: node => verbatim(node, source),
|
||||
// 点分模块名逐节照抄,每一节各自能跳到定义,和 VS Code 里一样
|
||||
@@ -355,10 +357,14 @@ function joinTokens(tokens: Token[]): Segment[] {
|
||||
|
||||
// ─── 属性表 ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/** 属性表里值的三种来源。 */
|
||||
/** 属性表里的值怎么写。 */
|
||||
interface Phrases {
|
||||
/** 按表翻译,只翻落在块头部里的那一段。 */
|
||||
translated: (node: Node) => Segment[]
|
||||
/** 同 translated,只翻 node 落在 span 里的那一段(对象字面量里方法的头部)。 */
|
||||
within: (node: Node, span: SourceSpan) => Segment[]
|
||||
/** 字典 / 对象字面量的项数:「字典 3 项」,叫法按字面量的节点类型查表。 */
|
||||
entryCount: (literal: Node, size: number) => Segment[]
|
||||
/** 源码原样照抄、按源码着色(装饰器)。 */
|
||||
verbatim: (node: Node) => Segment[]
|
||||
/** 导入来源:字符串字面量按字符串着色,模块名按类型着色。 */
|
||||
@@ -492,13 +498,40 @@ function importRows(facts: ImportFacts, say: Phrases): PropertyRow[] {
|
||||
]
|
||||
}
|
||||
|
||||
/** 常量 / 变量:每个声明的变量依次是名称 / 访问级别 / 类型(有标注才有)/ 值(变量叫初始值)。 */
|
||||
/** 常量 / 变量:每个声明的变量依次是名称 / 访问级别 / 类型(有标注才有)/ 值(变量叫初始值,字典 / 对象字面量见 literalValue)。 */
|
||||
function variableRows(block: VariableBlock, say: Phrases): PropertyRow[] {
|
||||
const valueLabel = block.kind === 'const' ? '值' : '初始值'
|
||||
return block.facts.declarators.flatMap(declarator => [
|
||||
{ label: '名称', value: say.translated(declarator.name), ...defining(declarator.name) },
|
||||
...accessRows(block.facts.access),
|
||||
...(declarator.type ? [{ label: '类型', value: say.translated(declarator.type) }] : []),
|
||||
{ label: valueLabel, value: declarator.value ? say.translated(declarator.value) : [hint('无')] },
|
||||
{ label: valueLabel, ...(declarator.value ? literalValue(declarator.value, declarator.entries, say) : { value: [hint('无')] }) },
|
||||
])
|
||||
}
|
||||
|
||||
/**
|
||||
* 值:字典 / 对象字面量(语言插件给了 entries)写项数,各项展开成下一层子行;
|
||||
* 空字面量和别的值是一行译文(空的译成「空字典」「空对象」)。
|
||||
*/
|
||||
function literalValue(value: Node, entries: EntryFacts[] | undefined, say: Phrases): { value: Segment[], items?: PropertyItem[] } {
|
||||
if (!entries?.length)
|
||||
return { value: say.translated(value) }
|
||||
return { value: say.entryCount(value, entries.length), items: entries.map(entry => entryItem(entry, say)) }
|
||||
}
|
||||
|
||||
/**
|
||||
* 字典 / 对象字面量的一项是一个子行,两列:键 | 值。键照源码写法(字符串带引号,计算属性名 `[k]` 照常翻),
|
||||
* `**x`、`...x` 的键写「展开」、值是展开的表达式,方法的值是它的头部。讲的定义是键(对象的属性名)。
|
||||
*/
|
||||
function entryItem(entry: EntryFacts, say: Phrases): PropertyItem {
|
||||
switch (entry.kind) {
|
||||
case 'pair': {
|
||||
const { value, ...nested } = literalValue(entry.value, entry.entries, say)
|
||||
return { cells: [say.translated(entry.key), value], ...nested, ...defining(entry.key) }
|
||||
}
|
||||
case 'spread':
|
||||
return { cells: [[hint('展开')], say.translated(entry.value)] }
|
||||
case 'method':
|
||||
return { cells: [say.translated(entry.name), say.within(entry.node, entry.header)], ...defining(entry.name) }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user