1 // Copyright 2016 The SwiftShader Authors. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef COMPILER_PREPROCESSOR_MACRO_EXPANDER_H_ 16 #define COMPILER_PREPROCESSOR_MACRO_EXPANDER_H_ 17 18 #include <cassert> 19 #include <memory> 20 #include <vector> 21 22 #include "Lexer.h" 23 #include "Macro.h" 24 #include "pp_utils.h" 25 26 namespace pp 27 { 28 29 class Diagnostics; 30 31 class MacroExpander : public Lexer 32 { 33 public: 34 MacroExpander(Lexer* lexer, MacroSet* macroSet, Diagnostics* diagnostics, bool parseDefined); 35 virtual ~MacroExpander(); 36 37 virtual void lex(Token* token); 38 39 private: 40 PP_DISALLOW_COPY_AND_ASSIGN(MacroExpander); 41 42 void getToken(Token* token); 43 void ungetToken(const Token& token); 44 bool isNextTokenLeftParen(); 45 46 bool pushMacro(const Macro& macro, const Token& identifier); 47 void popMacro(); 48 49 bool expandMacro(const Macro& macro, 50 const Token& identifier, 51 std::vector<Token>* replacements); 52 53 typedef std::vector<Token> MacroArg; 54 bool collectMacroArgs(const Macro& macro, 55 const Token& identifier, 56 std::vector<MacroArg>* args); 57 void replaceMacroParams(const Macro& macro, 58 const std::vector<MacroArg>& args, 59 std::vector<Token>* replacements); 60 61 struct MacroContext 62 { 63 const Macro* macro; 64 size_t index; 65 std::vector<Token> replacements; 66 MacroContextMacroContext67 MacroContext() : macro(0), index(0) { } emptyMacroContext68 bool empty() const { return index == replacements.size(); } getMacroContext69 const Token& get() { return replacements[index++]; } ungetMacroContext70 void unget() { assert(index > 0); --index; } 71 }; 72 73 Lexer* mLexer; 74 MacroSet* mMacroSet; 75 Diagnostics* mDiagnostics; 76 const bool mParseDefined; 77 78 Token* mReserveToken; 79 std::vector<MacroContext*> mContextStack; 80 }; 81 82 } // namespace pp 83 #endif // COMPILER_PREPROCESSOR_MACRO_EXPANDER_H_ 84 85