clang 24.0.0git
ParseAST.cpp
Go to the documentation of this file.
1//===--- ParseAST.cpp - Provide the clang::ParseAST method ----------------===//
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 clang::ParseAST method.
10//
11//===----------------------------------------------------------------------===//
12
17#include "clang/AST/Stmt.h"
18#include "clang/Parse/Parser.h"
21#include "clang/Sema/Sema.h"
23#include "llvm/Support/CrashRecoveryContext.h"
24#include "llvm/Support/TimeProfiler.h"
25#include <cstdio>
26#include <memory>
27
28using namespace clang;
29
30namespace {
31
32/// Resets LLVM's pretty stack state so that stack traces are printed correctly
33/// when there are nested CrashRecoveryContexts and the inner one recovers from
34/// a crash.
35class ResetStackCleanup
36 : public llvm::CrashRecoveryContextCleanupBase<ResetStackCleanup,
37 const void> {
38public:
39 ResetStackCleanup(llvm::CrashRecoveryContext *Context, const void *Top)
40 : llvm::CrashRecoveryContextCleanupBase<ResetStackCleanup, const void>(
41 Context, Top) {}
42 void recoverResources() override {
43 llvm::RestorePrettyStackState(resource);
44 }
45};
46
47/// If a crash happens while the parser is active, an entry is printed for it.
48class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
49 const Parser &P;
50public:
51 PrettyStackTraceParserEntry(const Parser &p) : P(p) {}
52 void print(raw_ostream &OS) const override;
53};
54
55/// If a crash happens while the parser is active, print out a line indicating
56/// what the current token is.
57void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
58 const Token &Tok = P.getCurToken();
59 if (Tok.is(tok::eof)) {
60 OS << "<eof> parser at end of file\n";
61 return;
62 }
63
64 if (Tok.getLocation().isInvalid()) {
65 OS << "<unknown> parser at unknown location\n";
66 return;
67 }
68
69 const Preprocessor &PP = P.getPreprocessor();
71 if (Tok.isAnnotation()) {
72 OS << ": at annotation token\n";
73 } else {
74 // Do the equivalent of PP.getSpelling(Tok) except for the parts that would
75 // allocate memory.
76 bool Invalid = false;
77 const SourceManager &SM = P.getPreprocessor().getSourceManager();
78 unsigned Length = Tok.getLength();
79 const char *Spelling = SM.getCharacterData(Tok.getLocation(), &Invalid);
80 if (Invalid) {
81 OS << ": unknown current parser token\n";
82 return;
83 }
84 OS << ": current parser token '" << StringRef(Spelling, Length) << "'\n";
85 }
86}
87
88} // namespace
89
90//===----------------------------------------------------------------------===//
91// Public interface to the file
92//===----------------------------------------------------------------------===//
93
94/// ParseAST - Parse the entire file specified, notifying the ASTConsumer as
95/// the file is parsed. This inserts the parsed decls into the translation unit
96/// held by Ctx.
97///
99 ASTContext &Ctx, bool PrintStats,
100 TranslationUnitKind TUKind,
101 CodeCompleteConsumer *CompletionConsumer,
102 bool SkipFunctionBodies) {
103
104 std::unique_ptr<Sema> S(
105 new Sema(PP, Ctx, *Consumer, TUKind, CompletionConsumer));
106
107 // Recover resources if we crash before exiting this method.
108 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(S.get());
109
110 ParseAST(*S, PrintStats, SkipFunctionBodies);
111}
112
113void clang::ParseAST(Sema &S, bool PrintStats, bool SkipFunctionBodies) {
114 // Collect global stats on Decls/Stmts (until we have a module streamer).
115 if (PrintStats) {
118 }
119
120 // Also turn on collection of stats inside of the Sema object.
121 bool OldCollectStats = PrintStats;
122 std::swap(OldCollectStats, S.CollectStats);
123
124 ASTConsumer *Consumer = &S.getASTConsumer();
125
126 std::unique_ptr<Parser> ParseOP(
127 new Parser(S.getPreprocessor(), S, SkipFunctionBodies));
128 Parser &P = *ParseOP;
129
130 llvm::CrashRecoveryContextCleanupRegistrar<const void, ResetStackCleanup>
131 CleanupPrettyStack(llvm::SavePrettyStackState());
132 PrettyStackTraceParserEntry CrashInfo(P);
133
134 // Recover resources if we crash before exiting this method.
135 llvm::CrashRecoveryContextCleanupRegistrar<Parser>
136 CleanupParser(ParseOP.get());
137
140 if (External)
141 External->StartTranslationUnit(Consumer);
142
143 // If a PCH through header is specified that does not have an include in
144 // the source, or a PCH is being created with #pragma hdrstop with nothing
145 // after the pragma, there won't be any tokens or a Lexer.
146 bool HaveLexer = S.getPreprocessor().getCurrentLexer();
147
148 if (HaveLexer) {
149 llvm::TimeTraceScope TimeScope("Frontend", [&]() {
150 llvm::TimeTraceMetadata M;
151 if (llvm::isTimeTraceVerbose()) {
152 const SourceManager &SM = S.getSourceManager();
153 if (const auto *FE = SM.getFileEntryForID(SM.getMainFileID()))
154 M.File = FE->tryGetRealPathName();
155 }
156 return M;
157 });
158 P.Initialize();
160 Sema::ModuleImportState ImportState;
161 EnterExpressionEvaluationContext PotentiallyEvaluated(
163
164 for (bool AtEOF = P.ParseFirstTopLevelDecl(ADecl, ImportState); !AtEOF;
165 AtEOF = P.ParseTopLevelDecl(ADecl, ImportState)) {
166 // If we got a null return and something *was* parsed, ignore it. This
167 // is due to a top-level semicolon, an action override, or a parse error
168 // skipping something.
169 if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get()))
170 return;
171 }
172 }
173
174 // Process any TopLevelDecls generated by #pragma weak.
175 for (Decl *D : S.WeakTopLevelDecls())
176 Consumer->HandleTopLevelDecl(DeclGroupRef(D));
177
179
180 std::swap(OldCollectStats, S.CollectStats);
181 if (PrintStats) {
182 llvm::errs() << "\nSTATISTICS:\n";
183 if (HaveLexer) P.getActions().PrintStats();
187 Consumer->PrintStats();
188 }
189}
Defines the clang::ASTContext interface.
Token Tok
The Token.
static void print(llvm::raw_ostream &OS, const T &V, const Context &Ctx, QualType Ty)
#define SM(sm)
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
virtual void HandleTranslationUnit(ASTContext &Ctx)
HandleTranslationUnit - This method is called when the ASTs for entire translation unit have been par...
Definition ASTConsumer.h:68
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
virtual void PrintStats()
PrintStats - If desired, print any statistics.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
void PrintStats() const
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Abstract interface for a consumer of code-completion information.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
static void EnableStatistics()
Definition DeclBase.cpp:220
static void PrintStats()
Definition DeclBase.cpp:224
RAII object that enters a new expression evaluation context.
Abstract interface for external sources of AST nodes.
PtrTy get() const
Definition Ownership.h:81
Parser - This implements a parser for the C family of languages.
Definition Parser.h:256
Preprocessor & getPreprocessor() const
Definition Parser.h:291
Sema & getActions() const
Definition Parser.h:292
bool ParseTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
ParseTopLevelDecl - Parse one top-level declaration, return whatever the action tells us to.
Definition Parser.cpp:613
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition Parser.h:304
const Token & getCurToken() const
Definition Parser.h:295
bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result, Sema::ModuleImportState &ImportState)
Parse the first top-level declaration in a translation unit.
Definition Parser.cpp:592
void Initialize()
Initialize - Warm up the parser.
Definition Parser.cpp:490
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
PreprocessorLexer * getCurrentLexer() const
Return the current lexer being lexed from.
void EnterMainSourceFile()
Enter the specified FileID as the main source file, which implicitly adds the builtin defines etc.
SourceManager & getSourceManager() const
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
Preprocessor & getPreprocessor() const
Definition Sema.h:940
ASTContext & getASTContext() const
Definition Sema.h:941
SmallVectorImpl< Decl * > & WeakTopLevelDecls()
WeakTopLevelDeclDecls - access to #pragma weak-generated Decls.
Definition Sema.h:4963
ASTConsumer & getASTConsumer() const
Definition Sema.h:942
bool CollectStats
Flag indicating whether or not to collect detailed statistics.
Definition Sema.h:1240
SourceManager & getSourceManager() const
Definition Sema.h:939
ModuleImportState
An enumeration to represent the transition of states in parsing module fragments and imports.
Definition Sema.h:9983
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6840
void PrintStats() const
Print out statistics about the semantic analysis.
Definition Sema.cpp:684
void print(raw_ostream &OS, const SourceManager &SM) const
This class handles loading and caching of source files into memory.
static void EnableStatistics()
Definition Stmt.cpp:144
static void PrintStats()
Definition Stmt.cpp:108
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
unsigned getLength() const
Definition Token.h:145
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:104
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition Token.h:131
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
void ParseAST(Preprocessor &pp, ASTConsumer *C, ASTContext &Ctx, bool PrintStats=false, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr, bool SkipFunctionBodies=false)
Parse the entire file specified, notifying the ASTConsumer as the file is parsed.
Definition ParseAST.cpp:98
@ External
External linkage, which indicates that the entity can be referred to from other translation units.
Definition Linkage.h:58
TranslationUnitKind
Describes the kind of translation unit being processed.