Suggest including <stdbool.h> for bool, true and false

Message ID 20200519213658.41099-1-mark@klomp.org
State New
Headers show
Series
  • Suggest including <stdbool.h> for bool, true and false
Related show

Commit Message

Mark Wielaard May 19, 2020, 9:36 p.m.
Currently gcc suggests to use _Bool instead of bool and doesn't give
any suggestions when true or false are used, but undefined. This patch
makes it so that (for C99 or higher) a fixit hint is emitted to include
<stdbool.h>.

gcc/c-family/ChangeLog:

	* known-headers.cc (get_stdlib_header_for_name): Return
        "<stdbool.h> for "bool", "true" or "false" when STDLIB_C and
        flag_isoc99.

gcc/testsuite/ChangeLog:

	* gcc.dg/spellcheck-stdbool.c: New test.
---
 gcc/c-family/known-headers.cc             |  8 ++++++++
 gcc/testsuite/gcc.dg/spellcheck-stdbool.c | 17 +++++++++++++++++
 2 files changed, 25 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/spellcheck-stdbool.c

-- 
2.20.1

Comments

H.J. Lu via Gcc-patches May 22, 2020, 1:14 p.m. | #1
On Tue, 2020-05-19 at 23:36 +0200, Mark Wielaard wrote:
> Currently gcc suggests to use _Bool instead of bool and doesn't give

> any suggestions when true or false are used, but undefined. This

> patch

> makes it so that (for C99 or higher) a fixit hint is emitted to

> include

> <stdbool.h>.


[...snip...]

Looks good to me.

Thanks
Dave

Patch

diff --git a/gcc/c-family/known-headers.cc b/gcc/c-family/known-headers.cc
index a21166860c0f..183ce2834afd 100644
--- a/gcc/c-family/known-headers.cc
+++ b/gcc/c-family/known-headers.cc
@@ -158,6 +158,14 @@  get_stdlib_header_for_name (const char *name, enum stdlib lib)
   for (size_t i = 0; i < num_hints; i++)
     if (strcmp (name, hints[i].name) == 0)
       return hints[i].header[lib];
+
+  /* Only for C99 and higher.  */
+  if (lib == STDLIB_C && flag_isoc99)
+    if (strcmp (name, "bool") == 0
+	|| strcmp (name, "true") == 0
+	|| strcmp (name, "false") == 0)
+      return "<stdbool.h>";
+
   return NULL;
 }
 
diff --git a/gcc/testsuite/gcc.dg/spellcheck-stdbool.c b/gcc/testsuite/gcc.dg/spellcheck-stdbool.c
new file mode 100644
index 000000000000..01f12da35cfe
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/spellcheck-stdbool.c
@@ -0,0 +1,17 @@ 
+/* { dg-options "-std=c99" } */
+/* Missing <stdbool.h>.  */
+
+bool b; /* { dg-error "unknown type name 'bool'" } */
+/* { dg-message "'bool' is defined in header '<stdbool.h>'; did you forget to '#include <stdbool.h>'?" "" { target *-*-* } .-1 } */
+
+int test_true (void)
+{
+  return true; /* { dg-error "'true' undeclared" } */
+  /* { dg-message "'true' is defined in header '<stdbool.h>'; did you forget to '#include <stdbool.h>'?" "" { target *-*-* } .-1 } */
+}
+
+int test_false (void)
+{
+  return false; /* { dg-error "'false' undeclared" } */
+  /* { dg-message "'false' is defined in header '<stdbool.h>'; did you forget to '#include <stdbool.h>'?" "" { target *-*-* } .-1 } */
+}