Files
superwork/vscode/src/codeReader/translators/pythonZh.ts
T

100 lines
3.1 KiB
TypeScript

import type { Node, Translator } from '../contract'
import { createZhTemplateTranslator } from './zhTemplate'
/** 写在类型注解里(参数、返回值、带注解赋值的 type 节点之内):内置类型名只在这里翻成中文。 */
function insideAnnotation(leaf: Node): boolean {
for (let node = leaf.parent; node; node = node.parent) {
if (node.type === 'type')
return true
if (node.type === 'block' || node.type === 'module')
return false
}
return false
}
function stringContent(node: Node): string {
if (node.type === 'string_content')
return node.text
return node.children.map(child => child ? stringContent(child) : '').join('')
}
/** `#` 注释去掉井号;docstring 只取引号里的内容。 */
function commentText(node: Node, text: string): string {
return node.type === 'comment' ? text.replace(/^#+\s?/, '') : stringContent(node)
}
export const pythonZhTranslator: Translator = createZhTemplateTranslator({
id: 'python.zh-template',
label: '中文直译',
languageIds: ['python'],
keywords: {
'import': '导入',
'from': { zh: '从', byContext: { raise_statement: '源自', yield: '自' } },
'as': '作为',
'def': '函数',
'async': '异步',
'await': '等待',
'class': '类',
'return': '返回',
'if': '如果',
'elif': '否则如果',
// 循环的 else 只在没被 break 打断时执行,try 的 else 只在没抛异常时执行
'else': {
zh: '否则',
byContext: {
'for_statement > else_clause': '未中断时',
'while_statement > else_clause': '未中断时',
'try_statement > else_clause': '未出错时',
},
},
'for': '遍历',
'in': { zh: '在', byContext: { for_statement: '取自' } },
'while': '当',
'try': '尝试',
'except': '捕获',
'finally': '最终',
'raise': '抛出',
'with': '使用',
'yield': '产出',
'lambda': '匿名函数',
'pass': '跳过',
'break': '跳出',
'continue': '继续',
'global': '全局',
'nonlocal': '非局部',
'del': '删除',
'assert': '断言',
'not': '非',
'and': '并且',
'or': '或者',
'is': '是',
'not in': '不在',
'is not': '不是',
'match': '匹配',
'case': '情况',
},
literals: { none: '空', true: '真', false: '假' },
builtinTypes: {
str: '字符串',
int: '整数',
float: '浮点数',
bool: '布尔',
list: '列表',
dict: '字典',
set: '集合',
tuple: '元组',
bytes: '字节串',
},
isTypePosition: leaf => leaf.type === 'identifier' && leaf.parent?.type !== 'attribute' && insideAnnotation(leaf),
operators: { '==': '等于', '!=': '不等于' },
operatorParents: ['comparison_operator'],
emptyLiterals: { list: '空列表', dictionary: '空字典' },
mapLiterals: { dictionary: '字典' },
stringNodes: ['string'],
commentText,
// `a if c else b` 的三个具名子节点依次是 a、c、b,语法没给它们起字段名
nodeTemplates: {
conditional_expression: ['如果', { namedChild: 1 }, '则', { namedChild: 0 }, '否则', { namedChild: 2 }],
},
})