diff --git a/src/type.ts b/src/type.ts index 3679789..6e4e5a6 100644 --- a/src/type.ts +++ b/src/type.ts @@ -1563,7 +1563,7 @@ export class TypeResolver { } } if (!res && tsType.isUnion()) { - res = this.parseUnionType(tsType, typeNode as ts.UnionTypeNode); + res = this.parseUnionType(tsType, typeNode); } if (!res && this.isArray(tsType)) { if (!tsType.typeArguments) { @@ -1669,11 +1669,15 @@ export class TypeResolver { private parseUnionType( tsUnionType: ts.UnionType, - unionTypeNode?: ts.UnionTypeNode, + unionTypeNode?: ts.Node, ): Type { const union_type = new TSUnion(); /* 1. get type from typeNode firstly */ - if (unionTypeNode && unionTypeNode.types) { + if ( + unionTypeNode && + ts.isUnionTypeNode(unionTypeNode) && + unionTypeNode.types + ) { for (const typeNode of unionTypeNode.types) { const type = this.generateNodeType(typeNode); union_type.addType(type); @@ -1683,6 +1687,17 @@ export class TypeResolver { if (!tsUnionType.types) { return builtinTypes.get('any')!; } + if ( + unionTypeNode && + unionTypeNode.kind === ts.SyntaxKind.TypeReference + ) { + const tsTypeRawName = this.getTsTypeRawName(unionTypeNode)!; + if (builtinWasmTypes.has(tsTypeRawName)) { + union_type.addType(builtinWasmTypes.get(tsTypeRawName)!); + union_type.addType(builtinTypes.get('undefined')!); + return union_type; + } + } for (const tsType of tsUnionType.types) { union_type.addType(this.tsTypeToType(tsType)); } @@ -2912,15 +2927,6 @@ export class TypeResolver { } } - public static maybeBuiltinWasmType(node: ts.Node) { - const definedTypeName = (node as any).type?.typeName?.escapedText; - if (definedTypeName) { - if (builtinWasmTypes.has(definedTypeName)) { - return builtinWasmTypes.get(definedTypeName)!; - } - } - } - public arrayTypeCheck(node: ts.Node): boolean { const parentNode = node.parent; if ( diff --git a/tests/samples/wasmType_in_otherType.ts b/tests/samples/wasmType_in_otherType.ts index 628dc44..63bc99f 100644 --- a/tests/samples/wasmType_in_otherType.ts +++ b/tests/samples/wasmType_in_otherType.ts @@ -155,4 +155,19 @@ export function wasmTypeF32AsReturnType(): f32 { export function wasmTypeF64AsReturnType(): f64 { return 100.25; -} \ No newline at end of file +} + +function wasmTypeInOptionalUnionType_inner(a_param?: i32) { + if (a_param) { + console.log(a_param); + } else { + console.log('undefined'); + } +} + +export function wasmTypeInOptionalUnionType() { + const a: i32 = 100; + wasmTypeInOptionalUnionType_inner(a); + const b = undefined; + wasmTypeInOptionalUnionType_inner(b); +} diff --git a/tools/validate/wamr/validation.json b/tools/validate/wamr/validation.json index 5cb1cf7..a2325e9 100644 --- a/tools/validate/wamr/validation.json +++ b/tools/validate/wamr/validation.json @@ -4825,6 +4825,11 @@ "name": "wasmTypeF64AsReturnType", "args": [], "result": "100.25:f64" + }, + { + "name": "wasmTypeInOptionalUnionType", + "args": [], + "result": "100\nundefined" } ] }