Skip to content

Commit

Permalink
实现解析插值功能
Browse files Browse the repository at this point in the history
  • Loading branch information
jindy committed Jun 18, 2022
1 parent de2bd59 commit 6893188
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 9 deletions.
6 changes: 6 additions & 0 deletions src/compiler-core/src/ast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const enum NodeTypes {
// interpolation
INTERPOLATION,
// simple_expression
SIMPLE_EXPRESSION,
}
60 changes: 60 additions & 0 deletions src/compiler-core/src/parse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { NodeTypes } from "./ast"

export function baseParse(content: string) {
const context = createParseContext(content)
return createRoot(parseChildren(context))
}

function parseChildren(context) {
const nodes: any = []
let node
if (context.source.startsWith("{{")) {
node = parseInterpolation(context)
}
nodes.push(node)
return nodes
}

function parseInterpolation(context) {
const openDelimiter = "{{"
const closeDelimiter = "}}"

const closeIndex = context.source.indexOf(
closeDelimiter,
openDelimiter.length
)
// context.source = context.source.slice(openDelimiter.length)
advanceBy(context, openDelimiter.length)

const rawContentLength = closeIndex - openDelimiter.length
const rawContent = context.source.slice(0, rawContentLength)
const content = rawContent.trim()

// context.source = context.source.slice(
// rawContentLength + closeDelimiter.length
// )
advanceBy(context, rawContentLength + closeDelimiter.length)
return {
type: NodeTypes.INTERPOLATION,
content: {
type: NodeTypes.SIMPLE_EXPRESSION,
content: content,
},
}
}

function advanceBy(context, length) {
context.source = context.source.slice(length)
}

function createRoot(children) {
return {
children,
}
}

function createParseContext(content) {
return {
source: content,
}
}
19 changes: 19 additions & 0 deletions src/compiler-core/tests/parse.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { NodeTypes } from "../src/ast"
import { baseParse } from "../src/parse"

describe("Parse", () => {
describe("interpolation", () => {
test("simple interpolation", () => {
// root
const ast: any = baseParse("{{massage}}")

expect(ast.children[0]).toStrictEqual({
type: NodeTypes.INTERPOLATION,
content: {
type: NodeTypes.SIMPLE_EXPRESSION,
content: "massage",
},
})
})
})
})
9 changes: 0 additions & 9 deletions src/shared/test.ts

This file was deleted.

0 comments on commit 6893188

Please sign in to comment.