-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
Copy pathif.ts
49 lines (42 loc) · 1.28 KB
/
if.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import type { CodegenContext } from '../generate'
import { IRNodeTypes, type IfIRNode } from '../ir'
import { genBlock } from './block'
import { genExpression } from './expression'
import { type CodeFragment, NEWLINE, buildCodeFragment, genCall } from './utils'
export function genIf(
oper: IfIRNode,
context: CodegenContext,
isNested = false,
): CodeFragment[] {
const { helper } = context
const { condition, positive, negative, once } = oper
const [frag, push] = buildCodeFragment()
const codes: CodeFragment[] = [
isNested ? '(' : '() => (',
...genExpression(condition, context),
')',
]
let positiveArg = genBlock(positive, context)
let negativeArg: false | CodeFragment[] = false
if (negative) {
positiveArg.unshift(' ? ')
negativeArg = [' : ']
if (negative.type === IRNodeTypes.BLOCK) {
negativeArg.push(...genBlock(negative, context))
} else {
negativeArg.push(...genIf(negative!, context, true))
}
} else {
positiveArg.unshift(' ? ')
positiveArg.push(' : undefined')
}
codes.push(...positiveArg)
if (negativeArg) codes.push(...negativeArg)
if (isNested) {
push(...codes)
} else {
push(NEWLINE, `const n${oper.id} = `)
push(...genCall(helper('createIf'), codes, once && 'true'))
}
return frag
}