150
|
1 //===- Preprocessor.cpp - C Language Family Preprocessor Implementation ---===//
|
|
2 //
|
|
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
4 // See https://llvm.org/LICENSE.txt for license information.
|
|
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
6 //
|
|
7 //===----------------------------------------------------------------------===//
|
|
8 //
|
|
9 // This file implements the Preprocessor interface.
|
|
10 //
|
|
11 //===----------------------------------------------------------------------===//
|
|
12 //
|
|
13 // Options to support:
|
|
14 // -H - Print the name of each header file used.
|
|
15 // -d[DNI] - Dump various things.
|
|
16 // -fworking-directory - #line's with preprocessor's working dir.
|
|
17 // -fpreprocessed
|
|
18 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
|
|
19 // -W*
|
|
20 // -w
|
|
21 //
|
|
22 // Messages to emit:
|
|
23 // "Multiple include guards may be useful for:\n"
|
|
24 //
|
|
25 //===----------------------------------------------------------------------===//
|
|
26
|
|
27 #include "clang/Lex/Preprocessor.h"
|
|
28 #include "clang/Basic/Builtins.h"
|
|
29 #include "clang/Basic/FileManager.h"
|
|
30 #include "clang/Basic/FileSystemStatCache.h"
|
|
31 #include "clang/Basic/IdentifierTable.h"
|
|
32 #include "clang/Basic/LLVM.h"
|
|
33 #include "clang/Basic/LangOptions.h"
|
|
34 #include "clang/Basic/Module.h"
|
|
35 #include "clang/Basic/SourceLocation.h"
|
|
36 #include "clang/Basic/SourceManager.h"
|
|
37 #include "clang/Basic/TargetInfo.h"
|
|
38 #include "clang/Lex/CodeCompletionHandler.h"
|
|
39 #include "clang/Lex/ExternalPreprocessorSource.h"
|
|
40 #include "clang/Lex/HeaderSearch.h"
|
|
41 #include "clang/Lex/LexDiagnostic.h"
|
|
42 #include "clang/Lex/Lexer.h"
|
|
43 #include "clang/Lex/LiteralSupport.h"
|
|
44 #include "clang/Lex/MacroArgs.h"
|
|
45 #include "clang/Lex/MacroInfo.h"
|
|
46 #include "clang/Lex/ModuleLoader.h"
|
|
47 #include "clang/Lex/Pragma.h"
|
|
48 #include "clang/Lex/PreprocessingRecord.h"
|
|
49 #include "clang/Lex/PreprocessorLexer.h"
|
|
50 #include "clang/Lex/PreprocessorOptions.h"
|
|
51 #include "clang/Lex/ScratchBuffer.h"
|
|
52 #include "clang/Lex/Token.h"
|
|
53 #include "clang/Lex/TokenLexer.h"
|
|
54 #include "llvm/ADT/APInt.h"
|
|
55 #include "llvm/ADT/ArrayRef.h"
|
|
56 #include "llvm/ADT/DenseMap.h"
|
|
57 #include "llvm/ADT/STLExtras.h"
|
|
58 #include "llvm/ADT/SmallString.h"
|
|
59 #include "llvm/ADT/SmallVector.h"
|
|
60 #include "llvm/ADT/StringRef.h"
|
|
61 #include "llvm/Support/Capacity.h"
|
|
62 #include "llvm/Support/ErrorHandling.h"
|
|
63 #include "llvm/Support/MemoryBuffer.h"
|
|
64 #include "llvm/Support/raw_ostream.h"
|
|
65 #include <algorithm>
|
|
66 #include <cassert>
|
|
67 #include <memory>
|
|
68 #include <string>
|
|
69 #include <utility>
|
|
70 #include <vector>
|
|
71
|
|
72 using namespace clang;
|
|
73
|
|
74 LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
|
|
75
|
|
76 ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
|
|
77
|
|
78 Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
|
|
79 DiagnosticsEngine &diags, LangOptions &opts,
|
|
80 SourceManager &SM, HeaderSearch &Headers,
|
|
81 ModuleLoader &TheModuleLoader,
|
|
82 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
|
|
83 TranslationUnitKind TUKind)
|
|
84 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
|
|
85 FileMgr(Headers.getFileMgr()), SourceMgr(SM),
|
|
86 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
|
|
87 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
|
|
88 // As the language options may have not been loaded yet (when
|
|
89 // deserializing an ASTUnit), adding keywords to the identifier table is
|
|
90 // deferred to Preprocessor::Initialize().
|
|
91 Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
|
|
92 TUKind(TUKind), SkipMainFilePreamble(0, true),
|
|
93 CurSubmoduleState(&NullSubmoduleState) {
|
|
94 OwnsHeaderSearch = OwnsHeaders;
|
|
95
|
|
96 // Default to discarding comments.
|
|
97 KeepComments = false;
|
|
98 KeepMacroComments = false;
|
|
99 SuppressIncludeNotFoundError = false;
|
|
100
|
|
101 // Macro expansion is enabled.
|
|
102 DisableMacroExpansion = false;
|
|
103 MacroExpansionInDirectivesOverride = false;
|
|
104 InMacroArgs = false;
|
|
105 ArgMacro = nullptr;
|
|
106 InMacroArgPreExpansion = false;
|
|
107 NumCachedTokenLexers = 0;
|
|
108 PragmasEnabled = true;
|
|
109 ParsingIfOrElifDirective = false;
|
|
110 PreprocessedOutput = false;
|
|
111
|
|
112 // We haven't read anything from the external source.
|
|
113 ReadMacrosFromExternalSource = false;
|
|
114
|
|
115 BuiltinInfo = std::make_unique<Builtin::Context>();
|
|
116
|
|
117 // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
|
|
118 // a macro. They get unpoisoned where it is allowed.
|
|
119 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
|
|
120 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
|
221
|
121 (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
|
|
122 SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
|
150
|
123
|
|
124 // Initialize the pragma handlers.
|
|
125 RegisterBuiltinPragmas();
|
|
126
|
|
127 // Initialize builtin macros like __LINE__ and friends.
|
|
128 RegisterBuiltinMacros();
|
|
129
|
|
130 if(LangOpts.Borland) {
|
|
131 Ident__exception_info = getIdentifierInfo("_exception_info");
|
|
132 Ident___exception_info = getIdentifierInfo("__exception_info");
|
|
133 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
|
|
134 Ident__exception_code = getIdentifierInfo("_exception_code");
|
|
135 Ident___exception_code = getIdentifierInfo("__exception_code");
|
|
136 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
|
|
137 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
|
|
138 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
|
|
139 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
|
|
140 } else {
|
|
141 Ident__exception_info = Ident__exception_code = nullptr;
|
|
142 Ident__abnormal_termination = Ident___exception_info = nullptr;
|
|
143 Ident___exception_code = Ident___abnormal_termination = nullptr;
|
|
144 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
|
|
145 Ident_AbnormalTermination = nullptr;
|
|
146 }
|
|
147
|
|
148 // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
|
|
149 if (usingPCHWithPragmaHdrStop())
|
|
150 SkippingUntilPragmaHdrStop = true;
|
|
151
|
|
152 // If using a PCH with a through header, start skipping tokens.
|
|
153 if (!this->PPOpts->PCHThroughHeader.empty() &&
|
|
154 !this->PPOpts->ImplicitPCHInclude.empty())
|
|
155 SkippingUntilPCHThroughHeader = true;
|
|
156
|
|
157 if (this->PPOpts->GeneratePreamble)
|
|
158 PreambleConditionalStack.startRecording();
|
|
159
|
|
160 MaxTokens = LangOpts.MaxTokens;
|
|
161 }
|
|
162
|
|
163 Preprocessor::~Preprocessor() {
|
|
164 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
|
|
165
|
|
166 IncludeMacroStack.clear();
|
|
167
|
|
168 // Free any cached macro expanders.
|
|
169 // This populates MacroArgCache, so all TokenLexers need to be destroyed
|
|
170 // before the code below that frees up the MacroArgCache list.
|
|
171 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
|
|
172 CurTokenLexer.reset();
|
|
173
|
|
174 // Free any cached MacroArgs.
|
|
175 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
|
|
176 ArgList = ArgList->deallocate();
|
|
177
|
|
178 // Delete the header search info, if we own it.
|
|
179 if (OwnsHeaderSearch)
|
|
180 delete &HeaderInfo;
|
|
181 }
|
|
182
|
|
183 void Preprocessor::Initialize(const TargetInfo &Target,
|
|
184 const TargetInfo *AuxTarget) {
|
|
185 assert((!this->Target || this->Target == &Target) &&
|
|
186 "Invalid override of target information");
|
|
187 this->Target = &Target;
|
|
188
|
|
189 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
|
|
190 "Invalid override of aux target information.");
|
|
191 this->AuxTarget = AuxTarget;
|
|
192
|
|
193 // Initialize information about built-ins.
|
|
194 BuiltinInfo->InitializeTarget(Target, AuxTarget);
|
|
195 HeaderInfo.setTarget(Target);
|
|
196
|
|
197 // Populate the identifier table with info about keywords for the current language.
|
|
198 Identifiers.AddKeywords(LangOpts);
|
236
|
199
|
|
200 // Initialize the __FTL_EVAL_METHOD__ macro to the TargetInfo.
|
|
201 setTUFPEvalMethod(getTargetInfo().getFPEvalMethod());
|
|
202
|
|
203 if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_UnsetOnCommandLine)
|
|
204 // Use setting from TargetInfo.
|
|
205 setCurrentFPEvalMethod(SourceLocation(), Target.getFPEvalMethod());
|
|
206 else
|
|
207 // Set initial value of __FLT_EVAL_METHOD__ from the command line.
|
|
208 setCurrentFPEvalMethod(SourceLocation(), getLangOpts().getFPEvalMethod());
|
|
209 // When `-ffast-math` option is enabled, it triggers several driver math
|
|
210 // options to be enabled. Among those, only one the following two modes
|
|
211 // affect the eval-method: reciprocal or reassociate.
|
|
212 if (getLangOpts().AllowFPReassoc || getLangOpts().AllowRecip)
|
|
213 setCurrentFPEvalMethod(SourceLocation(), LangOptions::FEM_Indeterminable);
|
150
|
214 }
|
|
215
|
|
216 void Preprocessor::InitializeForModelFile() {
|
|
217 NumEnteredSourceFiles = 0;
|
|
218
|
|
219 // Reset pragmas
|
|
220 PragmaHandlersBackup = std::move(PragmaHandlers);
|
|
221 PragmaHandlers = std::make_unique<PragmaNamespace>(StringRef());
|
|
222 RegisterBuiltinPragmas();
|
|
223
|
|
224 // Reset PredefinesFileID
|
|
225 PredefinesFileID = FileID();
|
|
226 }
|
|
227
|
|
228 void Preprocessor::FinalizeForModelFile() {
|
|
229 NumEnteredSourceFiles = 1;
|
|
230
|
|
231 PragmaHandlers = std::move(PragmaHandlersBackup);
|
|
232 }
|
|
233
|
|
234 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
|
236
|
235 llvm::errs() << tok::getTokenName(Tok.getKind());
|
|
236
|
|
237 if (!Tok.isAnnotation())
|
|
238 llvm::errs() << " '" << getSpelling(Tok) << "'";
|
150
|
239
|
|
240 if (!DumpFlags) return;
|
|
241
|
|
242 llvm::errs() << "\t";
|
|
243 if (Tok.isAtStartOfLine())
|
|
244 llvm::errs() << " [StartOfLine]";
|
|
245 if (Tok.hasLeadingSpace())
|
|
246 llvm::errs() << " [LeadingSpace]";
|
|
247 if (Tok.isExpandDisabled())
|
|
248 llvm::errs() << " [ExpandDisabled]";
|
|
249 if (Tok.needsCleaning()) {
|
|
250 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
|
|
251 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
|
|
252 << "']";
|
|
253 }
|
|
254
|
|
255 llvm::errs() << "\tLoc=<";
|
|
256 DumpLocation(Tok.getLocation());
|
|
257 llvm::errs() << ">";
|
|
258 }
|
|
259
|
|
260 void Preprocessor::DumpLocation(SourceLocation Loc) const {
|
|
261 Loc.print(llvm::errs(), SourceMgr);
|
|
262 }
|
|
263
|
|
264 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
|
|
265 llvm::errs() << "MACRO: ";
|
|
266 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
|
|
267 DumpToken(MI.getReplacementToken(i));
|
|
268 llvm::errs() << " ";
|
|
269 }
|
|
270 llvm::errs() << "\n";
|
|
271 }
|
|
272
|
|
273 void Preprocessor::PrintStats() {
|
|
274 llvm::errs() << "\n*** Preprocessor Stats:\n";
|
|
275 llvm::errs() << NumDirectives << " directives found:\n";
|
|
276 llvm::errs() << " " << NumDefined << " #define.\n";
|
|
277 llvm::errs() << " " << NumUndefined << " #undef.\n";
|
|
278 llvm::errs() << " #include/#include_next/#import:\n";
|
|
279 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
|
|
280 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
|
|
281 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
|
221
|
282 llvm::errs() << " " << NumElse << " #else/#elif/#elifdef/#elifndef.\n";
|
150
|
283 llvm::errs() << " " << NumEndif << " #endif.\n";
|
|
284 llvm::errs() << " " << NumPragma << " #pragma.\n";
|
|
285 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
|
|
286
|
|
287 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
|
|
288 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
|
|
289 << NumFastMacroExpanded << " on the fast path.\n";
|
|
290 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
|
|
291 << " token paste (##) operations performed, "
|
|
292 << NumFastTokenPaste << " on the fast path.\n";
|
|
293
|
|
294 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
|
|
295
|
|
296 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
|
|
297 llvm::errs() << "\n Macro Expanded Tokens: "
|
|
298 << llvm::capacity_in_bytes(MacroExpandedTokens);
|
|
299 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
|
|
300 // FIXME: List information for all submodules.
|
|
301 llvm::errs() << "\n Macros: "
|
|
302 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
|
|
303 llvm::errs() << "\n #pragma push_macro Info: "
|
|
304 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
|
|
305 llvm::errs() << "\n Poison Reasons: "
|
|
306 << llvm::capacity_in_bytes(PoisonReasons);
|
|
307 llvm::errs() << "\n Comment Handlers: "
|
|
308 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
|
|
309 }
|
|
310
|
|
311 Preprocessor::macro_iterator
|
|
312 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
|
|
313 if (IncludeExternalMacros && ExternalSource &&
|
|
314 !ReadMacrosFromExternalSource) {
|
|
315 ReadMacrosFromExternalSource = true;
|
|
316 ExternalSource->ReadDefinedMacros();
|
|
317 }
|
|
318
|
|
319 // Make sure we cover all macros in visible modules.
|
|
320 for (const ModuleMacro &Macro : ModuleMacros)
|
|
321 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
|
|
322
|
|
323 return CurSubmoduleState->Macros.begin();
|
|
324 }
|
|
325
|
|
326 size_t Preprocessor::getTotalMemory() const {
|
|
327 return BP.getTotalMemory()
|
|
328 + llvm::capacity_in_bytes(MacroExpandedTokens)
|
|
329 + Predefines.capacity() /* Predefines buffer. */
|
|
330 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
|
|
331 // and ModuleMacros.
|
|
332 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
|
|
333 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
|
|
334 + llvm::capacity_in_bytes(PoisonReasons)
|
|
335 + llvm::capacity_in_bytes(CommentHandlers);
|
|
336 }
|
|
337
|
|
338 Preprocessor::macro_iterator
|
|
339 Preprocessor::macro_end(bool IncludeExternalMacros) const {
|
|
340 if (IncludeExternalMacros && ExternalSource &&
|
|
341 !ReadMacrosFromExternalSource) {
|
|
342 ReadMacrosFromExternalSource = true;
|
|
343 ExternalSource->ReadDefinedMacros();
|
|
344 }
|
|
345
|
|
346 return CurSubmoduleState->Macros.end();
|
|
347 }
|
|
348
|
|
349 /// Compares macro tokens with a specified token value sequence.
|
|
350 static bool MacroDefinitionEquals(const MacroInfo *MI,
|
|
351 ArrayRef<TokenValue> Tokens) {
|
|
352 return Tokens.size() == MI->getNumTokens() &&
|
|
353 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
|
|
354 }
|
|
355
|
|
356 StringRef Preprocessor::getLastMacroWithSpelling(
|
|
357 SourceLocation Loc,
|
|
358 ArrayRef<TokenValue> Tokens) const {
|
|
359 SourceLocation BestLocation;
|
|
360 StringRef BestSpelling;
|
|
361 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
|
|
362 I != E; ++I) {
|
|
363 const MacroDirective::DefInfo
|
|
364 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
|
|
365 if (!Def || !Def.getMacroInfo())
|
|
366 continue;
|
|
367 if (!Def.getMacroInfo()->isObjectLike())
|
|
368 continue;
|
|
369 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
|
|
370 continue;
|
|
371 SourceLocation Location = Def.getLocation();
|
|
372 // Choose the macro defined latest.
|
|
373 if (BestLocation.isInvalid() ||
|
|
374 (Location.isValid() &&
|
|
375 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
|
|
376 BestLocation = Location;
|
|
377 BestSpelling = I->first->getName();
|
|
378 }
|
|
379 }
|
|
380 return BestSpelling;
|
|
381 }
|
|
382
|
|
383 void Preprocessor::recomputeCurLexerKind() {
|
|
384 if (CurLexer)
|
236
|
385 CurLexerKind = CurLexer->isDependencyDirectivesLexer()
|
|
386 ? CLK_DependencyDirectivesLexer
|
|
387 : CLK_Lexer;
|
150
|
388 else if (CurTokenLexer)
|
|
389 CurLexerKind = CLK_TokenLexer;
|
|
390 else
|
|
391 CurLexerKind = CLK_CachingLexer;
|
|
392 }
|
|
393
|
|
394 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
|
|
395 unsigned CompleteLine,
|
|
396 unsigned CompleteColumn) {
|
|
397 assert(File);
|
|
398 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
|
|
399 assert(!CodeCompletionFile && "Already set");
|
|
400
|
|
401 // Load the actual file's contents.
|
221
|
402 Optional<llvm::MemoryBufferRef> Buffer =
|
|
403 SourceMgr.getMemoryBufferForFileOrNone(File);
|
|
404 if (!Buffer)
|
150
|
405 return true;
|
|
406
|
|
407 // Find the byte position of the truncation point.
|
|
408 const char *Position = Buffer->getBufferStart();
|
|
409 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
|
|
410 for (; *Position; ++Position) {
|
|
411 if (*Position != '\r' && *Position != '\n')
|
|
412 continue;
|
|
413
|
|
414 // Eat \r\n or \n\r as a single line.
|
|
415 if ((Position[1] == '\r' || Position[1] == '\n') &&
|
|
416 Position[0] != Position[1])
|
|
417 ++Position;
|
|
418 ++Position;
|
|
419 break;
|
|
420 }
|
|
421 }
|
|
422
|
|
423 Position += CompleteColumn - 1;
|
|
424
|
|
425 // If pointing inside the preamble, adjust the position at the beginning of
|
|
426 // the file after the preamble.
|
|
427 if (SkipMainFilePreamble.first &&
|
|
428 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
|
|
429 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
|
|
430 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
|
|
431 }
|
|
432
|
|
433 if (Position > Buffer->getBufferEnd())
|
|
434 Position = Buffer->getBufferEnd();
|
|
435
|
|
436 CodeCompletionFile = File;
|
|
437 CodeCompletionOffset = Position - Buffer->getBufferStart();
|
|
438
|
|
439 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
|
|
440 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
|
|
441 char *NewBuf = NewBuffer->getBufferStart();
|
|
442 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
|
|
443 *NewPos = '\0';
|
|
444 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
|
|
445 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
|
|
446
|
|
447 return false;
|
|
448 }
|
|
449
|
|
450 void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
|
|
451 bool IsAngled) {
|
221
|
452 setCodeCompletionReached();
|
150
|
453 if (CodeComplete)
|
|
454 CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
|
|
455 }
|
|
456
|
|
457 void Preprocessor::CodeCompleteNaturalLanguage() {
|
221
|
458 setCodeCompletionReached();
|
150
|
459 if (CodeComplete)
|
|
460 CodeComplete->CodeCompleteNaturalLanguage();
|
|
461 }
|
|
462
|
|
463 /// getSpelling - This method is used to get the spelling of a token into a
|
|
464 /// SmallVector. Note that the returned StringRef may not point to the
|
|
465 /// supplied buffer if a copy can be avoided.
|
|
466 StringRef Preprocessor::getSpelling(const Token &Tok,
|
|
467 SmallVectorImpl<char> &Buffer,
|
|
468 bool *Invalid) const {
|
|
469 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
|
|
470 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
|
|
471 // Try the fast path.
|
|
472 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
|
|
473 return II->getName();
|
|
474 }
|
|
475
|
|
476 // Resize the buffer if we need to copy into it.
|
|
477 if (Tok.needsCleaning())
|
|
478 Buffer.resize(Tok.getLength());
|
|
479
|
|
480 const char *Ptr = Buffer.data();
|
|
481 unsigned Len = getSpelling(Tok, Ptr, Invalid);
|
|
482 return StringRef(Ptr, Len);
|
|
483 }
|
|
484
|
|
485 /// CreateString - Plop the specified string into a scratch buffer and return a
|
|
486 /// location for it. If specified, the source location provides a source
|
|
487 /// location for the token.
|
|
488 void Preprocessor::CreateString(StringRef Str, Token &Tok,
|
|
489 SourceLocation ExpansionLocStart,
|
|
490 SourceLocation ExpansionLocEnd) {
|
|
491 Tok.setLength(Str.size());
|
|
492
|
|
493 const char *DestPtr;
|
|
494 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
|
|
495
|
|
496 if (ExpansionLocStart.isValid())
|
|
497 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
|
|
498 ExpansionLocEnd, Str.size());
|
|
499 Tok.setLocation(Loc);
|
|
500
|
|
501 // If this is a raw identifier or a literal token, set the pointer data.
|
|
502 if (Tok.is(tok::raw_identifier))
|
|
503 Tok.setRawIdentifierData(DestPtr);
|
|
504 else if (Tok.isLiteral())
|
|
505 Tok.setLiteralData(DestPtr);
|
|
506 }
|
|
507
|
|
508 SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
|
|
509 auto &SM = getSourceManager();
|
|
510 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
|
|
511 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
|
|
512 bool Invalid = false;
|
|
513 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
|
|
514 if (Invalid)
|
|
515 return SourceLocation();
|
|
516
|
|
517 // FIXME: We could consider re-using spelling for tokens we see repeatedly.
|
|
518 const char *DestPtr;
|
|
519 SourceLocation Spelling =
|
|
520 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
|
|
521 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
|
|
522 }
|
|
523
|
|
524 Module *Preprocessor::getCurrentModule() {
|
|
525 if (!getLangOpts().isCompilingModule())
|
|
526 return nullptr;
|
|
527
|
|
528 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
|
|
529 }
|
|
530
|
236
|
531 Module *Preprocessor::getCurrentModuleImplementation() {
|
|
532 if (!getLangOpts().isCompilingModuleImplementation())
|
|
533 return nullptr;
|
|
534
|
|
535 return getHeaderSearchInfo().lookupModule(getLangOpts().ModuleName);
|
|
536 }
|
|
537
|
150
|
538 //===----------------------------------------------------------------------===//
|
|
539 // Preprocessor Initialization Methods
|
|
540 //===----------------------------------------------------------------------===//
|
|
541
|
|
542 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
|
|
543 /// which implicitly adds the builtin defines etc.
|
|
544 void Preprocessor::EnterMainSourceFile() {
|
|
545 // We do not allow the preprocessor to reenter the main file. Doing so will
|
|
546 // cause FileID's to accumulate information from both runs (e.g. #line
|
|
547 // information) and predefined macros aren't guaranteed to be set properly.
|
|
548 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
|
|
549 FileID MainFileID = SourceMgr.getMainFileID();
|
|
550
|
|
551 // If MainFileID is loaded it means we loaded an AST file, no need to enter
|
|
552 // a main file.
|
|
553 if (!SourceMgr.isLoadedFileID(MainFileID)) {
|
|
554 // Enter the main file source buffer.
|
|
555 EnterSourceFile(MainFileID, nullptr, SourceLocation());
|
|
556
|
|
557 // If we've been asked to skip bytes in the main file (e.g., as part of a
|
|
558 // precompiled preamble), do so now.
|
|
559 if (SkipMainFilePreamble.first > 0)
|
|
560 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
|
|
561 SkipMainFilePreamble.second);
|
|
562
|
|
563 // Tell the header info that the main file was entered. If the file is later
|
|
564 // #imported, it won't be re-entered.
|
|
565 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
|
236
|
566 markIncluded(FE);
|
150
|
567 }
|
|
568
|
|
569 // Preprocess Predefines to populate the initial preprocessor state.
|
|
570 std::unique_ptr<llvm::MemoryBuffer> SB =
|
|
571 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
|
|
572 assert(SB && "Cannot create predefined source buffer");
|
|
573 FileID FID = SourceMgr.createFileID(std::move(SB));
|
|
574 assert(FID.isValid() && "Could not create FileID for predefines?");
|
|
575 setPredefinesFileID(FID);
|
|
576
|
|
577 // Start parsing the predefines.
|
|
578 EnterSourceFile(FID, nullptr, SourceLocation());
|
|
579
|
|
580 if (!PPOpts->PCHThroughHeader.empty()) {
|
|
581 // Lookup and save the FileID for the through header. If it isn't found
|
|
582 // in the search path, it's a fatal error.
|
|
583 Optional<FileEntryRef> File = LookupFile(
|
|
584 SourceLocation(), PPOpts->PCHThroughHeader,
|
236
|
585 /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr,
|
|
586 /*CurDir=*/nullptr, /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
|
150
|
587 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr,
|
|
588 /*IsFrameworkFound=*/nullptr);
|
|
589 if (!File) {
|
|
590 Diag(SourceLocation(), diag::err_pp_through_header_not_found)
|
|
591 << PPOpts->PCHThroughHeader;
|
|
592 return;
|
|
593 }
|
|
594 setPCHThroughHeaderFileID(
|
|
595 SourceMgr.createFileID(*File, SourceLocation(), SrcMgr::C_User));
|
|
596 }
|
|
597
|
|
598 // Skip tokens from the Predefines and if needed the main file.
|
|
599 if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
|
|
600 (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
|
|
601 SkipTokensWhileUsingPCH();
|
|
602 }
|
|
603
|
|
604 void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
|
|
605 assert(PCHThroughHeaderFileID.isInvalid() &&
|
|
606 "PCHThroughHeaderFileID already set!");
|
|
607 PCHThroughHeaderFileID = FID;
|
|
608 }
|
|
609
|
|
610 bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
|
|
611 assert(PCHThroughHeaderFileID.isValid() &&
|
|
612 "Invalid PCH through header FileID");
|
|
613 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
|
|
614 }
|
|
615
|
|
616 bool Preprocessor::creatingPCHWithThroughHeader() {
|
|
617 return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
|
|
618 PCHThroughHeaderFileID.isValid();
|
|
619 }
|
|
620
|
|
621 bool Preprocessor::usingPCHWithThroughHeader() {
|
|
622 return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
|
|
623 PCHThroughHeaderFileID.isValid();
|
|
624 }
|
|
625
|
|
626 bool Preprocessor::creatingPCHWithPragmaHdrStop() {
|
|
627 return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
|
|
628 }
|
|
629
|
|
630 bool Preprocessor::usingPCHWithPragmaHdrStop() {
|
|
631 return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
|
|
632 }
|
|
633
|
|
634 /// Skip tokens until after the #include of the through header or
|
|
635 /// until after a #pragma hdrstop is seen. Tokens in the predefines file
|
|
636 /// and the main file may be skipped. If the end of the predefines file
|
|
637 /// is reached, skipping continues into the main file. If the end of the
|
|
638 /// main file is reached, it's a fatal error.
|
|
639 void Preprocessor::SkipTokensWhileUsingPCH() {
|
|
640 bool ReachedMainFileEOF = false;
|
|
641 bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
|
|
642 bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
|
|
643 Token Tok;
|
|
644 while (true) {
|
|
645 bool InPredefines =
|
|
646 (CurLexer && CurLexer->getFileID() == getPredefinesFileID());
|
|
647 switch (CurLexerKind) {
|
|
648 case CLK_Lexer:
|
|
649 CurLexer->Lex(Tok);
|
|
650 break;
|
|
651 case CLK_TokenLexer:
|
|
652 CurTokenLexer->Lex(Tok);
|
|
653 break;
|
|
654 case CLK_CachingLexer:
|
|
655 CachingLex(Tok);
|
|
656 break;
|
236
|
657 case CLK_DependencyDirectivesLexer:
|
|
658 CurLexer->LexDependencyDirectiveToken(Tok);
|
|
659 break;
|
150
|
660 case CLK_LexAfterModuleImport:
|
|
661 LexAfterModuleImport(Tok);
|
|
662 break;
|
|
663 }
|
|
664 if (Tok.is(tok::eof) && !InPredefines) {
|
|
665 ReachedMainFileEOF = true;
|
|
666 break;
|
|
667 }
|
|
668 if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
|
|
669 break;
|
|
670 if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
|
|
671 break;
|
|
672 }
|
|
673 if (ReachedMainFileEOF) {
|
|
674 if (UsingPCHThroughHeader)
|
|
675 Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
|
|
676 << PPOpts->PCHThroughHeader << 1;
|
|
677 else if (!PPOpts->PCHWithHdrStopCreate)
|
|
678 Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
|
|
679 }
|
|
680 }
|
|
681
|
|
682 void Preprocessor::replayPreambleConditionalStack() {
|
|
683 // Restore the conditional stack from the preamble, if there is one.
|
|
684 if (PreambleConditionalStack.isReplaying()) {
|
|
685 assert(CurPPLexer &&
|
|
686 "CurPPLexer is null when calling replayPreambleConditionalStack.");
|
|
687 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
|
|
688 PreambleConditionalStack.doneReplaying();
|
|
689 if (PreambleConditionalStack.reachedEOFWhileSkipping())
|
|
690 SkipExcludedConditionalBlock(
|
|
691 PreambleConditionalStack.SkipInfo->HashTokenLoc,
|
|
692 PreambleConditionalStack.SkipInfo->IfTokenLoc,
|
|
693 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
|
|
694 PreambleConditionalStack.SkipInfo->FoundElse,
|
|
695 PreambleConditionalStack.SkipInfo->ElseLoc);
|
|
696 }
|
|
697 }
|
|
698
|
|
699 void Preprocessor::EndSourceFile() {
|
|
700 // Notify the client that we reached the end of the source file.
|
|
701 if (Callbacks)
|
|
702 Callbacks->EndOfMainFile();
|
|
703 }
|
|
704
|
|
705 //===----------------------------------------------------------------------===//
|
|
706 // Lexer Event Handling.
|
|
707 //===----------------------------------------------------------------------===//
|
|
708
|
|
709 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
|
|
710 /// identifier information for the token and install it into the token,
|
|
711 /// updating the token kind accordingly.
|
|
712 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
|
|
713 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
|
|
714
|
|
715 // Look up this token, see if it is a macro, or if it is a language keyword.
|
|
716 IdentifierInfo *II;
|
|
717 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
|
|
718 // No cleaning needed, just use the characters from the lexed buffer.
|
|
719 II = getIdentifierInfo(Identifier.getRawIdentifier());
|
|
720 } else {
|
|
721 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
|
|
722 SmallString<64> IdentifierBuffer;
|
|
723 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
|
|
724
|
|
725 if (Identifier.hasUCN()) {
|
|
726 SmallString<64> UCNIdentifierBuffer;
|
|
727 expandUCNs(UCNIdentifierBuffer, CleanedStr);
|
|
728 II = getIdentifierInfo(UCNIdentifierBuffer);
|
|
729 } else {
|
|
730 II = getIdentifierInfo(CleanedStr);
|
|
731 }
|
|
732 }
|
|
733
|
|
734 // Update the token info (identifier info and appropriate token kind).
|
236
|
735 // FIXME: the raw_identifier may contain leading whitespace which is removed
|
|
736 // from the cleaned identifier token. The SourceLocation should be updated to
|
|
737 // refer to the non-whitespace character. For instance, the text "\\\nB" (a
|
|
738 // line continuation before 'B') is parsed as a single tok::raw_identifier and
|
|
739 // is cleaned to tok::identifier "B". After cleaning the token's length is
|
|
740 // still 3 and the SourceLocation refers to the location of the backslash.
|
150
|
741 Identifier.setIdentifierInfo(II);
|
236
|
742 Identifier.setKind(II->getTokenID());
|
150
|
743
|
|
744 return II;
|
|
745 }
|
|
746
|
|
747 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
|
|
748 PoisonReasons[II] = DiagID;
|
|
749 }
|
|
750
|
|
751 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
|
|
752 assert(Ident__exception_code && Ident__exception_info);
|
|
753 assert(Ident___exception_code && Ident___exception_info);
|
|
754 Ident__exception_code->setIsPoisoned(Poison);
|
|
755 Ident___exception_code->setIsPoisoned(Poison);
|
|
756 Ident_GetExceptionCode->setIsPoisoned(Poison);
|
|
757 Ident__exception_info->setIsPoisoned(Poison);
|
|
758 Ident___exception_info->setIsPoisoned(Poison);
|
|
759 Ident_GetExceptionInfo->setIsPoisoned(Poison);
|
|
760 Ident__abnormal_termination->setIsPoisoned(Poison);
|
|
761 Ident___abnormal_termination->setIsPoisoned(Poison);
|
|
762 Ident_AbnormalTermination->setIsPoisoned(Poison);
|
|
763 }
|
|
764
|
|
765 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
|
|
766 assert(Identifier.getIdentifierInfo() &&
|
|
767 "Can't handle identifiers without identifier info!");
|
|
768 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
|
|
769 PoisonReasons.find(Identifier.getIdentifierInfo());
|
|
770 if(it == PoisonReasons.end())
|
|
771 Diag(Identifier, diag::err_pp_used_poisoned_id);
|
|
772 else
|
|
773 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
|
|
774 }
|
|
775
|
|
776 void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
|
|
777 assert(II.isOutOfDate() && "not out of date");
|
|
778 getExternalSource()->updateOutOfDateIdentifier(II);
|
|
779 }
|
|
780
|
|
781 /// HandleIdentifier - This callback is invoked when the lexer reads an
|
|
782 /// identifier. This callback looks up the identifier in the map and/or
|
|
783 /// potentially macro expands it or turns it into a named token (like 'for').
|
|
784 ///
|
|
785 /// Note that callers of this method are guarded by checking the
|
|
786 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
|
|
787 /// IdentifierInfo methods that compute these properties will need to change to
|
|
788 /// match.
|
|
789 bool Preprocessor::HandleIdentifier(Token &Identifier) {
|
|
790 assert(Identifier.getIdentifierInfo() &&
|
|
791 "Can't handle identifiers without identifier info!");
|
|
792
|
|
793 IdentifierInfo &II = *Identifier.getIdentifierInfo();
|
|
794
|
|
795 // If the information about this identifier is out of date, update it from
|
|
796 // the external source.
|
|
797 // We have to treat __VA_ARGS__ in a special way, since it gets
|
|
798 // serialized with isPoisoned = true, but our preprocessor may have
|
|
799 // unpoisoned it if we're defining a C99 macro.
|
|
800 if (II.isOutOfDate()) {
|
|
801 bool CurrentIsPoisoned = false;
|
|
802 const bool IsSpecialVariadicMacro =
|
|
803 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
|
|
804 if (IsSpecialVariadicMacro)
|
|
805 CurrentIsPoisoned = II.isPoisoned();
|
|
806
|
|
807 updateOutOfDateIdentifier(II);
|
|
808 Identifier.setKind(II.getTokenID());
|
|
809
|
|
810 if (IsSpecialVariadicMacro)
|
|
811 II.setIsPoisoned(CurrentIsPoisoned);
|
|
812 }
|
|
813
|
|
814 // If this identifier was poisoned, and if it was not produced from a macro
|
|
815 // expansion, emit an error.
|
|
816 if (II.isPoisoned() && CurPPLexer) {
|
|
817 HandlePoisonedIdentifier(Identifier);
|
|
818 }
|
|
819
|
|
820 // If this is a macro to be expanded, do it.
|
|
821 if (MacroDefinition MD = getMacroDefinition(&II)) {
|
|
822 auto *MI = MD.getMacroInfo();
|
|
823 assert(MI && "macro definition with no macro info?");
|
|
824 if (!DisableMacroExpansion) {
|
|
825 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
|
|
826 // C99 6.10.3p10: If the preprocessing token immediately after the
|
|
827 // macro name isn't a '(', this macro should not be expanded.
|
|
828 if (!MI->isFunctionLike() || isNextPPTokenLParen())
|
|
829 return HandleMacroExpandedIdentifier(Identifier, MD);
|
|
830 } else {
|
|
831 // C99 6.10.3.4p2 says that a disabled macro may never again be
|
|
832 // expanded, even if it's in a context where it could be expanded in the
|
|
833 // future.
|
|
834 Identifier.setFlag(Token::DisableExpand);
|
|
835 if (MI->isObjectLike() || isNextPPTokenLParen())
|
|
836 Diag(Identifier, diag::pp_disabled_macro_expansion);
|
|
837 }
|
|
838 }
|
|
839 }
|
|
840
|
|
841 // If this identifier is a keyword in a newer Standard or proposed Standard,
|
|
842 // produce a warning. Don't warn if we're not considering macro expansion,
|
|
843 // since this identifier might be the name of a macro.
|
|
844 // FIXME: This warning is disabled in cases where it shouldn't be, like
|
|
845 // "#define constexpr constexpr", "int constexpr;"
|
|
846 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
|
236
|
847 Diag(Identifier, getIdentifierTable().getFutureCompatDiagKind(II, getLangOpts()))
|
150
|
848 << II.getName();
|
|
849 // Don't diagnose this keyword again in this translation unit.
|
|
850 II.setIsFutureCompatKeyword(false);
|
|
851 }
|
|
852
|
|
853 // If this is an extension token, diagnose its use.
|
|
854 // We avoid diagnosing tokens that originate from macro definitions.
|
|
855 // FIXME: This warning is disabled in cases where it shouldn't be,
|
|
856 // like "#define TY typeof", "TY(1) x".
|
|
857 if (II.isExtensionToken() && !DisableMacroExpansion)
|
|
858 Diag(Identifier, diag::ext_token_used);
|
|
859
|
|
860 // If this is the 'import' contextual keyword following an '@', note
|
|
861 // that the next token indicates a module name.
|
|
862 //
|
|
863 // Note that we do not treat 'import' as a contextual
|
|
864 // keyword when we're in a caching lexer, because caching lexers only get
|
|
865 // used in contexts where import declarations are disallowed.
|
|
866 //
|
|
867 // Likewise if this is the C++ Modules TS import keyword.
|
|
868 if (((LastTokenWasAt && II.isModulesImport()) ||
|
|
869 Identifier.is(tok::kw_import)) &&
|
|
870 !InMacroArgs && !DisableMacroExpansion &&
|
|
871 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
|
|
872 CurLexerKind != CLK_CachingLexer) {
|
|
873 ModuleImportLoc = Identifier.getLocation();
|
236
|
874 NamedModuleImportPath.clear();
|
150
|
875 ModuleImportExpectsIdentifier = true;
|
|
876 CurLexerKind = CLK_LexAfterModuleImport;
|
|
877 }
|
|
878 return true;
|
|
879 }
|
|
880
|
|
881 void Preprocessor::Lex(Token &Result) {
|
|
882 ++LexLevel;
|
|
883
|
|
884 // We loop here until a lex function returns a token; this avoids recursion.
|
|
885 bool ReturnedToken;
|
|
886 do {
|
|
887 switch (CurLexerKind) {
|
|
888 case CLK_Lexer:
|
|
889 ReturnedToken = CurLexer->Lex(Result);
|
|
890 break;
|
|
891 case CLK_TokenLexer:
|
|
892 ReturnedToken = CurTokenLexer->Lex(Result);
|
|
893 break;
|
|
894 case CLK_CachingLexer:
|
|
895 CachingLex(Result);
|
|
896 ReturnedToken = true;
|
|
897 break;
|
236
|
898 case CLK_DependencyDirectivesLexer:
|
|
899 ReturnedToken = CurLexer->LexDependencyDirectiveToken(Result);
|
|
900 break;
|
150
|
901 case CLK_LexAfterModuleImport:
|
|
902 ReturnedToken = LexAfterModuleImport(Result);
|
|
903 break;
|
|
904 }
|
|
905 } while (!ReturnedToken);
|
|
906
|
|
907 if (Result.is(tok::unknown) && TheModuleLoader.HadFatalFailure)
|
|
908 return;
|
|
909
|
|
910 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
|
|
911 // Remember the identifier before code completion token.
|
|
912 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
|
|
913 setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
|
|
914 // Set IdenfitierInfo to null to avoid confusing code that handles both
|
|
915 // identifiers and completion tokens.
|
|
916 Result.setIdentifierInfo(nullptr);
|
|
917 }
|
|
918
|
236
|
919 // Update StdCXXImportSeqState to track our position within a C++20 import-seq
|
150
|
920 // if this token is being produced as a result of phase 4 of translation.
|
236
|
921 // Update TrackGMFState to decide if we are currently in a Global Module
|
|
922 // Fragment. GMF state updates should precede StdCXXImportSeq ones, since GMF state
|
|
923 // depends on the prevailing StdCXXImportSeq state in two cases.
|
150
|
924 if (getLangOpts().CPlusPlusModules && LexLevel == 1 &&
|
|
925 !Result.getFlag(Token::IsReinjected)) {
|
|
926 switch (Result.getKind()) {
|
|
927 case tok::l_paren: case tok::l_square: case tok::l_brace:
|
236
|
928 StdCXXImportSeqState.handleOpenBracket();
|
150
|
929 break;
|
|
930 case tok::r_paren: case tok::r_square:
|
236
|
931 StdCXXImportSeqState.handleCloseBracket();
|
150
|
932 break;
|
|
933 case tok::r_brace:
|
236
|
934 StdCXXImportSeqState.handleCloseBrace();
|
150
|
935 break;
|
236
|
936 // This token is injected to represent the translation of '#include "a.h"'
|
|
937 // into "import a.h;". Mimic the notional ';'.
|
|
938 case tok::annot_module_include:
|
150
|
939 case tok::semi:
|
236
|
940 TrackGMFState.handleSemi();
|
|
941 StdCXXImportSeqState.handleSemi();
|
150
|
942 break;
|
|
943 case tok::header_name:
|
|
944 case tok::annot_header_unit:
|
236
|
945 StdCXXImportSeqState.handleHeaderName();
|
150
|
946 break;
|
|
947 case tok::kw_export:
|
236
|
948 TrackGMFState.handleExport();
|
|
949 StdCXXImportSeqState.handleExport();
|
150
|
950 break;
|
|
951 case tok::identifier:
|
|
952 if (Result.getIdentifierInfo()->isModulesImport()) {
|
236
|
953 TrackGMFState.handleImport(StdCXXImportSeqState.afterTopLevelSeq());
|
|
954 StdCXXImportSeqState.handleImport();
|
|
955 if (StdCXXImportSeqState.afterImportSeq()) {
|
150
|
956 ModuleImportLoc = Result.getLocation();
|
236
|
957 NamedModuleImportPath.clear();
|
150
|
958 ModuleImportExpectsIdentifier = true;
|
|
959 CurLexerKind = CLK_LexAfterModuleImport;
|
|
960 }
|
|
961 break;
|
236
|
962 } else if (Result.getIdentifierInfo() == getIdentifierInfo("module")) {
|
|
963 TrackGMFState.handleModule(StdCXXImportSeqState.afterTopLevelSeq());
|
|
964 break;
|
150
|
965 }
|
236
|
966 [[fallthrough]];
|
150
|
967 default:
|
236
|
968 TrackGMFState.handleMisc();
|
|
969 StdCXXImportSeqState.handleMisc();
|
150
|
970 break;
|
|
971 }
|
|
972 }
|
|
973
|
|
974 LastTokenWasAt = Result.is(tok::at);
|
|
975 --LexLevel;
|
|
976
|
221
|
977 if ((LexLevel == 0 || PreprocessToken) &&
|
|
978 !Result.getFlag(Token::IsReinjected)) {
|
|
979 if (LexLevel == 0)
|
|
980 ++TokenCount;
|
150
|
981 if (OnToken)
|
|
982 OnToken(Result);
|
|
983 }
|
|
984 }
|
|
985
|
|
986 /// Lex a header-name token (including one formed from header-name-tokens if
|
|
987 /// \p AllowConcatenation is \c true).
|
|
988 ///
|
|
989 /// \param FilenameTok Filled in with the next token. On success, this will
|
|
990 /// be either a header_name token. On failure, it will be whatever other
|
|
991 /// token was found instead.
|
|
992 /// \param AllowMacroExpansion If \c true, allow the header name to be formed
|
|
993 /// by macro expansion (concatenating tokens as necessary if the first
|
|
994 /// token is a '<').
|
|
995 /// \return \c true if we reached EOD or EOF while looking for a > token in
|
|
996 /// a concatenated header name and diagnosed it. \c false otherwise.
|
|
997 bool Preprocessor::LexHeaderName(Token &FilenameTok, bool AllowMacroExpansion) {
|
|
998 // Lex using header-name tokenization rules if tokens are being lexed from
|
|
999 // a file. Just grab a token normally if we're in a macro expansion.
|
|
1000 if (CurPPLexer)
|
|
1001 CurPPLexer->LexIncludeFilename(FilenameTok);
|
|
1002 else
|
|
1003 Lex(FilenameTok);
|
|
1004
|
|
1005 // This could be a <foo/bar.h> file coming from a macro expansion. In this
|
|
1006 // case, glue the tokens together into an angle_string_literal token.
|
|
1007 SmallString<128> FilenameBuffer;
|
|
1008 if (FilenameTok.is(tok::less) && AllowMacroExpansion) {
|
|
1009 bool StartOfLine = FilenameTok.isAtStartOfLine();
|
|
1010 bool LeadingSpace = FilenameTok.hasLeadingSpace();
|
|
1011 bool LeadingEmptyMacro = FilenameTok.hasLeadingEmptyMacro();
|
|
1012
|
|
1013 SourceLocation Start = FilenameTok.getLocation();
|
|
1014 SourceLocation End;
|
|
1015 FilenameBuffer.push_back('<');
|
|
1016
|
|
1017 // Consume tokens until we find a '>'.
|
|
1018 // FIXME: A header-name could be formed starting or ending with an
|
|
1019 // alternative token. It's not clear whether that's ill-formed in all
|
|
1020 // cases.
|
|
1021 while (FilenameTok.isNot(tok::greater)) {
|
|
1022 Lex(FilenameTok);
|
|
1023 if (FilenameTok.isOneOf(tok::eod, tok::eof)) {
|
|
1024 Diag(FilenameTok.getLocation(), diag::err_expected) << tok::greater;
|
|
1025 Diag(Start, diag::note_matching) << tok::less;
|
|
1026 return true;
|
|
1027 }
|
|
1028
|
|
1029 End = FilenameTok.getLocation();
|
|
1030
|
|
1031 // FIXME: Provide code completion for #includes.
|
|
1032 if (FilenameTok.is(tok::code_completion)) {
|
|
1033 setCodeCompletionReached();
|
|
1034 Lex(FilenameTok);
|
|
1035 continue;
|
|
1036 }
|
|
1037
|
|
1038 // Append the spelling of this token to the buffer. If there was a space
|
|
1039 // before it, add it now.
|
|
1040 if (FilenameTok.hasLeadingSpace())
|
|
1041 FilenameBuffer.push_back(' ');
|
|
1042
|
|
1043 // Get the spelling of the token, directly into FilenameBuffer if
|
|
1044 // possible.
|
|
1045 size_t PreAppendSize = FilenameBuffer.size();
|
|
1046 FilenameBuffer.resize(PreAppendSize + FilenameTok.getLength());
|
|
1047
|
|
1048 const char *BufPtr = &FilenameBuffer[PreAppendSize];
|
|
1049 unsigned ActualLen = getSpelling(FilenameTok, BufPtr);
|
|
1050
|
|
1051 // If the token was spelled somewhere else, copy it into FilenameBuffer.
|
|
1052 if (BufPtr != &FilenameBuffer[PreAppendSize])
|
|
1053 memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
|
|
1054
|
|
1055 // Resize FilenameBuffer to the correct size.
|
|
1056 if (FilenameTok.getLength() != ActualLen)
|
|
1057 FilenameBuffer.resize(PreAppendSize + ActualLen);
|
|
1058 }
|
|
1059
|
|
1060 FilenameTok.startToken();
|
|
1061 FilenameTok.setKind(tok::header_name);
|
|
1062 FilenameTok.setFlagValue(Token::StartOfLine, StartOfLine);
|
|
1063 FilenameTok.setFlagValue(Token::LeadingSpace, LeadingSpace);
|
|
1064 FilenameTok.setFlagValue(Token::LeadingEmptyMacro, LeadingEmptyMacro);
|
|
1065 CreateString(FilenameBuffer, FilenameTok, Start, End);
|
|
1066 } else if (FilenameTok.is(tok::string_literal) && AllowMacroExpansion) {
|
|
1067 // Convert a string-literal token of the form " h-char-sequence "
|
|
1068 // (produced by macro expansion) into a header-name token.
|
|
1069 //
|
|
1070 // The rules for header-names don't quite match the rules for
|
|
1071 // string-literals, but all the places where they differ result in
|
|
1072 // undefined behavior, so we can and do treat them the same.
|
|
1073 //
|
|
1074 // A string-literal with a prefix or suffix is not translated into a
|
|
1075 // header-name. This could theoretically be observable via the C++20
|
|
1076 // context-sensitive header-name formation rules.
|
|
1077 StringRef Str = getSpelling(FilenameTok, FilenameBuffer);
|
|
1078 if (Str.size() >= 2 && Str.front() == '"' && Str.back() == '"')
|
|
1079 FilenameTok.setKind(tok::header_name);
|
|
1080 }
|
|
1081
|
|
1082 return false;
|
|
1083 }
|
|
1084
|
|
1085 /// Collect the tokens of a C++20 pp-import-suffix.
|
|
1086 void Preprocessor::CollectPpImportSuffix(SmallVectorImpl<Token> &Toks) {
|
|
1087 // FIXME: For error recovery, consider recognizing attribute syntax here
|
|
1088 // and terminating / diagnosing a missing semicolon if we find anything
|
|
1089 // else? (Can we leave that to the parser?)
|
|
1090 unsigned BracketDepth = 0;
|
|
1091 while (true) {
|
|
1092 Toks.emplace_back();
|
|
1093 Lex(Toks.back());
|
|
1094
|
|
1095 switch (Toks.back().getKind()) {
|
|
1096 case tok::l_paren: case tok::l_square: case tok::l_brace:
|
|
1097 ++BracketDepth;
|
|
1098 break;
|
|
1099
|
|
1100 case tok::r_paren: case tok::r_square: case tok::r_brace:
|
|
1101 if (BracketDepth == 0)
|
|
1102 return;
|
|
1103 --BracketDepth;
|
|
1104 break;
|
|
1105
|
|
1106 case tok::semi:
|
|
1107 if (BracketDepth == 0)
|
|
1108 return;
|
|
1109 break;
|
|
1110
|
|
1111 case tok::eof:
|
|
1112 return;
|
|
1113
|
|
1114 default:
|
|
1115 break;
|
|
1116 }
|
|
1117 }
|
|
1118 }
|
|
1119
|
|
1120
|
|
1121 /// Lex a token following the 'import' contextual keyword.
|
|
1122 ///
|
|
1123 /// pp-import: [C++20]
|
|
1124 /// import header-name pp-import-suffix[opt] ;
|
|
1125 /// import header-name-tokens pp-import-suffix[opt] ;
|
|
1126 /// [ObjC] @ import module-name ;
|
|
1127 /// [Clang] import module-name ;
|
|
1128 ///
|
|
1129 /// header-name-tokens:
|
|
1130 /// string-literal
|
|
1131 /// < [any sequence of preprocessing-tokens other than >] >
|
|
1132 ///
|
|
1133 /// module-name:
|
|
1134 /// module-name-qualifier[opt] identifier
|
|
1135 ///
|
|
1136 /// module-name-qualifier
|
|
1137 /// module-name-qualifier[opt] identifier .
|
|
1138 ///
|
|
1139 /// We respond to a pp-import by importing macros from the named module.
|
|
1140 bool Preprocessor::LexAfterModuleImport(Token &Result) {
|
|
1141 // Figure out what kind of lexer we actually have.
|
|
1142 recomputeCurLexerKind();
|
|
1143
|
|
1144 // Lex the next token. The header-name lexing rules are used at the start of
|
|
1145 // a pp-import.
|
|
1146 //
|
|
1147 // For now, we only support header-name imports in C++20 mode.
|
|
1148 // FIXME: Should we allow this in all language modes that support an import
|
|
1149 // declaration as an extension?
|
236
|
1150 if (NamedModuleImportPath.empty() && getLangOpts().CPlusPlusModules) {
|
150
|
1151 if (LexHeaderName(Result))
|
|
1152 return true;
|
|
1153 } else {
|
|
1154 Lex(Result);
|
|
1155 }
|
|
1156
|
|
1157 // Allocate a holding buffer for a sequence of tokens and introduce it into
|
|
1158 // the token stream.
|
|
1159 auto EnterTokens = [this](ArrayRef<Token> Toks) {
|
|
1160 auto ToksCopy = std::make_unique<Token[]>(Toks.size());
|
|
1161 std::copy(Toks.begin(), Toks.end(), ToksCopy.get());
|
|
1162 EnterTokenStream(std::move(ToksCopy), Toks.size(),
|
|
1163 /*DisableMacroExpansion*/ true, /*IsReinject*/ false);
|
|
1164 };
|
|
1165
|
|
1166 // Check for a header-name.
|
|
1167 SmallVector<Token, 32> Suffix;
|
|
1168 if (Result.is(tok::header_name)) {
|
|
1169 // Enter the header-name token into the token stream; a Lex action cannot
|
|
1170 // both return a token and cache tokens (doing so would corrupt the token
|
|
1171 // cache if the call to Lex comes from CachingLex / PeekAhead).
|
|
1172 Suffix.push_back(Result);
|
|
1173
|
|
1174 // Consume the pp-import-suffix and expand any macros in it now. We'll add
|
|
1175 // it back into the token stream later.
|
|
1176 CollectPpImportSuffix(Suffix);
|
|
1177 if (Suffix.back().isNot(tok::semi)) {
|
|
1178 // This is not a pp-import after all.
|
|
1179 EnterTokens(Suffix);
|
|
1180 return false;
|
|
1181 }
|
|
1182
|
|
1183 // C++2a [cpp.module]p1:
|
|
1184 // The ';' preprocessing-token terminating a pp-import shall not have
|
|
1185 // been produced by macro replacement.
|
|
1186 SourceLocation SemiLoc = Suffix.back().getLocation();
|
|
1187 if (SemiLoc.isMacroID())
|
|
1188 Diag(SemiLoc, diag::err_header_import_semi_in_macro);
|
|
1189
|
|
1190 // Reconstitute the import token.
|
|
1191 Token ImportTok;
|
|
1192 ImportTok.startToken();
|
|
1193 ImportTok.setKind(tok::kw_import);
|
|
1194 ImportTok.setLocation(ModuleImportLoc);
|
|
1195 ImportTok.setIdentifierInfo(getIdentifierInfo("import"));
|
|
1196 ImportTok.setLength(6);
|
|
1197
|
|
1198 auto Action = HandleHeaderIncludeOrImport(
|
|
1199 /*HashLoc*/ SourceLocation(), ImportTok, Suffix.front(), SemiLoc);
|
|
1200 switch (Action.Kind) {
|
|
1201 case ImportAction::None:
|
|
1202 break;
|
|
1203
|
|
1204 case ImportAction::ModuleBegin:
|
|
1205 // Let the parser know we're textually entering the module.
|
|
1206 Suffix.emplace_back();
|
|
1207 Suffix.back().startToken();
|
|
1208 Suffix.back().setKind(tok::annot_module_begin);
|
|
1209 Suffix.back().setLocation(SemiLoc);
|
|
1210 Suffix.back().setAnnotationEndLoc(SemiLoc);
|
|
1211 Suffix.back().setAnnotationValue(Action.ModuleForHeader);
|
236
|
1212 [[fallthrough]];
|
150
|
1213
|
|
1214 case ImportAction::ModuleImport:
|
236
|
1215 case ImportAction::HeaderUnitImport:
|
150
|
1216 case ImportAction::SkippedModuleImport:
|
|
1217 // We chose to import (or textually enter) the file. Convert the
|
|
1218 // header-name token into a header unit annotation token.
|
|
1219 Suffix[0].setKind(tok::annot_header_unit);
|
|
1220 Suffix[0].setAnnotationEndLoc(Suffix[0].getLocation());
|
|
1221 Suffix[0].setAnnotationValue(Action.ModuleForHeader);
|
|
1222 // FIXME: Call the moduleImport callback?
|
|
1223 break;
|
|
1224 case ImportAction::Failure:
|
|
1225 assert(TheModuleLoader.HadFatalFailure &&
|
|
1226 "This should be an early exit only to a fatal error");
|
|
1227 Result.setKind(tok::eof);
|
|
1228 CurLexer->cutOffLexing();
|
|
1229 EnterTokens(Suffix);
|
|
1230 return true;
|
|
1231 }
|
|
1232
|
|
1233 EnterTokens(Suffix);
|
|
1234 return false;
|
|
1235 }
|
|
1236
|
|
1237 // The token sequence
|
|
1238 //
|
|
1239 // import identifier (. identifier)*
|
|
1240 //
|
|
1241 // indicates a module import directive. We already saw the 'import'
|
|
1242 // contextual keyword, so now we're looking for the identifiers.
|
|
1243 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
|
|
1244 // We expected to see an identifier here, and we did; continue handling
|
|
1245 // identifiers.
|
236
|
1246 NamedModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
|
150
|
1247 Result.getLocation()));
|
|
1248 ModuleImportExpectsIdentifier = false;
|
|
1249 CurLexerKind = CLK_LexAfterModuleImport;
|
|
1250 return true;
|
|
1251 }
|
|
1252
|
|
1253 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
|
|
1254 // see the next identifier. (We can also see a '[[' that begins an
|
|
1255 // attribute-specifier-seq here under the C++ Modules TS.)
|
|
1256 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
|
|
1257 ModuleImportExpectsIdentifier = true;
|
|
1258 CurLexerKind = CLK_LexAfterModuleImport;
|
|
1259 return true;
|
|
1260 }
|
|
1261
|
|
1262 // If we didn't recognize a module name at all, this is not a (valid) import.
|
236
|
1263 if (NamedModuleImportPath.empty() || Result.is(tok::eof))
|
150
|
1264 return true;
|
|
1265
|
|
1266 // Consume the pp-import-suffix and expand any macros in it now, if we're not
|
|
1267 // at the semicolon already.
|
|
1268 SourceLocation SemiLoc = Result.getLocation();
|
|
1269 if (Result.isNot(tok::semi)) {
|
|
1270 Suffix.push_back(Result);
|
|
1271 CollectPpImportSuffix(Suffix);
|
|
1272 if (Suffix.back().isNot(tok::semi)) {
|
|
1273 // This is not an import after all.
|
|
1274 EnterTokens(Suffix);
|
|
1275 return false;
|
|
1276 }
|
|
1277 SemiLoc = Suffix.back().getLocation();
|
|
1278 }
|
|
1279
|
|
1280 // Under the Modules TS, the dot is just part of the module name, and not
|
|
1281 // a real hierarchy separator. Flatten such module names now.
|
|
1282 //
|
|
1283 // FIXME: Is this the right level to be performing this transformation?
|
|
1284 std::string FlatModuleName;
|
|
1285 if (getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) {
|
236
|
1286 for (auto &Piece : NamedModuleImportPath) {
|
150
|
1287 if (!FlatModuleName.empty())
|
|
1288 FlatModuleName += ".";
|
|
1289 FlatModuleName += Piece.first->getName();
|
|
1290 }
|
236
|
1291 SourceLocation FirstPathLoc = NamedModuleImportPath[0].second;
|
|
1292 NamedModuleImportPath.clear();
|
|
1293 NamedModuleImportPath.push_back(
|
150
|
1294 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
|
|
1295 }
|
|
1296
|
|
1297 Module *Imported = nullptr;
|
|
1298 if (getLangOpts().Modules) {
|
|
1299 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
|
236
|
1300 NamedModuleImportPath,
|
150
|
1301 Module::Hidden,
|
|
1302 /*IsInclusionDirective=*/false);
|
|
1303 if (Imported)
|
|
1304 makeModuleVisible(Imported, SemiLoc);
|
|
1305 }
|
|
1306 if (Callbacks)
|
236
|
1307 Callbacks->moduleImport(ModuleImportLoc, NamedModuleImportPath, Imported);
|
150
|
1308
|
|
1309 if (!Suffix.empty()) {
|
|
1310 EnterTokens(Suffix);
|
|
1311 return false;
|
|
1312 }
|
|
1313 return true;
|
|
1314 }
|
|
1315
|
|
1316 void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
|
|
1317 CurSubmoduleState->VisibleModules.setVisible(
|
|
1318 M, Loc, [](Module *) {},
|
|
1319 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
|
|
1320 // FIXME: Include the path in the diagnostic.
|
|
1321 // FIXME: Include the import location for the conflicting module.
|
|
1322 Diag(ModuleImportLoc, diag::warn_module_conflict)
|
|
1323 << Path[0]->getFullModuleName()
|
|
1324 << Conflict->getFullModuleName()
|
|
1325 << Message;
|
|
1326 });
|
|
1327
|
|
1328 // Add this module to the imports list of the currently-built submodule.
|
|
1329 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
|
|
1330 BuildingSubmoduleStack.back().M->Imports.insert(M);
|
|
1331 }
|
|
1332
|
|
1333 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
|
|
1334 const char *DiagnosticTag,
|
|
1335 bool AllowMacroExpansion) {
|
|
1336 // We need at least one string literal.
|
|
1337 if (Result.isNot(tok::string_literal)) {
|
|
1338 Diag(Result, diag::err_expected_string_literal)
|
|
1339 << /*Source='in...'*/0 << DiagnosticTag;
|
|
1340 return false;
|
|
1341 }
|
|
1342
|
|
1343 // Lex string literal tokens, optionally with macro expansion.
|
|
1344 SmallVector<Token, 4> StrToks;
|
|
1345 do {
|
|
1346 StrToks.push_back(Result);
|
|
1347
|
|
1348 if (Result.hasUDSuffix())
|
|
1349 Diag(Result, diag::err_invalid_string_udl);
|
|
1350
|
|
1351 if (AllowMacroExpansion)
|
|
1352 Lex(Result);
|
|
1353 else
|
|
1354 LexUnexpandedToken(Result);
|
|
1355 } while (Result.is(tok::string_literal));
|
|
1356
|
|
1357 // Concatenate and parse the strings.
|
|
1358 StringLiteralParser Literal(StrToks, *this);
|
236
|
1359 assert(Literal.isOrdinary() && "Didn't allow wide strings in");
|
150
|
1360
|
|
1361 if (Literal.hadError)
|
|
1362 return false;
|
|
1363
|
|
1364 if (Literal.Pascal) {
|
|
1365 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
|
|
1366 << /*Source='in...'*/0 << DiagnosticTag;
|
|
1367 return false;
|
|
1368 }
|
|
1369
|
|
1370 String = std::string(Literal.GetString());
|
|
1371 return true;
|
|
1372 }
|
|
1373
|
|
1374 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
|
|
1375 assert(Tok.is(tok::numeric_constant));
|
|
1376 SmallString<8> IntegerBuffer;
|
|
1377 bool NumberInvalid = false;
|
|
1378 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
|
|
1379 if (NumberInvalid)
|
|
1380 return false;
|
221
|
1381 NumericLiteralParser Literal(Spelling, Tok.getLocation(), getSourceManager(),
|
|
1382 getLangOpts(), getTargetInfo(),
|
|
1383 getDiagnostics());
|
150
|
1384 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
|
|
1385 return false;
|
|
1386 llvm::APInt APVal(64, 0);
|
|
1387 if (Literal.GetIntegerValue(APVal))
|
|
1388 return false;
|
|
1389 Lex(Tok);
|
|
1390 Value = APVal.getLimitedValue();
|
|
1391 return true;
|
|
1392 }
|
|
1393
|
|
1394 void Preprocessor::addCommentHandler(CommentHandler *Handler) {
|
|
1395 assert(Handler && "NULL comment handler");
|
236
|
1396 assert(!llvm::is_contained(CommentHandlers, Handler) &&
|
150
|
1397 "Comment handler already registered");
|
|
1398 CommentHandlers.push_back(Handler);
|
|
1399 }
|
|
1400
|
|
1401 void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
|
|
1402 std::vector<CommentHandler *>::iterator Pos =
|
|
1403 llvm::find(CommentHandlers, Handler);
|
|
1404 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
|
|
1405 CommentHandlers.erase(Pos);
|
|
1406 }
|
|
1407
|
|
1408 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
|
|
1409 bool AnyPendingTokens = false;
|
|
1410 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
|
|
1411 HEnd = CommentHandlers.end();
|
|
1412 H != HEnd; ++H) {
|
|
1413 if ((*H)->HandleComment(*this, Comment))
|
|
1414 AnyPendingTokens = true;
|
|
1415 }
|
|
1416 if (!AnyPendingTokens || getCommentRetentionState())
|
|
1417 return false;
|
|
1418 Lex(result);
|
|
1419 return true;
|
|
1420 }
|
|
1421
|
236
|
1422 void Preprocessor::emitMacroDeprecationWarning(const Token &Identifier) const {
|
|
1423 const MacroAnnotations &A =
|
|
1424 getMacroAnnotations(Identifier.getIdentifierInfo());
|
|
1425 assert(A.DeprecationInfo &&
|
|
1426 "Macro deprecation warning without recorded annotation!");
|
|
1427 const MacroAnnotationInfo &Info = *A.DeprecationInfo;
|
|
1428 if (Info.Message.empty())
|
|
1429 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
|
|
1430 << Identifier.getIdentifierInfo() << 0;
|
|
1431 else
|
|
1432 Diag(Identifier, diag::warn_pragma_deprecated_macro_use)
|
|
1433 << Identifier.getIdentifierInfo() << 1 << Info.Message;
|
|
1434 Diag(Info.Location, diag::note_pp_macro_annotation) << 0;
|
|
1435 }
|
|
1436
|
|
1437 void Preprocessor::emitRestrictExpansionWarning(const Token &Identifier) const {
|
|
1438 const MacroAnnotations &A =
|
|
1439 getMacroAnnotations(Identifier.getIdentifierInfo());
|
|
1440 assert(A.RestrictExpansionInfo &&
|
|
1441 "Macro restricted expansion warning without recorded annotation!");
|
|
1442 const MacroAnnotationInfo &Info = *A.RestrictExpansionInfo;
|
|
1443 if (Info.Message.empty())
|
|
1444 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
|
|
1445 << Identifier.getIdentifierInfo() << 0;
|
|
1446 else
|
|
1447 Diag(Identifier, diag::warn_pragma_restrict_expansion_macro_use)
|
|
1448 << Identifier.getIdentifierInfo() << 1 << Info.Message;
|
|
1449 Diag(Info.Location, diag::note_pp_macro_annotation) << 1;
|
|
1450 }
|
|
1451
|
|
1452 void Preprocessor::emitFinalMacroWarning(const Token &Identifier,
|
|
1453 bool IsUndef) const {
|
|
1454 const MacroAnnotations &A =
|
|
1455 getMacroAnnotations(Identifier.getIdentifierInfo());
|
|
1456 assert(A.FinalAnnotationLoc &&
|
|
1457 "Final macro warning without recorded annotation!");
|
|
1458
|
|
1459 Diag(Identifier, diag::warn_pragma_final_macro)
|
|
1460 << Identifier.getIdentifierInfo() << (IsUndef ? 0 : 1);
|
|
1461 Diag(*A.FinalAnnotationLoc, diag::note_pp_macro_annotation) << 2;
|
|
1462 }
|
|
1463
|
150
|
1464 ModuleLoader::~ModuleLoader() = default;
|
|
1465
|
|
1466 CommentHandler::~CommentHandler() = default;
|
|
1467
|
221
|
1468 EmptylineHandler::~EmptylineHandler() = default;
|
|
1469
|
150
|
1470 CodeCompletionHandler::~CodeCompletionHandler() = default;
|
|
1471
|
|
1472 void Preprocessor::createPreprocessingRecord() {
|
|
1473 if (Record)
|
|
1474 return;
|
|
1475
|
|
1476 Record = new PreprocessingRecord(getSourceManager());
|
|
1477 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
|
|
1478 }
|