Chris Lattner | a2812b5 | 2008-10-12 05:44:03 +0000 | [diff] [blame^] | 1 | //===--- TokenRewriter.cpp - Token-based code rewriting interface ---------===// |
| 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 TokenRewriter class, which is used for code |
| 11 | // transformations. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "clang/Rewrite/TokenRewriter.h" |
| 16 | #include "clang/Lex/Lexer.h" |
| 17 | #include "clang/Basic/SourceManager.h" |
| 18 | using namespace clang; |
| 19 | |
| 20 | TokenRewriter::TokenRewriter(unsigned FileID, SourceManager &SM, |
| 21 | const LangOptions &LangOpts) { |
| 22 | |
| 23 | std::pair<const char*,const char*> File = SM.getBufferData(FileID); |
| 24 | |
| 25 | // Create a lexer to lex all the tokens of the main file in raw mode. |
| 26 | Lexer RawLex(SourceLocation::getFileLoc(FileID, 0), |
| 27 | LangOpts, File.first, File.second); |
| 28 | |
| 29 | // Return all comments and whitespace as tokens. |
| 30 | RawLex.SetKeepWhitespaceMode(true); |
| 31 | |
| 32 | // Lex the file, populating our datastructures. |
| 33 | Token RawTok; |
| 34 | RawLex.LexFromRawLexer(RawTok); |
| 35 | while (RawTok.isNot(tok::eof)) { |
| 36 | AddToken(RawTok, TokenList.end()); |
| 37 | RawLex.LexFromRawLexer(RawTok); |
| 38 | } |
| 39 | |
| 40 | |
| 41 | } |
| 42 | |
| 43 | /// AddToken - Add the specified token into the Rewriter before the other |
| 44 | /// position. |
| 45 | void TokenRewriter::AddToken(const Token &T, TokenRefTy Where) { |
| 46 | Where = TokenList.insert(Where, T); |
| 47 | |
| 48 | bool InsertSuccess = TokenAtLoc.insert(std::make_pair(T.getLocation(), |
| 49 | Where)).second; |
| 50 | assert(InsertSuccess && "Token location already in rewriter!"); |
| 51 | InsertSuccess = InsertSuccess; |
| 52 | } |
| 53 | |