Home | History | Annotate | Download | only in Parse
      1 //===--- ParseAST.cpp - Provide the clang::ParseAST method ----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the clang::ParseAST method.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Parse/ParseAST.h"
     15 #include "clang/AST/ASTConsumer.h"
     16 #include "clang/AST/ASTContext.h"
     17 #include "clang/AST/DeclCXX.h"
     18 #include "clang/AST/ExternalASTSource.h"
     19 #include "clang/AST/Stmt.h"
     20 #include "clang/Parse/ParseDiagnostic.h"
     21 #include "clang/Parse/Parser.h"
     22 #include "clang/Sema/CodeCompleteConsumer.h"
     23 #include "clang/Sema/ExternalSemaSource.h"
     24 #include "clang/Sema/Sema.h"
     25 #include "clang/Sema/SemaConsumer.h"
     26 #include "llvm/ADT/OwningPtr.h"
     27 #include "llvm/Support/CrashRecoveryContext.h"
     28 #include <cstdio>
     29 
     30 using namespace clang;
     31 
     32 namespace {
     33 
     34 /// If a crash happens while the parser is active, an entry is printed for it.
     35 class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry {
     36   const Parser &P;
     37 public:
     38   PrettyStackTraceParserEntry(const Parser &p) : P(p) {}
     39   virtual void print(raw_ostream &OS) const;
     40 };
     41 
     42 /// If a crash happens while the parser is active, print out a line indicating
     43 /// what the current token is.
     44 void PrettyStackTraceParserEntry::print(raw_ostream &OS) const {
     45   const Token &Tok = P.getCurToken();
     46   if (Tok.is(tok::eof)) {
     47     OS << "<eof> parser at end of file\n";
     48     return;
     49   }
     50 
     51   if (Tok.getLocation().isInvalid()) {
     52     OS << "<unknown> parser at unknown location\n";
     53     return;
     54   }
     55 
     56   const Preprocessor &PP = P.getPreprocessor();
     57   Tok.getLocation().print(OS, PP.getSourceManager());
     58   if (Tok.isAnnotation()) {
     59     OS << ": at annotation token\n";
     60   } else {
     61     // Do the equivalent of PP.getSpelling(Tok) except for the parts that would
     62     // allocate memory.
     63     bool Invalid = false;
     64     const SourceManager &SM = P.getPreprocessor().getSourceManager();
     65     unsigned Length = Tok.getLength();
     66     const char *Spelling = SM.getCharacterData(Tok.getLocation(), &Invalid);
     67     if (Invalid) {
     68       OS << ": unknown current parser token\n";
     69       return;
     70     }
     71     OS << ": current parser token '" << StringRef(Spelling, Length) << "'\n";
     72   }
     73 }
     74 
     75 }  // namespace
     76 
     77 //===----------------------------------------------------------------------===//
     78 // Public interface to the file
     79 //===----------------------------------------------------------------------===//
     80 
     81 /// ParseAST - Parse the entire file specified, notifying the ASTConsumer as
     82 /// the file is parsed.  This inserts the parsed decls into the translation unit
     83 /// held by Ctx.
     84 ///
     85 void clang::ParseAST(Preprocessor &PP, ASTConsumer *Consumer,
     86                      ASTContext &Ctx, bool PrintStats,
     87                      TranslationUnitKind TUKind,
     88                      CodeCompleteConsumer *CompletionConsumer,
     89                      bool SkipFunctionBodies) {
     90 
     91   OwningPtr<Sema> S(new Sema(PP, Ctx, *Consumer, TUKind, CompletionConsumer));
     92 
     93   // Recover resources if we crash before exiting this method.
     94   llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(S.get());
     95 
     96   ParseAST(*S.get(), PrintStats, SkipFunctionBodies);
     97 }
     98 
     99 void clang::ParseAST(Sema &S, bool PrintStats, bool SkipFunctionBodies) {
    100   // Collect global stats on Decls/Stmts (until we have a module streamer).
    101   if (PrintStats) {
    102     Decl::EnableStatistics();
    103     Stmt::EnableStatistics();
    104   }
    105 
    106   // Also turn on collection of stats inside of the Sema object.
    107   bool OldCollectStats = PrintStats;
    108   std::swap(OldCollectStats, S.CollectStats);
    109 
    110   ASTConsumer *Consumer = &S.getASTConsumer();
    111 
    112   OwningPtr<Parser> ParseOP(new Parser(S.getPreprocessor(), S,
    113                                        SkipFunctionBodies));
    114   Parser &P = *ParseOP.get();
    115 
    116   PrettyStackTraceParserEntry CrashInfo(P);
    117 
    118   // Recover resources if we crash before exiting this method.
    119   llvm::CrashRecoveryContextCleanupRegistrar<Parser>
    120     CleanupParser(ParseOP.get());
    121 
    122   S.getPreprocessor().EnterMainSourceFile();
    123   P.Initialize();
    124 
    125   // C11 6.9p1 says translation units must have at least one top-level
    126   // declaration. C++ doesn't have this restriction. We also don't want to
    127   // complain if we have a precompiled header, although technically if the PCH
    128   // is empty we should still emit the (pedantic) diagnostic.
    129   Parser::DeclGroupPtrTy ADecl;
    130   ExternalASTSource *External = S.getASTContext().getExternalSource();
    131   if (External)
    132     External->StartTranslationUnit(Consumer);
    133 
    134   if (P.ParseTopLevelDecl(ADecl)) {
    135     if (!External && !S.getLangOpts().CPlusPlus)
    136       P.Diag(diag::ext_empty_translation_unit);
    137   } else {
    138     do {
    139       // If we got a null return and something *was* parsed, ignore it.  This
    140       // is due to a top-level semicolon, an action override, or a parse error
    141       // skipping something.
    142       if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get()))
    143         return;
    144     } while (!P.ParseTopLevelDecl(ADecl));
    145   }
    146 
    147   // Process any TopLevelDecls generated by #pragma weak.
    148   for (SmallVectorImpl<Decl *>::iterator
    149        I = S.WeakTopLevelDecls().begin(),
    150        E = S.WeakTopLevelDecls().end(); I != E; ++I)
    151     Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
    152 
    153   Consumer->HandleTranslationUnit(S.getASTContext());
    154 
    155   std::swap(OldCollectStats, S.CollectStats);
    156   if (PrintStats) {
    157     llvm::errs() << "\nSTATISTICS:\n";
    158     P.getActions().PrintStats();
    159     S.getASTContext().PrintStats();
    160     Decl::PrintStats();
    161     Stmt::PrintStats();
    162     Consumer->PrintStats();
    163   }
    164 }
    165