From 4156842d1a55b8ded0d3a80fb176df05c9d1f9ec Mon Sep 17 00:00:00 2001 From: Benoit Giannangeli Date: Wed, 20 Sep 2023 15:04:51 +0200 Subject: [PATCH] feat(object): Nullable object fields have null default value if none specified closes #175 --- src/parser.zig | 33 ++++++++++++++++++------------- tests/063-field-null-default.buzz | 14 +++++++++++++ 2 files changed, 33 insertions(+), 14 deletions(-) create mode 100644 tests/063-field-null-default.buzz diff --git a/src/parser.zig b/src/parser.zig index 7f9602a5..e8f8bbf6 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -1748,6 +1748,8 @@ pub const Parser = struct { if (!default.?.isConstant(default.?)) { self.reporter.reportErrorAt(.constant_default, default.?.location, "Default value must be constant"); } + } else if (property_type.optional) { + default = try self.nullLiteral(); } if (static) { @@ -3623,6 +3625,22 @@ pub const Parser = struct { return &node.node; } + fn nullLiteral(self: *Self) !*ParseNode { + const start_location = self.parser.previous_token.?; + var node = try self.gc.allocator.create(NullNode); + + node.* = NullNode{}; + + node.node.type_def = try self.gc.type_registry.getTypeDef(.{ + .def_type = .Void, + }); + + node.node.location = start_location; + node.node.end_location = self.parser.previous_token.?; + + return &node.node; + } + fn literal(self: *Self, _: bool) anyerror!*ParseNode { const start_location = self.parser.previous_token.?; @@ -3655,20 +3673,7 @@ pub const Parser = struct { return &node.node; }, - .Null => { - var node = try self.gc.allocator.create(NullNode); - - node.* = NullNode{}; - - node.node.type_def = try self.gc.type_registry.getTypeDef(.{ - .def_type = .Void, - }); - - node.node.location = start_location; - node.node.end_location = self.parser.previous_token.?; - - return &node.node; - }, + .Null => return self.nullLiteral(), .Void => { var node = try self.gc.allocator.create(VoidNode); diff --git a/tests/063-field-null-default.buzz b/tests/063-field-null-default.buzz new file mode 100644 index 00000000..a7919515 --- /dev/null +++ b/tests/063-field-null-default.buzz @@ -0,0 +1,14 @@ +import "std"; + +object Person { + str name, + int? age, +} + +test "Nullable object field have a default value at null" { + Person person = Person{ + name = "Joe" + }; + + assert(person.age == null, message: "Nullable object field have a default value at null"); +} \ No newline at end of file