File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -1697,6 +1697,54 @@ function processExpression(node) {
1697
1697
1698
1698
## codegen 代码生成
1699
1699
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
+
1700
1748
---
1701
1749
1702
1750
## compile 实现
You can’t perform that action at this time.
0 commit comments