Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix(type-inference): for ternary expression with null branch #141

Merged
merged 1 commit into from
Feb 8, 2025
Merged
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
15 changes: 14 additions & 1 deletion server/src/TypeInferer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,20 @@ export class TypeInferer {
const alternate = node.node.childForFieldName("alternative")
if (!consequent || !alternate) return null

return this.inferType(new Expression(consequent, node.file))
const trueType = this.inferType(new Expression(consequent, node.file))
const falseType = this.inferType(new Expression(alternate, node.file))
if (!falseType) return trueType
if (!trueType) return falseType

if (trueType instanceof NullTy) {
return new OptionTy(falseType)
}

if (falseType instanceof NullTy) {
return new OptionTy(trueType)
}

return trueType
}

if (node instanceof NamedNode) {
Expand Down
45 changes: 45 additions & 0 deletions server/src/e2e/suite/testcases/types/basic.test
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,48 @@ fun foo() {
}
------------------------------------------------------------------------
ok

========================================================================
ternary expression
========================================================================
primitive Int;
primitive String;

contract Contract {}

fun foo() {
let a = true ? 10 : 20;
//! ^ Int
}
------------------------------------------------------------------------
ok

========================================================================
ternary expression with false null
========================================================================
primitive Int;
primitive String;

contract Contract {}

fun foo() {
let a = true ? 10 : null;
//! ^ Int?
}
------------------------------------------------------------------------
ok

========================================================================
ternary expression with true null
========================================================================
primitive Int;
primitive String;

contract Contract {}

fun foo() {
let a = true ? null : 10;
//! ^ Int?
}
------------------------------------------------------------------------
ok