[PATCH] D11658: [Sema] main can't be declared as global variable

Davide Italiano dccitaliano at gmail.com
Thu Jul 30 12:01:22 PDT 2015


davide created this revision.
davide added reviewers: aaron.ballman, rsmith.
davide added a subscriber: cfe-commits.

I modeled it in this way: every time we act on a variable declaration, we check if it's main and it's global, and in case it's true we emit a diagnostic. Actually, to completely fulfill the standard requirements we should also consider ill-formed anything that declares the name "main" with C linkage, but I'd like to tackle this separately. In particular I'm not sure if "name" refers only to variables or also to e.g. function names etc..
For reference, this was reported in PR24309. 

http://reviews.llvm.org/D11658

Files:
  include/clang/Basic/DiagnosticSemaKinds.td
  lib/Sema/SemaDecl.cpp
  test/CXX/basic/basic.start/basic.start.main/p3.cpp

Index: test/CXX/basic/basic.start/basic.start.main/p3.cpp
===================================================================
--- test/CXX/basic/basic.start/basic.start.main/p3.cpp
+++ test/CXX/basic/basic.start/basic.start.main/p3.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+int main; // expected-error{{main can't be declared as global variable}}
+
+int f () {
+  int main; // OK
+  (void)main;
+}
Index: lib/Sema/SemaDecl.cpp
===================================================================
--- lib/Sema/SemaDecl.cpp
+++ lib/Sema/SemaDecl.cpp
@@ -6105,6 +6105,13 @@
     }
   }
 
+  // [basic.start.main]p3
+  // A program that declares a variable main at global scope is ill-formed.
+  if (getLangOpts().CPlusPlus && Name.getAsString() == "main" &&
+      NewVD->isFileVarDecl()) {
+      Diag(D.getLocStart(), diag::err_main_global_variable);
+  }
+
   if (D.isRedeclaration() && !Previous.empty()) {
     checkDLLAttributeRedeclaration(
         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
Index: include/clang/Basic/DiagnosticSemaKinds.td
===================================================================
--- include/clang/Basic/DiagnosticSemaKinds.td
+++ include/clang/Basic/DiagnosticSemaKinds.td
@@ -510,6 +510,7 @@
 def err_main_arg_wrong : Error<"%select{first|second|third|fourth}0 "
     "parameter of 'main' (%select{argument count|argument array|environment|"
     "platform-specific data}0) must be of type %1">;
+def err_main_global_variable : Error<"main can't be declared as global variable">;
 def ext_main_used : Extension<
   "ISO C++ does not allow 'main' to be used by a program">, InGroup<Main>;
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D11658.31063.patch
Type: text/x-patch
Size: 1678 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20150730/3658b1af/attachment.bin>


More information about the cfe-commits mailing list