Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(object): Nullable object fields have null default value if none specified #180

Merged
merged 1 commit into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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");
}