clang 22.0.0git
IncrementalParser.cpp
Go to the documentation of this file.
1//===--------- IncrementalParser.cpp - Incremental Compilation -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the class which performs incremental code compilation.
10//
11//===----------------------------------------------------------------------===//
12
13#include "IncrementalParser.h"
14#include "IncrementalAction.h"
15
19#include "clang/Parse/Parser.h"
20#include "clang/Sema/Sema.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Support/CrashRecoveryContext.h"
23#include "llvm/Support/Error.h"
24
25#include <sstream>
26
27#define DEBUG_TYPE "clang-repl"
28
29namespace clang {
30
31// IncrementalParser::IncrementalParser() {}
32
34 IncrementalAction *Act, llvm::Error &Err,
35 std::list<PartialTranslationUnit> &PTUs)
36 : S(Instance.getSema()), Act(Act), PTUs(PTUs) {
37 llvm::ErrorAsOutParameter EAO(&Err);
39 P.reset(new Parser(S.getPreprocessor(), S, /*SkipBodies=*/false));
40 P->Initialize();
41}
42
44
46IncrementalParser::ParseOrWrapTopLevelDecl() {
47 // Recover resources if we crash before exiting this method.
48 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(&S);
49 Sema::GlobalEagerInstantiationScope GlobalInstantiations(S, /*Enabled=*/true,
50 /*AtEndOfTU=*/true);
51 Sema::LocalEagerInstantiationScope LocalInstantiations(S, /*AtEndOfTU=*/true);
52
53 // Add a new PTU.
55 C.addTranslationUnitDecl();
56
57 // Skip previous eof due to last incremental input.
58 if (P->getCurToken().is(tok::annot_repl_input_end)) {
59 P->ConsumeAnyToken();
60 // FIXME: Clang does not call ExitScope on finalizing the regular TU, we
61 // might want to do that around HandleEndOfTranslationUnit.
62 P->ExitScope();
63 S.CurContext = nullptr;
64 // Start a new PTU.
65 P->EnterScope(Scope::DeclScope);
66 S.ActOnTranslationUnitScope(P->getCurScope());
67 }
68
70 Sema::ModuleImportState ImportState;
71 for (bool AtEOF = P->ParseFirstTopLevelDecl(ADecl, ImportState); !AtEOF;
72 AtEOF = P->ParseTopLevelDecl(ADecl, ImportState)) {
73 if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get()))
74 return llvm::make_error<llvm::StringError>("Parsing failed. "
75 "The consumer rejected a decl",
76 std::error_code());
77 }
78
79 DiagnosticsEngine &Diags = S.getDiagnostics();
80 if (Diags.hasErrorOccurred()) {
81 CleanUpPTU(C.getTranslationUnitDecl());
82
83 Diags.Reset(/*soft=*/true);
84 Diags.getClient()->clear();
85 return llvm::make_error<llvm::StringError>("Parsing failed.",
86 std::error_code());
87 }
88
89 // Process any TopLevelDecls generated by #pragma weak.
90 for (Decl *D : S.WeakTopLevelDecls()) {
91 DeclGroupRef DGR(D);
93 }
94
95 LocalInstantiations.perform();
96 GlobalInstantiations.perform();
97
99
100 return C.getTranslationUnitDecl();
101}
102
104IncrementalParser::Parse(llvm::StringRef input) {
106 assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
107
108 std::ostringstream SourceName;
109 SourceName << "input_line_" << InputCount++;
110
111 // Create an uninitialized memory buffer, copy code in and append "\n"
112 size_t InputSize = input.size(); // don't include trailing 0
113 // MemBuffer size should *not* include terminating zero
114 std::unique_ptr<llvm::MemoryBuffer> MB(
115 llvm::WritableMemoryBuffer::getNewUninitMemBuffer(InputSize + 1,
116 SourceName.str()));
117 char *MBStart = const_cast<char *>(MB->getBufferStart());
118 memcpy(MBStart, input.data(), InputSize);
119 MBStart[InputSize] = '\n';
120
122
123 // FIXME: Create SourceLocation, which will allow clang to order the overload
124 // candidates for example
125 SourceLocation NewLoc = SM.getLocForStartOfFile(SM.getMainFileID());
126
127 // Create FileID for the current buffer.
128 FileID FID = SM.createFileID(std::move(MB), SrcMgr::C_User, /*LoadedID=*/0,
129 /*LoadedOffset=*/0, NewLoc);
130
131 // NewLoc only used for diags.
132 if (PP.EnterSourceFile(FID, /*DirLookup=*/nullptr, NewLoc))
133 return llvm::make_error<llvm::StringError>("Parsing failed. "
134 "Cannot enter source file.",
135 std::error_code());
136
137 auto PTU = ParseOrWrapTopLevelDecl();
138 if (!PTU)
139 return PTU.takeError();
140
141 if (PP.getLangOpts().DelayedTemplateParsing) {
142 // Microsoft-specific:
143 // Late parsed templates can leave unswallowed "macro"-like tokens.
144 // They will seriously confuse the Parser when entering the next
145 // source file. So lex until we are EOF.
146 Token Tok;
147 do {
148 PP.Lex(Tok);
149 } while (Tok.isNot(tok::annot_repl_input_end));
150 } else {
151 Token AssertTok;
152 PP.Lex(AssertTok);
153 assert(AssertTok.is(tok::annot_repl_input_end) &&
154 "Lexer must be EOF when starting incremental parse!");
155 }
156
157 return PTU;
158}
159
161 if (StoredDeclsMap *Map = MostRecentTU->getPrimaryContext()->getLookupPtr()) {
162 for (auto &&[Key, List] : *Map) {
163 DeclContextLookupResult R = List.getLookupResult();
164 std::vector<NamedDecl *> NamedDeclsToRemove;
165 bool RemoveAll = true;
166 for (NamedDecl *D : R) {
167 if (D->getTranslationUnitDecl() == MostRecentTU)
168 NamedDeclsToRemove.push_back(D);
169 else
170 RemoveAll = false;
171 }
172 if (LLVM_LIKELY(RemoveAll)) {
173 Map->erase(Key);
174 } else {
175 for (NamedDecl *D : NamedDeclsToRemove)
176 List.remove(D);
177 }
178 }
179 }
180
181 // FIXME: We should de-allocate MostRecentTU
182 for (Decl *D : MostRecentTU->decls()) {
183 auto *ND = dyn_cast<NamedDecl>(D);
184 if (!ND || ND->getDeclName().isEmpty())
185 continue;
186 // Check if we need to clean up the IdResolver chain.
187 if (ND->getDeclName().getFETokenInfo() && !D->getLangOpts().ObjC &&
188 !D->getLangOpts().CPlusPlus)
190 }
191}
192
195 std::unique_ptr<llvm::Module> M /*={}*/) {
196 PTUs.emplace_back(PartialTranslationUnit());
197 PartialTranslationUnit &LastPTU = PTUs.back();
198 LastPTU.TUPart = TU;
199
200 if (!M)
201 M = Act->GenModule();
202
203 assert((!Act->getCodeGen() || M) && "Must have a llvm::Module at this point");
204
205 LastPTU.TheModule = std::move(M);
206 LLVM_DEBUG(llvm::dbgs() << "compile-ptu " << PTUs.size() - 1
207 << ": [TU=" << LastPTU.TUPart);
208 if (LastPTU.TheModule)
209 LLVM_DEBUG(llvm::dbgs() << ", M=" << LastPTU.TheModule.get() << " ("
210 << LastPTU.TheModule->getName() << ")");
211 LLVM_DEBUG(llvm::dbgs() << "]\n");
212 return LastPTU;
213}
214} // end namespace clang
const Decl * D
#define SM(sm)
Definition: OffloadArch.cpp:16
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
virtual void HandleTranslationUnit(ASTContext &Ctx)
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
Definition: ASTConsumer.h:67
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1382
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1459
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2373
StoredDeclsMap * getLookupPtr() const
Retrieve the internal representation of the lookup structure.
Definition: DeclBase.h:2681
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
void RemoveDecl(NamedDecl *D)
RemoveDecl - Unlink the decl from its shadowed decl chain.
A custom action enabling the incremental processing functionality.
CodeGenerator * getCodeGen() const
Access the current code generator.
std::unique_ptr< llvm::Module > GenModule()
Generate an LLVM module for the most recent parsed input.
IncrementalParser(CompilerInstance &Instance, IncrementalAction *Act, llvm::Error &Err, std::list< PartialTranslationUnit > &PTUs)
IncrementalAction * Act
The FrontendAction used during incremental parsing.
std::list< PartialTranslationUnit > & PTUs
unsigned InputCount
Counts the number of direct user input lines that have been parsed.
void CleanUpPTU(TranslationUnitDecl *MostRecentTU)
PartialTranslationUnit & RegisterPTU(TranslationUnitDecl *TU, std::unique_ptr< llvm::Module > M={})
Register a PTU produced by Parse.
virtual llvm::Expected< TranslationUnitDecl * > Parse(llvm::StringRef Input)
Parses incremental input by creating an in-memory file.
std::unique_ptr< Parser > P
Parser.
ASTConsumer * Consumer
Consumer to process the produced top level decls. Owned by Act.
Sema & S
The Sema performing the incremental compilation.
This represents a decl that may have a name.
Definition: Decl.h:273
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:171
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition: Parser.h:219
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:145
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
void Lex(Token &Result)
Lex the next token for this preprocessor.
bool EnterSourceFile(FileID FID, ConstSearchDirIterator Dir, SourceLocation Loc, bool IsFirstIncludeOfFile=true)
Add a source file to the top of the include stack and start lexing tokens from it instead of the curr...
const LangOptions & getLangOpts() const
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
Preprocessor & getPreprocessor() const
Definition: Sema.h:917
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition: Sema.cpp:172
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:915
ASTContext & getASTContext() const
Definition: Sema.h:918
SmallVectorImpl< Decl * > & WeakTopLevelDecls()
WeakTopLevelDeclDecls - access to #pragma weak-generated Decls.
Definition: Sema.h:4859
ASTConsumer & getASTConsumer() const
Definition: Sema.h:919
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1411
SourceManager & getSourceManager() const
Definition: Sema.h:916
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition: Sema.h:9834
IdentifierResolver IdResolver
Definition: Sema.h:3461
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:102
bool isNot(tok::TokenKind K) const
Definition: Token.h:103
The top declaration context.
Definition: Decl.h:104
The JSON file list parser is used to communicate input to InstallAPI.
The class keeps track of various objects created as part of processing incremental inputs.
std::unique_ptr< llvm::Module > TheModule
The llvm IR produced for the input.