annotate clang/lib/Lex/Preprocessor.cpp @ 199:5784c86f13b3

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