[vala/staging] vala: Automatically remove superfluous silent casts
- From: Rico Tzschichholz <ricotz src gnome org>
- To: commits-list gnome org
- Cc:
- Subject: [vala/staging] vala: Automatically remove superfluous silent casts
- Date: Wed, 11 Nov 2020 17:24:25 +0000 (UTC)
commit e1d03574336db5b5f42f7869baed5ce98c274bc3
Author: Rico Tzschichholz <ricotz ubuntu com>
Date: Wed Nov 11 17:04:32 2020 +0100
vala: Automatically remove superfluous silent casts
If type of expression is target type then omit this GType cast.
This will clean up existing sources which matches the expected scheme for
type narrowing, see https://gitlab.gnome.org/GNOME/vala/issues/894
tests/Makefile.am | 1 +
tests/objects/casting-silent.vala | 28 ++++++++++++++++++++++++++++
vala/valacastexpression.vala | 9 +++++++++
3 files changed, 38 insertions(+)
---
diff --git a/tests/Makefile.am b/tests/Makefile.am
index 50816d39c..0c6db3f00 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -390,6 +390,7 @@ TESTS = \
delegates/bug761360.vala \
delegates/bug772204.test \
delegates/bug792077.vala \
+ objects/casting-silent.vala \
objects/chainup.vala \
objects/class-ccode-cprefix.vala \
objects/class_only.vala \
diff --git a/tests/objects/casting-silent.vala b/tests/objects/casting-silent.vala
new file mode 100644
index 000000000..51928cd75
--- /dev/null
+++ b/tests/objects/casting-silent.vala
@@ -0,0 +1,28 @@
+class Foo {
+}
+
+class Bar : Foo {
+}
+
+Bar get_bar () {
+ return new Bar ();
+}
+
+void main() {
+ {
+ var bar = new Foo ();
+ var foo = bar as Foo;
+
+ assert (foo == bar);
+ assert (foo == (bar as Foo));
+ assert (bar == (foo as Foo));
+ }
+ {
+ var bar = get_bar () as Foo;
+ var foo = bar as Bar;
+
+ assert (foo == bar);
+ assert (foo == (bar as Bar));
+ assert (bar == (foo as Foo));
+ }
+}
diff --git a/vala/valacastexpression.vala b/vala/valacastexpression.vala
index 86b9f9a12..e391b5f92 100644
--- a/vala/valacastexpression.vala
+++ b/vala/valacastexpression.vala
@@ -199,6 +199,15 @@ public class Vala.CastExpression : Expression {
if (is_silent_cast) {
value_type.nullable = true;
+
+ // Drop superfluous casts, if the source and target type matches then this cast is
not required
+ if (context.profile == Profile.GOBJECT
+ && type_reference.type_symbol is ObjectTypeSymbol && type_reference.type_symbol
== inner.value_type.type_symbol) {
+ Report.warning (source_reference, "Casting to `%s' is superfluous".printf
(type_reference.to_qualified_string ()));
+ context.analyzer.replaced_nodes.add (this);
+ parent_node.replace_expression (this, inner);
+ return !error;
+ }
}
if (context.profile == Profile.GOBJECT
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]