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