This is the mail archive of the
gcc-patches@gcc.gnu.org
mailing list for the GCC project.
[PATCH 02/02] C FE: add fix-it hint for . vs ->
- From: David Malcolm <dmalcolm at redhat dot com>
- To: gcc-patches at gcc dot gnu dot org
- Cc: David Malcolm <dmalcolm at redhat dot com>
- Date: Tue, 10 Nov 2015 11:35:25 -0500
- Subject: [PATCH 02/02] C FE: add fix-it hint for . vs ->
- Authentication-results: sourceware.org; auth=none
- References: <1447173325-48683-1-git-send-email-dmalcolm at redhat dot com>
This is the most trivial example of a real fix-it example I could think
of: if the user writes
ptr.field
rather than ptr->field.
gcc/c/ChangeLog:
* c-typeck.c (build_component_ref): Special-case POINTER_TYPE when
generating a "not a structure of union" error message, and
suggest a "->" rather than a ".", providing a fix-it hint.
gcc/testsuite/ChangeLog:
* gcc.dg/fixits.c: New file.
---
gcc/c/c-typeck.c | 15 +++++++++++++++
gcc/testsuite/gcc.dg/fixits.c | 14 ++++++++++++++
2 files changed, 29 insertions(+)
create mode 100644 gcc/testsuite/gcc.dg/fixits.c
diff --git a/gcc/c/c-typeck.c b/gcc/c/c-typeck.c
index c2e16c6..6fe1ca8 100644
--- a/gcc/c/c-typeck.c
+++ b/gcc/c/c-typeck.c
@@ -2336,6 +2336,21 @@ build_component_ref (location_t loc, tree datum, tree component)
return ref;
}
+ else if (code == POINTER_TYPE && !c_dialect_objc ())
+ {
+ /* Special-case the error message for "ptr.field" for the case
+ where the user has confused "." vs "->".
+ We don't do it for Objective-C, since Objective-C 2.0 dot-syntax
+ allows "." for ptrs; we could be handling a failed attempt
+ to access a property. */
+ rich_location richloc (line_table, loc);
+ /* "loc" should be the "." token. */
+ richloc.add_fixit_replace (source_range::from_location (loc), "->");
+ error_at_rich_loc (&richloc,
+ "%qE is a pointer; did you mean to use %<->%>?",
+ datum);
+ return error_mark_node;
+ }
else if (code != ERROR_MARK)
error_at (loc,
"request for member %qE in something not a structure or union",
diff --git a/gcc/testsuite/gcc.dg/fixits.c b/gcc/testsuite/gcc.dg/fixits.c
new file mode 100644
index 0000000..3b8c8a8
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/fixits.c
@@ -0,0 +1,14 @@
+/* { dg-do compile } */
+/* { dg-options "-fdiagnostics-show-caret" } */
+
+struct foo { int x; };
+
+int test (struct foo *ptr)
+{
+ return ptr.x; /* { dg-error "'ptr' is a pointer; did you mean to use '->'?" } */
+/* { dg-begin-multiline-output "" }
+ return ptr.x;
+ ^
+ ->
+ { dg-end-multiline-output "" } */
+}
--
1.8.5.3