test(compiler-core): test TempalteLiteral and IfStatement codegen

This commit is contained in:
Evan You
2020-02-02 21:35:28 -05:00
parent 5dc374a861
commit 8fd9e9ba97
3 changed files with 185 additions and 4 deletions

View File

@@ -329,7 +329,7 @@ export interface IfStatement extends Node {
type: NodeTypes.JS_IF_STATEMENT
test: ExpressionNode
consequent: BlockStatement
alternate: IfStatement | BlockStatement
alternate: IfStatement | BlockStatement | undefined
}
// Codegen Node Types ----------------------------------------------------------
@@ -671,6 +671,16 @@ export function createCacheExpression(
}
}
export function createBlockStatement(
body: BlockStatement['body']
): BlockStatement {
return {
type: NodeTypes.JS_BLOCK_STATEMENT,
body,
loc: locStub
}
}
export function createTemplateLiteral(
elements: TemplateLiteral['elements']
): TemplateLiteral {
@@ -680,3 +690,17 @@ export function createTemplateLiteral(
loc: locStub
}
}
export function createIfStatement(
test: IfStatement['test'],
consequent: IfStatement['consequent'],
alternate?: IfStatement['alternate']
): IfStatement {
return {
type: NodeTypes.JS_IF_STATEMENT,
test,
consequent,
alternate,
loc: locStub
}
}

View File

@@ -20,7 +20,8 @@ import {
CacheExpression,
locStub,
SSRCodegenNode,
TemplateLiteral
TemplateLiteral,
IfStatement
} from './ast'
import { SourceMapGenerator, RawSourceMap } from 'source-map'
import {
@@ -489,7 +490,7 @@ function genNode(node: CodegenNode | symbol | string, context: CodegenContext) {
!__BROWSER__ && genTemplateLiteral(node, context)
break
case NodeTypes.JS_IF_STATEMENT:
// TODO
!__BROWSER__ && genIfStatement(node, context)
break
/* istanbul ignore next */
@@ -731,3 +732,27 @@ function genTemplateLiteral(node: TemplateLiteral, context: CodegenContext) {
}
push('`')
}
function genIfStatement(node: IfStatement, context: CodegenContext) {
const { push, indent, deindent } = context
const { test, consequent, alternate } = node
push(`if (`)
genNode(test, context)
push(`) {`)
indent()
genNode(consequent, context)
deindent()
push(`}`)
if (alternate) {
push(` else `)
if (alternate.type === NodeTypes.JS_IF_STATEMENT) {
genIfStatement(alternate, context)
} else {
push(`{`)
indent()
genNode(alternate, context)
deindent()
push(`}`)
}
}
}