Skip to content

Commit eb5dbf9

Browse files
committed
draft
1 parent 94890fc commit eb5dbf9

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

slides.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1697,6 +1697,54 @@ function processExpression(node) {
16971697

16981698
## codegen 代码生成
16991699

1700+
`codegen` 主入口函数:
1701+
1702+
```js
1703+
// 代码生成
1704+
function generate(ast) {
1705+
// 创建上下文
1706+
const context = createCodegenContext()
1707+
// 生成代码
1708+
genCode(ast.codegenNode, context)
1709+
1710+
return {
1711+
code: context.code // 渲染函数代码字符串
1712+
}
1713+
}
1714+
```
1715+
1716+
---
1717+
1718+
```js
1719+
// 创建上下文,格式化代码字符串
1720+
function createCodegenContext() {
1721+
const context = {
1722+
code: '',
1723+
helper(key) {
1724+
return `_${helperNameMap[key]}`
1725+
},
1726+
push(code) {
1727+
context.code += code
1728+
},
1729+
// 当前缩进级别,初始值为0,即没有缩进
1730+
currentIndent: 0,
1731+
// 换行
1732+
newLine() {
1733+
context.code += '\n' + ' '.repeat(context.currentIndent * 2)
1734+
},
1735+
indent() { // 缩进
1736+
context.currentIndent++
1737+
context.newLine()
1738+
},
1739+
deIndent() { // 取消缩进
1740+
context.currentIndent--
1741+
context.newLine()
1742+
}
1743+
}
1744+
return context
1745+
}
1746+
```
1747+
17001748
---
17011749

17021750
## compile 实现

0 commit comments

Comments
 (0)