diff --git a/CHANGELOG.md b/CHANGELOG.md index 15fd7b53..32d5d00a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ - Changed pattern delimiters (https://github.com/buzz-language/buzz/issues/165) - `list.append` does not return the appended value anymore - Generic types syntax changed from `myFunction(, ...)` to `myFunction::(...)` +- Nullable object fields and nullable variables have a `null` initial value if none is provided ## Fixed diff --git a/src/parser.zig b/src/parser.zig index 08096084..d95a75b5 100644 --- a/src/parser.zig +++ b/src/parser.zig @@ -2579,8 +2579,15 @@ pub const Parser = struct { var value: ?*ParseNode = null; if (should_assign) { - try self.consume(.Equal, "Expected variable initial value"); - value = try self.expression(false); + if (try self.match(.Equal)) { + value = try self.expression(false); + } else if (parsed_type == null or !parsed_type.?.optional) { + self.reporter.reportErrorAt( + .syntax, + self.parser.previous_token.?, + "Expected variable initial value", + ); + } } if (var_type.def_type == .Placeholder and value != null and value.?.type_def != null and value.?.type_def.?.def_type == .Placeholder) { diff --git a/tests/063-field-null-default.buzz b/tests/063-field-null-default.buzz deleted file mode 100644 index a7919515..00000000 --- a/tests/063-field-null-default.buzz +++ /dev/null @@ -1,14 +0,0 @@ -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 diff --git a/tests/063-nullable-default.buzz b/tests/063-nullable-default.buzz new file mode 100644 index 00000000..939ea70e --- /dev/null +++ b/tests/063-nullable-default.buzz @@ -0,0 +1,20 @@ +import "std"; + +object Person { + str name, + int? age, +} + +test "Nullable object field has a default value at null" { + Person person = Person{ + name = "Joe" + }; + + assert(person.age == null, message: "Nullable object field has a default value at null"); +} + +test "Nullable variable has a default value at null" { + str? hello; + + assert(hello == null, message: "Nullable variable has default value at null"); +} \ No newline at end of file