Skip to content

Commit

Permalink
parseText
Browse files Browse the repository at this point in the history
  • Loading branch information
cuixiaorui committed Sep 8, 2021
1 parent 4743310 commit baaba51
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/compiler-core/__tests__/parser.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NodeTypes } from "../src/ast";
import { baseParse } from "../src/parser";

describe("parser", () => {
test("simple text", () => {
const ast = baseParse("some text");
const text = ast.children[0];

expect(text).toStrictEqual({
type: NodeTypes.TEXT,
content: "some text",
});
});
});
4 changes: 4 additions & 0 deletions src/compiler-core/src/ast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const enum NodeTypes {
TEXT,
ROOT
}
57 changes: 57 additions & 0 deletions src/compiler-core/src/parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { NodeTypes } from "./ast";

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

function createParserContext(content) {
console.log("创建 paserContext");
return {
source: content,
};
}

function parseChildren(context) {
console.log("开始解析 children");
const nodes = [];
const node = parseText(context);

nodes.push(node);

return nodes;
}

function parseText(context): any {
console.log("解析 text", context);
const endIndex = context.source.length;
const content = parseTextData(context, endIndex);

return {
type: NodeTypes.TEXT,
content,
};
}

function parseTextData(context: any, length: number): any {
console.log("解析 textData");
// 1. 直接返回 context.source
// 从 length 切的话,是为了可以获取到 text 的值(需要用一个范围来确定)
const rawText = context.source.slice(0, length);
// 2. 移动光标
advanceBy(context, length);

return rawText;
}

function advanceBy(context, numberOfCharacters) {
console.log("推进代码", context, numberOfCharacters);
context.source = context.source.slice(numberOfCharacters);
}

function createRoot(children) {
return {
type: NodeTypes.ROOT,
children,
};
}

0 comments on commit baaba51

Please sign in to comment.