From: Alistair Thomas Date: Mon, 25 Jun 2018 17:57:08 +0000 (+0100) Subject: vala: Allow read-only properties X-Git-Tag: 0.41.90~44 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=cbb92150d54e66b1bd84775d58d9f4b8a305967e;p=thirdparty%2Fvala.git vala: Allow read-only properties See https://gitlab.gnome.org/GNOME/vala/merge_requests/10 --- diff --git a/tests/Makefile.am b/tests/Makefile.am index c202f3015..9f9d614b3 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -240,6 +240,7 @@ TESTS = \ objects/paramspec.vala \ objects/properties.vala \ objects/property-notify.vala \ + objects/property-read-only-auto.vala \ objects/regex.vala \ objects/signals.vala \ objects/signals-delegate.vala \ diff --git a/tests/objects/property-read-only-auto.vala b/tests/objects/property-read-only-auto.vala new file mode 100644 index 000000000..e782d434e --- /dev/null +++ b/tests/objects/property-read-only-auto.vala @@ -0,0 +1,26 @@ +class Foo { + public int read_only { get; default = 42; } +} + +class Bar : Object { + public int read_only { get; default = 23; } +} + +interface IBaz : Object { + public abstract int read_only { get; } +} + +class Baz : Object, IBaz { + public int read_only { get; default = 4711; } +} + +void main () { + var foo = new Foo (); + assert (foo.read_only == 42); + + var bar = new Bar (); + assert (bar.read_only == 23); + + var baz = new Baz (); + assert (baz.read_only == 4711); +} diff --git a/vala/valaproperty.vala b/vala/valaproperty.vala index 6e5ae6973..aa899f636 100644 --- a/vala/valaproperty.vala +++ b/vala/valaproperty.vala @@ -103,17 +103,19 @@ public class Vala.Property : Symbol, Lockable { get { if (!_field_checked) { if (!is_abstract && source_type == SourceFileType.SOURCE) { - bool empty_get = (get_accessor != null && get_accessor.body == null); - bool empty_set = (set_accessor != null && set_accessor.body == null); - if (empty_get != empty_set) { - if (empty_get) { - Report.error (source_reference, "Property getter must have a body"); - } else if (empty_set) { - Report.error (source_reference, "Property setter must have a body"); - } + bool has_get = (get_accessor != null); + bool get_has_body = (has_get && get_accessor.body != null); + bool has_set = (set_accessor != null); + bool set_has_body = (has_set && set_accessor.body != null); + if (set_has_body && (has_get && !get_has_body)) { + error = true; + Report.error (source_reference, "Property getter must have a body"); + } + if (get_has_body && (has_set && !set_has_body)) { error = true; + Report.error (source_reference, "Property setter must have a body"); } - if (empty_get && empty_set) { + if (!get_has_body && !set_has_body) { /* automatic property accessor body generation */ _field = new Field ("_%s".printf (name), property_type.copy (), initializer, source_reference); _field.access = SymbolAccessibility.PRIVATE;