Pragma.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. //===--- Pragma.cpp - Pragma registration and handling --------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by Chris Lattner and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the PragmaHandler/PragmaTable interfaces and implements
  11. // pragma related methods of the Preprocessor class.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Lex/Pragma.h"
  15. #include "clang/Lex/PPCallbacks.h"
  16. #include "clang/Lex/HeaderSearch.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Basic/Diagnostic.h"
  19. #include "clang/Basic/FileManager.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. using namespace clang;
  23. // Out-of-line destructor to provide a home for the class.
  24. PragmaHandler::~PragmaHandler() {
  25. }
  26. //===----------------------------------------------------------------------===//
  27. // PragmaNamespace Implementation.
  28. //===----------------------------------------------------------------------===//
  29. PragmaNamespace::~PragmaNamespace() {
  30. for (unsigned i = 0, e = Handlers.size(); i != e; ++i)
  31. delete Handlers[i];
  32. }
  33. /// FindHandler - Check to see if there is already a handler for the
  34. /// specified name. If not, return the handler for the null identifier if it
  35. /// exists, otherwise return null. If IgnoreNull is true (the default) then
  36. /// the null handler isn't returned on failure to match.
  37. PragmaHandler *PragmaNamespace::FindHandler(const IdentifierInfo *Name,
  38. bool IgnoreNull) const {
  39. PragmaHandler *NullHandler = 0;
  40. for (unsigned i = 0, e = Handlers.size(); i != e; ++i) {
  41. if (Handlers[i]->getName() == Name)
  42. return Handlers[i];
  43. if (Handlers[i]->getName() == 0)
  44. NullHandler = Handlers[i];
  45. }
  46. return IgnoreNull ? 0 : NullHandler;
  47. }
  48. void PragmaNamespace::HandlePragma(Preprocessor &PP, LexerToken &Tok) {
  49. // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
  50. // expand it, the user can have a STDC #define, that should not affect this.
  51. PP.LexUnexpandedToken(Tok);
  52. // Get the handler for this token. If there is no handler, ignore the pragma.
  53. PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo(), false);
  54. if (Handler == 0) return;
  55. // Otherwise, pass it down.
  56. Handler->HandlePragma(PP, Tok);
  57. }
  58. //===----------------------------------------------------------------------===//
  59. // Preprocessor Pragma Directive Handling.
  60. //===----------------------------------------------------------------------===//
  61. /// HandlePragmaDirective - The "#pragma" directive has been parsed. Lex the
  62. /// rest of the pragma, passing it to the registered pragma handlers.
  63. void Preprocessor::HandlePragmaDirective() {
  64. ++NumPragma;
  65. // Invoke the first level of pragma handlers which reads the namespace id.
  66. LexerToken Tok;
  67. PragmaHandlers->HandlePragma(*this, Tok);
  68. // If the pragma handler didn't read the rest of the line, consume it now.
  69. if (CurLexer->ParsingPreprocessorDirective)
  70. DiscardUntilEndOfDirective();
  71. }
  72. /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
  73. /// return the first token after the directive. The _Pragma token has just
  74. /// been read into 'Tok'.
  75. void Preprocessor::Handle_Pragma(LexerToken &Tok) {
  76. // Remember the pragma token location.
  77. SourceLocation PragmaLoc = Tok.getLocation();
  78. // Read the '('.
  79. Lex(Tok);
  80. if (Tok.getKind() != tok::l_paren)
  81. return Diag(PragmaLoc, diag::err__Pragma_malformed);
  82. // Read the '"..."'.
  83. Lex(Tok);
  84. if (Tok.getKind() != tok::string_literal &&
  85. Tok.getKind() != tok::wide_string_literal)
  86. return Diag(PragmaLoc, diag::err__Pragma_malformed);
  87. // Remember the string.
  88. std::string StrVal = getSpelling(Tok);
  89. SourceLocation StrLoc = Tok.getLocation();
  90. // Read the ')'.
  91. Lex(Tok);
  92. if (Tok.getKind() != tok::r_paren)
  93. return Diag(PragmaLoc, diag::err__Pragma_malformed);
  94. // The _Pragma is lexically sound. Destringize according to C99 6.10.9.1.
  95. if (StrVal[0] == 'L') // Remove L prefix.
  96. StrVal.erase(StrVal.begin());
  97. assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
  98. "Invalid string token!");
  99. // Remove the front quote, replacing it with a space, so that the pragma
  100. // contents appear to have a space before them.
  101. StrVal[0] = ' ';
  102. // Replace the terminating quote with a \n\0.
  103. StrVal[StrVal.size()-1] = '\n';
  104. StrVal += '\0';
  105. // Remove escaped quotes and escapes.
  106. for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
  107. if (StrVal[i] == '\\' &&
  108. (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
  109. // \\ -> '\' and \" -> '"'.
  110. StrVal.erase(StrVal.begin()+i);
  111. --e;
  112. }
  113. }
  114. // Plop the string (including the newline and trailing null) into a buffer
  115. // where we can lex it.
  116. SourceLocation TokLoc = CreateString(&StrVal[0], StrVal.size(), StrLoc);
  117. const char *StrData = SourceMgr.getCharacterData(TokLoc);
  118. unsigned FileID = TokLoc.getFileID();
  119. assert(FileID && "Could not get FileID for _Pragma?");
  120. // Make and enter a lexer object so that we lex and expand the tokens just
  121. // like any others.
  122. Lexer *TL = new Lexer(SourceMgr.getBuffer(FileID), FileID, *this,
  123. StrData, StrData+StrVal.size()-1 /* no null */);
  124. // Ensure that the lexer thinks it is inside a directive, so that end \n will
  125. // return an EOM token.
  126. TL->ParsingPreprocessorDirective = true;
  127. // This lexer really is for _Pragma.
  128. TL->Is_PragmaLexer = true;
  129. EnterSourceFileWithLexer(TL, 0);
  130. // With everything set up, lex this as a #pragma directive.
  131. HandlePragmaDirective();
  132. // Finally, return whatever came after the pragma directive.
  133. return Lex(Tok);
  134. }
  135. /// HandlePragmaOnce - Handle #pragma once. OnceTok is the 'once'.
  136. ///
  137. void Preprocessor::HandlePragmaOnce(LexerToken &OnceTok) {
  138. if (isInPrimaryFile()) {
  139. Diag(OnceTok, diag::pp_pragma_once_in_main_file);
  140. return;
  141. }
  142. // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
  143. unsigned FileID = getCurrentFileLexer()->getCurFileID();
  144. // Mark the file as a once-only file now.
  145. HeaderInfo.MarkFileIncludeOnce(SourceMgr.getFileEntryForFileID(FileID));
  146. }
  147. /// HandlePragmaPoison - Handle #pragma GCC poison. PoisonTok is the 'poison'.
  148. ///
  149. void Preprocessor::HandlePragmaPoison(LexerToken &PoisonTok) {
  150. LexerToken Tok;
  151. while (1) {
  152. // Read the next token to poison. While doing this, pretend that we are
  153. // skipping while reading the identifier to poison.
  154. // This avoids errors on code like:
  155. // #pragma GCC poison X
  156. // #pragma GCC poison X
  157. if (CurLexer) CurLexer->LexingRawMode = true;
  158. LexUnexpandedToken(Tok);
  159. if (CurLexer) CurLexer->LexingRawMode = false;
  160. // If we reached the end of line, we're done.
  161. if (Tok.getKind() == tok::eom) return;
  162. // Can only poison identifiers.
  163. if (Tok.getKind() != tok::identifier) {
  164. Diag(Tok, diag::err_pp_invalid_poison);
  165. return;
  166. }
  167. // Look up the identifier info for the token. We disabled identifier lookup
  168. // by saying we're skipping contents, so we need to do this manually.
  169. IdentifierInfo *II = LookUpIdentifierInfo(Tok);
  170. // Already poisoned.
  171. if (II->isPoisoned()) continue;
  172. // If this is a macro identifier, emit a warning.
  173. if (II->getMacroInfo())
  174. Diag(Tok, diag::pp_poisoning_existing_macro);
  175. // Finally, poison it!
  176. II->setIsPoisoned();
  177. }
  178. }
  179. /// HandlePragmaSystemHeader - Implement #pragma GCC system_header. We know
  180. /// that the whole directive has been parsed.
  181. void Preprocessor::HandlePragmaSystemHeader(LexerToken &SysHeaderTok) {
  182. if (isInPrimaryFile()) {
  183. Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
  184. return;
  185. }
  186. // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
  187. Lexer *TheLexer = getCurrentFileLexer();
  188. // Mark the file as a system header.
  189. const FileEntry *File =
  190. SourceMgr.getFileEntryForFileID(TheLexer->getCurFileID());
  191. HeaderInfo.MarkFileSystemHeader(File);
  192. // Notify the client, if desired, that we are in a new source file.
  193. if (Callbacks)
  194. Callbacks->FileChanged(TheLexer->getSourceLocation(TheLexer->BufferPtr),
  195. PPCallbacks::SystemHeaderPragma,
  196. DirectoryLookup::SystemHeaderDir);
  197. }
  198. /// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
  199. ///
  200. void Preprocessor::HandlePragmaDependency(LexerToken &DependencyTok) {
  201. LexerToken FilenameTok;
  202. CurLexer->LexIncludeFilename(FilenameTok);
  203. // If the token kind is EOM, the error has already been diagnosed.
  204. if (FilenameTok.getKind() == tok::eom)
  205. return;
  206. // Reserve a buffer to get the spelling.
  207. llvm::SmallVector<char, 128> FilenameBuffer;
  208. FilenameBuffer.resize(FilenameTok.getLength());
  209. const char *FilenameStart = &FilenameBuffer[0], *FilenameEnd;
  210. bool isAngled = GetIncludeFilenameSpelling(FilenameTok,
  211. FilenameStart, FilenameEnd);
  212. // If GetIncludeFilenameSpelling set the start ptr to null, there was an
  213. // error.
  214. if (FilenameStart == 0)
  215. return;
  216. // Search include directories for this file.
  217. const DirectoryLookup *CurDir;
  218. const FileEntry *File = LookupFile(FilenameStart, FilenameEnd,
  219. isAngled, 0, CurDir);
  220. if (File == 0)
  221. return Diag(FilenameTok, diag::err_pp_file_not_found,
  222. std::string(FilenameStart, FilenameEnd));
  223. unsigned FileID = getCurrentFileLexer()->getCurFileID();
  224. const FileEntry *CurFile = SourceMgr.getFileEntryForFileID(FileID);
  225. // If this file is older than the file it depends on, emit a diagnostic.
  226. if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
  227. // Lex tokens at the end of the message and include them in the message.
  228. std::string Message;
  229. Lex(DependencyTok);
  230. while (DependencyTok.getKind() != tok::eom) {
  231. Message += getSpelling(DependencyTok) + " ";
  232. Lex(DependencyTok);
  233. }
  234. Message.erase(Message.end()-1);
  235. Diag(FilenameTok, diag::pp_out_of_date_dependency, Message);
  236. }
  237. }
  238. /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
  239. /// If 'Namespace' is non-null, then it is a token required to exist on the
  240. /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
  241. void Preprocessor::AddPragmaHandler(const char *Namespace,
  242. PragmaHandler *Handler) {
  243. PragmaNamespace *InsertNS = PragmaHandlers;
  244. // If this is specified to be in a namespace, step down into it.
  245. if (Namespace) {
  246. IdentifierInfo *NSID = getIdentifierInfo(Namespace);
  247. // If there is already a pragma handler with the name of this namespace,
  248. // we either have an error (directive with the same name as a namespace) or
  249. // we already have the namespace to insert into.
  250. if (PragmaHandler *Existing = PragmaHandlers->FindHandler(NSID)) {
  251. InsertNS = Existing->getIfNamespace();
  252. assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
  253. " handler with the same name!");
  254. } else {
  255. // Otherwise, this namespace doesn't exist yet, create and insert the
  256. // handler for it.
  257. InsertNS = new PragmaNamespace(NSID);
  258. PragmaHandlers->AddPragma(InsertNS);
  259. }
  260. }
  261. // Check to make sure we don't already have a pragma for this identifier.
  262. assert(!InsertNS->FindHandler(Handler->getName()) &&
  263. "Pragma handler already exists for this identifier!");
  264. InsertNS->AddPragma(Handler);
  265. }
  266. namespace {
  267. struct PragmaOnceHandler : public PragmaHandler {
  268. PragmaOnceHandler(const IdentifierInfo *OnceID) : PragmaHandler(OnceID) {}
  269. virtual void HandlePragma(Preprocessor &PP, LexerToken &OnceTok) {
  270. PP.CheckEndOfDirective("#pragma once");
  271. PP.HandlePragmaOnce(OnceTok);
  272. }
  273. };
  274. struct PragmaPoisonHandler : public PragmaHandler {
  275. PragmaPoisonHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
  276. virtual void HandlePragma(Preprocessor &PP, LexerToken &PoisonTok) {
  277. PP.HandlePragmaPoison(PoisonTok);
  278. }
  279. };
  280. struct PragmaSystemHeaderHandler : public PragmaHandler {
  281. PragmaSystemHeaderHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
  282. virtual void HandlePragma(Preprocessor &PP, LexerToken &SHToken) {
  283. PP.HandlePragmaSystemHeader(SHToken);
  284. PP.CheckEndOfDirective("#pragma");
  285. }
  286. };
  287. struct PragmaDependencyHandler : public PragmaHandler {
  288. PragmaDependencyHandler(const IdentifierInfo *ID) : PragmaHandler(ID) {}
  289. virtual void HandlePragma(Preprocessor &PP, LexerToken &DepToken) {
  290. PP.HandlePragmaDependency(DepToken);
  291. }
  292. };
  293. } // end anonymous namespace
  294. /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
  295. /// #pragma GCC poison/system_header/dependency and #pragma once.
  296. void Preprocessor::RegisterBuiltinPragmas() {
  297. AddPragmaHandler(0, new PragmaOnceHandler(getIdentifierInfo("once")));
  298. AddPragmaHandler("GCC", new PragmaPoisonHandler(getIdentifierInfo("poison")));
  299. AddPragmaHandler("GCC", new PragmaSystemHeaderHandler(
  300. getIdentifierInfo("system_header")));
  301. AddPragmaHandler("GCC", new PragmaDependencyHandler(
  302. getIdentifierInfo("dependency")));
  303. }