Fix Bug In Struct Field Initialization

Fields were not given default values when a struct was declared
without initializers.

Also, cleanup code in the helper function for binary operations
on struct instances.

Signed-off-by: Will Hawkins <hawkinsw@obs.cr>
This commit is contained in:
Will Hawkins
2026-03-27 03:50:54 -04:00
parent cd26d1d22c
commit 4d787394cd
7 changed files with 133 additions and 35 deletions
+20 -14
View File
@@ -186,23 +186,25 @@ public class P4StructValue: P4Value {
// Note: Because the number of values _always_ matches the number of fields, there
// is no need to check there!
for xx in zip(zip(lhs.stype.fields, lhs.values), zip(rhs.stype.fields, rhs.values)) {
let left = xx.0
let right = xx.1
for fields_to_compare in zip(
zip(lhs.stype.fields, lhs.values), zip(rhs.stype.fields, rhs.values))
{
let left_field_and_value = fields_to_compare.0
let right_field_and_value = fields_to_compare.1
let left_field = left.0
let left_value = left.1
let left_field_name = left_field_and_value.0
let left_field_value = left_field_and_value.1
let right_field = right.0
let right_value = right.1
let right_field_name = right_field_and_value.0
let right_field_value = right_field_and_value.1
// If the field names do not match, then there is a problem.
if left_field != right_field {
if left_field_name != right_field_name {
return false
}
// Now that we know that the field names match, do the values match?
if !op(left_value, right_value) {
if !op(left_field_value, right_field_value) {
return false
}
}
@@ -296,17 +298,21 @@ public class P4StructValue: P4Value {
}
public let stype: P4Struct
public let values: [P4Value?]
public let values: [P4Value]
public convenience init(withType type: P4Struct) {
self.init(withType: type, andInitializers: [])
}
public init(withType type: P4Struct, andInitializers initializers: [P4Value?]) {
var values: [P4Value?] = Array(repeating: .none, count: type.fields.count())
for i in 0..<initializers.count {
values[i] = initializers[i]
let values = zip(0..<type.fields.count(), type.fields.fields).map { (index, field) in
// If there is an initializer for the field, then use it.
if index < initializers.count, let initializer = initializers[index] {
initializer
} else {
// Otherwise, set a default!
field.type.def()
}
}
self.values = values
-1
View File
@@ -106,7 +106,6 @@ struct StructDeclaration {
if currentChild!.nodeType == "struct_declaration_fields" {
currentChild!.enumerateNamedChildren { declaration_field in
print("declaration field: \(declaration_field)")
switch VariableDeclarationStatement.Compile(
node: declaration_field, withContext: current_context)
{
+11 -11
View File
@@ -255,33 +255,33 @@ extension SelectExpression: CompilableExpression {
))
}
var kses: [SelectCaseExpression] = Array()
var kses_errors: [Error] = Array()
var sces: [SelectCaseExpression] = Array()
var sces_errors: [Error] = Array()
select_body_node.enumerateNamedChildren { current_node in
let maybe_parsed_kse = SelectCaseExpression.compile(
let maybe_parsed_cse = SelectCaseExpression.compile(
node: current_node, withContext: context)
if case .Ok(let parsed_kse) = maybe_parsed_kse {
let parsed_cse = parsed_kse as! SelectCaseExpression
if case .Ok(let parsed_cse) = maybe_parsed_cse {
let parsed_cse = parsed_cse as! SelectCaseExpression
switch parsed_cse.update_type(to: selector.type()) {
case .Ok(let updated_cse): kses.append(updated_cse)
case .Error(let e): kses_errors.append(ErrorOnNode(node: current_node, withError: e.msg))
case .Ok(let updated_cse): sces.append(updated_cse)
case .Error(let e): sces_errors.append(ErrorOnNode(node: current_node, withError: e.msg))
}
} else {
kses_errors.append(Error(withMessage: "\(maybe_parsed_kse.error()!)"))
sces_errors.append(Error(withMessage: "\(maybe_parsed_cse.error()!)"))
}
}
if !kses_errors.isEmpty {
if !sces_errors.isEmpty {
return .Error(
Error(
withMessage: "Error(s) parsing select cases: "
+ (kses_errors.map { error in
+ (sces_errors.map { error in
return "\(error.msg)"
}.joined(separator: ";"))))
}
return .Ok(
SelectExpression(withSelector: selector, withSelectCaseExpressions: kses),
SelectExpression(withSelector: selector, withSelectCaseExpressions: sces),
)
}
}
-2
View File
@@ -56,8 +56,6 @@ extension P4Struct: CompilableType {
return .Error(maybe_parsed_type_id.error()!)
}
print("Looking up \(parsed_type_id) in \(context.types)")
if case .Ok(let found_type) = context.types.lookup(identifier: parsed_type_id),
let found_struct_type = found_type as? P4Struct
{
+2 -2
View File
@@ -145,10 +145,10 @@ public struct SelectExpression {
public init(
withSelector selector: EvaluatableExpression,
withSelectCaseExpressions kses: [SelectCaseExpression]
withSelectCaseExpressions sces: [SelectCaseExpression]
) {
self.selector = selector
self.select_expressions = kses
self.select_expressions = sces
}
public func append_checked_sce(sce: SelectCaseExpression) -> SelectExpression {
+4 -4
View File
@@ -33,11 +33,11 @@ extension SelectExpression: EvaluatableExpression {
public func evaluate(execution: Common.ProgramExecution) -> Common.Result<any Common.P4Value> {
switch self.selector.evaluate(execution: execution) {
case .Ok(let selector_value):
for kse in self.select_expressions {
if case .Ok(let kse_key) = kse.key.evaluate(execution: execution),
kse_key.eq(rhs: selector_value)
for sce in self.select_expressions {
if case .Ok(let kse) = sce.key.evaluate(execution: execution),
kse.eq(rhs: selector_value)
{
let result = kse.evaluate(execution: execution)
let result = sce.evaluate(execution: execution)
return result
}
}
+95
View File
@@ -51,3 +51,98 @@ import TreeSitterP4
let (state_result, _) = try! #UseOkResult(runtime.run())
#expect(state_result == P4Lang.accept)
}
@Test func test_struct_declaration_and_field_write_field_read() async throws {
let simple_parser_declaration = """
struct Testing {
bool yesno;
int count;
};
parser main_parser() {
state start {
Testing ts;
ts.yesno = true;
ts.count = 5;
transition select (ts.count == 5) {
true: accept;
false: reject;
};
}
};
"""
let program = try #UseOkResult(
Program.Compile(simple_parser_declaration))
let runtime = try #UseOkResult(P4Runtime.ParserRuntime.create(program: program))
let (state_result, _) = try! #UseOkResult(runtime.run())
#expect(state_result == P4Lang.accept)
}
@Test func test_struct_declaration_and_field_read_defaults() async throws {
let simple_parser_declaration = """
struct Testing {
bool yesno;
int count;
};
parser main_parser() {
state start {
Testing ts;
transition select (ts.count == 0) {
true: accept;
false: reject;
};
}
};
"""
let program = try #UseOkResult(
Program.Compile(simple_parser_declaration))
let runtime = try #UseOkResult(P4Runtime.ParserRuntime.create(program: program))
let (state_result, _) = try! #UseOkResult(runtime.run())
#expect(state_result == P4Lang.accept)
}
@Test func test_struct_declaration_and_field_read_defaults_sc() async throws {
let simple_parser_declaration = """
struct Testing {
bool yesno;
int count;
};
parser main_parser() {
state start {
Testing ts;
transition select (ts.count) {
0: accept;
_: reject;
};
}
};
"""
let program = try #UseOkResult(
Program.Compile(simple_parser_declaration))
let runtime = try #UseOkResult(P4Runtime.ParserRuntime.create(program: program))
let (state_result, _) = try! #UseOkResult(runtime.run())
#expect(state_result == P4Lang.accept)
}
@Test func test_struct_declaration_and_field_read_defaults_sc2() async throws {
let simple_parser_declaration = """
struct Testing {
bool yesno;
int count;
};
parser main_parser() {
state start {
Testing ts;
ts.count = 1;
transition select (ts.count) {
0: accept;
_: reject;
};
}
};
"""
let program = try #UseOkResult(
Program.Compile(simple_parser_declaration))
let runtime = try #UseOkResult(P4Runtime.ParserRuntime.create(program: program))
let (state_result, _) = try! #UseOkResult(runtime.run())
#expect(state_result == P4Lang.reject)
}