Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions template-engines/pug/parser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const tuples = [
[/^(\w+)/, 'tag'],
[/^\n( *)/, 'indent'],
[/\s?([^\n]+)/, 'text'],
]

module.exports = class Parser {
constructor(str) {
this.source = str
this.capture = []
this.ast = []
this.currentLine = 0
while (this.nextToken) {
if (!this.source.length) break
}
}

/* eslint no-cond-assign: 0 */
get nextToken() {
return tuples.some(([reg, type]) => {
if (this.capture = reg.exec(this.source)) {
if (type === 'indent') {
this.currentLine += 1
}
const token = this.generateToken(type)
return this.ast.push(token)
}
return false
})
}

generateToken(type) {
this.source = this.source.substr(this.capture[0].length)
return {
type,
val: this.capture[1],
line: this.currentLine,
}
}
}
30 changes: 30 additions & 0 deletions template-engines/pug/test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const { readFileSync } = require('fs')
const { resolve } = require('path')
const Parser = require('../parser')

test('parser template into AST', () => {
const template = readFileSync(resolve(__dirname, 'index.tpug'), 'utf-8')
const { ast } = new Parser(template)
const expectedAst = [
{ type: 'tag', line: 0, val: 'html' },
{ type: 'indent', line: 1, val: ' ' },
{ type: 'tag', line: 1, val: 'head' },
{ type: 'indent', line: 2, val: ' ' },
{ type: 'tag', line: 2, val: 'title' },
{ type: 'text', line: 2, val: 'tPug' },
{ type: 'indent', line: 3, val: ' ' },
{ type: 'tag', line: 3, val: 'body' },
{ type: 'indent', line: 4, val: ' ' },
{ type: 'tag', line: 4, val: 'h1' },
{ type: 'text', line: 4, val: 'Hello World!' },
{ type: 'indent', line: 5, val: ' ' },
{ type: 'tag', line: 5, val: 'ul' },
{ type: 'indent', line: 6, val: ' ' },
{ type: 'tag', line: 6, val: 'li' },
{ type: 'text', line: 6, val: 'zhang.zhao' },
{ type: 'indent', line: 7, val: ' ' },
{ type: 'tag', line: 7, val: 'li' },
{ type: 'text', line: 7, val: 'lingli.chen' },
]
expect(ast).toEqual(expectedAst)
})
8 changes: 8 additions & 0 deletions template-engines/pug/test/index.tpug
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
html
head
title tPug
body
h1 Hello World!
ul
li zhang.zhao
li lingli.chen