Skip to content

Commit

Permalink
feat(object): Nullable object fields have null default value if none …
Browse files Browse the repository at this point in the history
…specified

closes #175
  • Loading branch information
giann committed Sep 20, 2023
1 parent 2382089 commit 4156842
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 14 deletions.
33 changes: 19 additions & 14 deletions src/parser.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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.?;

Expand Down Expand Up @@ -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);

Expand Down
14 changes: 14 additions & 0 deletions tests/063-field-null-default.buzz
Original file line number Diff line number Diff line change
@@ -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");
}

0 comments on commit 4156842

Please sign in to comment.