Refactor Expected Types During Compilation

By adding an expected type to the compilation context, it is
now possible for type checking to occur on keyset expressions
and return statements at the moment that they are being compiled.

Previously, it was necessary to tentatively compile them and then
typecheck afterward.

Signed-off-by: Will Hawkins <hawkinsw@obs.cr>
This commit is contained in:
Will Hawkins
2026-04-10 00:59:11 -04:00
parent ad7e5a6f6d
commit b687454389
8 changed files with 112 additions and 115 deletions
@@ -134,3 +134,24 @@ import TreeSitterP4
#expect(AsInstantiatedParserState(state_result) == P4Lang.reject)
}
@Test func test_function_call_invalid_return_type() async throws {
let simple_parser_declaration = """
int functionb(int c) {
return true;
};
parser main_parser() {
state start {
int c = 5;
transition select (4 == functionb(c)) {
false: reject;
true: accept;
};
}
};
"""
let error = try #UseErrorResult(Program.Compile(simple_parser_declaration))
#expect(error.msg.contains("{29, 12}: Type of expression in return statement (Boolean) is not compatible with function return type (Int)"))
}
@@ -105,7 +105,6 @@ import TreeSitterP4
}
};
"""
let program = try #UseOkResult(Program.Compile(simple_parser_declaration))
let parser = try #UseOkResult(program.find_parser(withName: Identifier(name: "main_parser")))
let runtime = try #UseOkResult(P4Runtime.ParserRuntime.create(program: program))
@@ -133,7 +132,7 @@ import TreeSitterP4
#RequireErrorResult(
Error(
withMessage:
"Error(s) parsing select cases: {81, 12}: Keyset expression type does not match selector expression type"
"Error(s) parsing select cases: {81, 4}: Key expression of type Boolean is not compatible with selector type Int"
),
Program.Compile(simple_parser_declaration)))
}