Skip to content

Commit bf67e09

Browse files
committed
feat(typecheck): enhance instanceof type checking with support for primitive types and enums
1 parent 80f20ae commit bf67e09

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

engine/baml-compiler/src/thir/typecheck.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,13 @@
1717
///
1818
/// However, the current implementation is simple and ad-hoc, likely wrong
1919
/// in several places. Bidirectional typing is the target.
20-
use std::{borrow::Cow, sync::Arc};
20+
use std::{borrow::Cow, str::FromStr, sync::Arc};
2121

2222
use baml_types::{
2323
ir_type::{ArrowGeneric, TypeIR},
2424
BamlMap, BamlMediaType, BamlValueWithMeta, TypeValue,
2525
};
26+
use baml_vm::types::Type;
2627
use internal_baml_ast::ast::WithSpan;
2728
use internal_baml_diagnostics::{DatamodelError, Diagnostics, Span};
2829

@@ -1356,6 +1357,7 @@ pub fn typecheck_expression(
13561357
"image" | "audio" | "video" | "pdf" | "baml" => {}
13571358

13581359
cls if context.classes.contains_key(cls) => {}
1360+
p if TypeValue::from_str(p).is_ok() => {}
13591361

13601362
_ => {
13611363
diagnostics.push_error(DatamodelError::new_validation_error(
@@ -2344,17 +2346,22 @@ pub fn typecheck_expression(
23442346
thir::Expr::Var(name, _) => {
23452347
if context.classes.get(name).is_some() {
23462348
Some(TypeIR::bool())
2349+
} else if context.enums.get(name).is_some() {
2350+
Some(TypeIR::bool())
2351+
} else if TypeValue::from_str(name).is_ok() {
2352+
Some(TypeIR::bool())
23472353
} else {
2354+
// TODO: Check type aliases (may be recursive)
23482355
diagnostics.push_error(DatamodelError::new_validation_error(
2349-
&format!("Class {name} not found"),
2356+
&format!("Type {name} not found"),
23502357
span.clone(),
23512358
));
23522359
None
23532360
}
23542361
}
23552362
_ => {
23562363
diagnostics.push_error(DatamodelError::new_validation_error(
2357-
"Invalid binary operation (instanceof): right operand must be a class",
2364+
"Invalid binary operation (instanceof): right operand must be a type",
23582365
span.clone(),
23592366
));
23602367
None

integ-tests/baml_src/test-files/vm/expr_funcs.baml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,26 @@ class DummyJsonTodo {
154154
userId int
155155
}
156156

157+
enum DummyEnum {
158+
POSITIVE
159+
NEGATIVE
160+
NEUTRAL
161+
}
162+
157163
function ExecFetchAs(url: string) -> DummyJsonTodo {
158164
let todo = baml.fetch_as<DummyJsonTodo>(url);
159165

160166
todo
161167
}
168+
169+
function InstanceofWithPrimitives(n: int) -> bool {
170+
n instanceof int
171+
}
172+
173+
function InstanceofWithClasses(dummy: DummyJsonTodo) -> bool {
174+
dummy instanceof DummyJsonTodo
175+
}
176+
177+
function InstanceofWithEnums(e: DummyEnum) -> bool {
178+
e instanceof DummyEnum
179+
}

0 commit comments

Comments
 (0)