Skip to content

Commit

Permalink
实现代码生成 string 类型
Browse files Browse the repository at this point in the history
  • Loading branch information
jindy committed Jun 21, 2022
1 parent 750af23 commit f6caae3
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/compiler-core/src/codegen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export function generate(ast) {
// let code = ""
// code += "return "
const context = createCodegenContext()
const { push } = context
push("return ")
const functionName = "render"
const args = ["_ctx", "_cache"]
const signature = args.join(",")
// code += `function ${functionName}(${signature}){`
push(`function ${functionName}(${signature}){`)

// const node = ast.codegenNode
// code += `return '${node.content}'`
// code += `return`
push(`return`)
genNode(ast.codegenNode, context)
// code += `}`
push(`}`)
return {
code: context.code,
}
}

function createCodegenContext(): any {
const context = {
code: "",
push(source) {
context.code += source
},
}
return context
}

function genNode(node, context) {
const { push } = context
// const node = ast.codegenNode
push(` '${node.content}'`)
// code += `return '${node.content}'`
// return code
}
8 changes: 7 additions & 1 deletion src/compiler-core/src/transform.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { NodeTypes } from "./ast"

export function transform(root, options) {
export function transform(root, options = {}) {
const context = createTransformContext(root, options)
// 1.遍历,深度优先搜索 ----》递归
traverseNode(root, context)
// 2.修改 text content

createCodegen(root)
}

function createCodegen(root) {
root.codegenNode = root.children[0]
}

function createTransformContext(root, options) {
Expand Down
3 changes: 3 additions & 0 deletions src/compiler-core/tests/__snapshots__/codegen.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`codegen string 1`] = `"return function render(_ctx,_cache){return 'hi'}"`;
13 changes: 13 additions & 0 deletions src/compiler-core/tests/codegen.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { generate } from "../src/codegen"
import { baseParse } from "../src/parse"
import { transform } from "../src/transform"

describe("codegen", () => {
it("string", () => {
const ast = baseParse("hi")
transform(ast)
const { code } = generate(ast)
// 快照测试
expect(code).toMatchSnapshot()
})
})

0 comments on commit f6caae3

Please sign in to comment.