PpContext.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. //
  2. // Copyright (C) 2013 LunarG, Inc.
  3. // Copyright (C) 2015-2018 Google, Inc.
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions
  8. // are met:
  9. //
  10. // Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. //
  13. // Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. //
  18. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  19. // contributors may be used to endorse or promote products derived
  20. // from this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  30. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  31. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  32. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. // POSSIBILITY OF SUCH DAMAGE.
  34. //
  35. /****************************************************************************\
  36. Copyright (c) 2002, NVIDIA Corporation.
  37. NVIDIA Corporation("NVIDIA") supplies this software to you in
  38. consideration of your agreement to the following terms, and your use,
  39. installation, modification or redistribution of this NVIDIA software
  40. constitutes acceptance of these terms. If you do not agree with these
  41. terms, please do not use, install, modify or redistribute this NVIDIA
  42. software.
  43. In consideration of your agreement to abide by the following terms, and
  44. subject to these terms, NVIDIA grants you a personal, non-exclusive
  45. license, under NVIDIA's copyrights in this original NVIDIA software (the
  46. "NVIDIA Software"), to use, reproduce, modify and redistribute the
  47. NVIDIA Software, with or without modifications, in source and/or binary
  48. forms; provided that if you redistribute the NVIDIA Software, you must
  49. retain the copyright notice of NVIDIA, this notice and the following
  50. text and disclaimers in all such redistributions of the NVIDIA Software.
  51. Neither the name, trademarks, service marks nor logos of NVIDIA
  52. Corporation may be used to endorse or promote products derived from the
  53. NVIDIA Software without specific prior written permission from NVIDIA.
  54. Except as expressly stated in this notice, no other rights or licenses
  55. express or implied, are granted by NVIDIA herein, including but not
  56. limited to any patent rights that may be infringed by your derivative
  57. works or by other works in which the NVIDIA Software may be
  58. incorporated. No hardware is licensed hereunder.
  59. THE NVIDIA SOFTWARE IS BEING PROVIDED ON AN "AS IS" BASIS, WITHOUT
  60. WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
  61. INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF TITLE,
  62. NON-INFRINGEMENT, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
  63. ITS USE AND OPERATION EITHER ALONE OR IN COMBINATION WITH OTHER
  64. PRODUCTS.
  65. IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT,
  66. INCIDENTAL, EXEMPLARY, CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  67. TO, LOST PROFITS; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  68. USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) OR ARISING IN ANY WAY
  69. OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE
  70. NVIDIA SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT,
  71. TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
  72. NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  73. \****************************************************************************/
  74. #ifndef PPCONTEXT_H
  75. #define PPCONTEXT_H
  76. #include <stack>
  77. #include <unordered_map>
  78. #include <sstream>
  79. #include "../ParseHelper.h"
  80. #include "PpTokens.h"
  81. /* windows only pragma */
  82. #ifdef _MSC_VER
  83. #pragma warning(disable : 4127)
  84. #endif
  85. namespace glslang {
  86. class TPpToken {
  87. public:
  88. TPpToken() { clear(); }
  89. void clear()
  90. {
  91. space = false;
  92. i64val = 0;
  93. loc.init();
  94. name[0] = 0;
  95. }
  96. // Used for comparing macro definitions, so checks what is relevant for that.
  97. bool operator==(const TPpToken& right) const
  98. {
  99. return space == right.space &&
  100. ival == right.ival && dval == right.dval && i64val == right.i64val &&
  101. strncmp(name, right.name, MaxTokenLength) == 0;
  102. }
  103. bool operator!=(const TPpToken& right) const { return ! operator==(right); }
  104. TSourceLoc loc;
  105. // True if a space (for white space or a removed comment) should also be
  106. // recognized, in front of the token returned:
  107. bool space;
  108. // Numeric value of the token:
  109. union {
  110. int ival;
  111. double dval;
  112. long long i64val;
  113. };
  114. // Text string of the token:
  115. char name[MaxTokenLength + 1];
  116. };
  117. class TStringAtomMap {
  118. //
  119. // Implementation is in PpAtom.cpp
  120. //
  121. // Maintain a bi-directional mapping between relevant preprocessor strings and
  122. // "atoms" which a unique integers (small, contiguous, not hash-like) per string.
  123. //
  124. public:
  125. TStringAtomMap();
  126. // Map string -> atom.
  127. // Return 0 if no existing string.
  128. int getAtom(const char* s) const
  129. {
  130. auto it = atomMap.find(s);
  131. return it == atomMap.end() ? 0 : it->second;
  132. }
  133. // Map a new or existing string -> atom, inventing a new atom if necessary.
  134. int getAddAtom(const char* s)
  135. {
  136. int atom = getAtom(s);
  137. if (atom == 0) {
  138. atom = nextAtom++;
  139. addAtomFixed(s, atom);
  140. }
  141. return atom;
  142. }
  143. // Map atom -> string.
  144. const char* getString(int atom) const { return stringMap[atom]->c_str(); }
  145. protected:
  146. TStringAtomMap(TStringAtomMap&);
  147. TStringAtomMap& operator=(TStringAtomMap&);
  148. TUnorderedMap<TString, int> atomMap;
  149. TVector<const TString*> stringMap; // these point into the TString in atomMap
  150. int nextAtom;
  151. // Bad source characters can lead to bad atoms, so gracefully handle those by
  152. // pre-filling the table with them (to avoid if tests later).
  153. TString badToken;
  154. // Add bi-directional mappings:
  155. // - string -> atom
  156. // - atom -> string
  157. void addAtomFixed(const char* s, int atom)
  158. {
  159. auto it = atomMap.insert(std::pair<TString, int>(s, atom)).first;
  160. if (stringMap.size() < (size_t)atom + 1)
  161. stringMap.resize(atom + 100, &badToken);
  162. stringMap[atom] = &it->first;
  163. }
  164. };
  165. class TInputScanner;
  166. enum MacroExpandResult {
  167. MacroExpandNotStarted, // macro not expanded, which might not be an error
  168. MacroExpandError, // a clear error occurred while expanding, no expansion
  169. MacroExpandStarted, // macro expansion process has started
  170. MacroExpandUndef // macro is undefined and will be expanded
  171. };
  172. // This class is the result of turning a huge pile of C code communicating through globals
  173. // into a class. This was done to allowing instancing to attain thread safety.
  174. // Don't expect too much in terms of OO design.
  175. class TPpContext {
  176. public:
  177. TPpContext(TParseContextBase&, const std::string& rootFileName, TShader::Includer&);
  178. virtual ~TPpContext();
  179. void setPreamble(const char* preamble, size_t length);
  180. int tokenize(TPpToken& ppToken);
  181. int tokenPaste(int token, TPpToken&);
  182. class tInput {
  183. public:
  184. tInput(TPpContext* p) : done(false), pp(p) { }
  185. virtual ~tInput() { }
  186. virtual int scan(TPpToken*) = 0;
  187. virtual int getch() = 0;
  188. virtual void ungetch() = 0;
  189. virtual bool peekPasting() { return false; } // true when about to see ##
  190. virtual bool peekContinuedPasting(int) { return false; } // true when non-spaced tokens can paste
  191. virtual bool endOfReplacementList() { return false; } // true when at the end of a macro replacement list (RHS of #define)
  192. virtual bool isMacroInput() { return false; }
  193. // Will be called when we start reading tokens from this instance
  194. virtual void notifyActivated() {}
  195. // Will be called when we do not read tokens from this instance anymore
  196. virtual void notifyDeleted() {}
  197. protected:
  198. bool done;
  199. TPpContext* pp;
  200. };
  201. void setInput(TInputScanner& input, bool versionWillBeError);
  202. void pushInput(tInput* in)
  203. {
  204. inputStack.push_back(in);
  205. in->notifyActivated();
  206. }
  207. void popInput()
  208. {
  209. inputStack.back()->notifyDeleted();
  210. delete inputStack.back();
  211. inputStack.pop_back();
  212. }
  213. //
  214. // From PpTokens.cpp
  215. //
  216. // Capture the needed parts of a token stream for macro recording/playback.
  217. class TokenStream {
  218. public:
  219. // Manage a stream of these 'Token', which capture the relevant parts
  220. // of a TPpToken, plus its atom.
  221. class Token {
  222. public:
  223. Token(int atom, const TPpToken& ppToken) :
  224. atom(atom),
  225. space(ppToken.space),
  226. i64val(ppToken.i64val),
  227. name(ppToken.name) { }
  228. int get(TPpToken& ppToken)
  229. {
  230. ppToken.clear();
  231. ppToken.space = space;
  232. ppToken.i64val = i64val;
  233. snprintf(ppToken.name, sizeof(ppToken.name), "%s", name.c_str());
  234. return atom;
  235. }
  236. bool isAtom(int a) const { return atom == a; }
  237. int getAtom() const { return atom; }
  238. bool nonSpaced() const { return !space; }
  239. protected:
  240. Token() {}
  241. int atom;
  242. bool space; // did a space precede the token?
  243. long long i64val;
  244. TString name;
  245. };
  246. TokenStream() : currentPos(0) { }
  247. void putToken(int token, TPpToken* ppToken);
  248. bool peekToken(int atom) { return !atEnd() && stream[currentPos].isAtom(atom); }
  249. bool peekContinuedPasting(int atom)
  250. {
  251. // This is basically necessary because, for example, the PP
  252. // tokenizer only accepts valid numeric-literals plus suffixes, so
  253. // separates numeric-literals plus bad suffix into two tokens, which
  254. // should get both pasted together as one token when token pasting.
  255. //
  256. // The following code is a bit more generalized than the above example.
  257. if (!atEnd() && atom == PpAtomIdentifier && stream[currentPos].nonSpaced()) {
  258. switch(stream[currentPos].getAtom()) {
  259. case PpAtomConstInt:
  260. case PpAtomConstUint:
  261. case PpAtomConstInt64:
  262. case PpAtomConstUint64:
  263. case PpAtomConstInt16:
  264. case PpAtomConstUint16:
  265. case PpAtomConstFloat:
  266. case PpAtomConstDouble:
  267. case PpAtomConstFloat16:
  268. case PpAtomConstString:
  269. case PpAtomIdentifier:
  270. return true;
  271. default:
  272. break;
  273. }
  274. }
  275. return false;
  276. }
  277. int getToken(TParseContextBase&, TPpToken*);
  278. bool atEnd() { return currentPos >= stream.size(); }
  279. bool peekTokenizedPasting(bool lastTokenPastes);
  280. bool peekUntokenizedPasting();
  281. void reset() { currentPos = 0; }
  282. protected:
  283. TVector<Token> stream;
  284. size_t currentPos;
  285. };
  286. //
  287. // From Pp.cpp
  288. //
  289. struct MacroSymbol {
  290. MacroSymbol() : functionLike(0), busy(0), undef(0) { }
  291. TVector<int> args;
  292. TokenStream body;
  293. unsigned functionLike : 1; // 0 means object-like, 1 means function-like
  294. unsigned busy : 1;
  295. unsigned undef : 1;
  296. };
  297. typedef TMap<int, MacroSymbol> TSymbolMap;
  298. TSymbolMap macroDefs; // map atoms to macro definitions
  299. MacroSymbol* lookupMacroDef(int atom)
  300. {
  301. auto existingMacroIt = macroDefs.find(atom);
  302. return (existingMacroIt == macroDefs.end()) ? nullptr : &(existingMacroIt->second);
  303. }
  304. void addMacroDef(int atom, MacroSymbol& macroDef) { macroDefs[atom] = macroDef; }
  305. protected:
  306. TPpContext(TPpContext&);
  307. TPpContext& operator=(TPpContext&);
  308. TStringAtomMap atomStrings;
  309. char* preamble; // string to parse, all before line 1 of string 0, it is 0 if no preamble
  310. int preambleLength;
  311. char** strings; // official strings of shader, starting a string 0 line 1
  312. size_t* lengths;
  313. int numStrings; // how many official strings there are
  314. int currentString; // which string we're currently parsing (-1 for preamble)
  315. // Scanner data:
  316. int previous_token;
  317. TParseContextBase& parseContext;
  318. // Get the next token from *stack* of input sources, popping input sources
  319. // that are out of tokens, down until an input source is found that has a token.
  320. // Return EndOfInput when there are no more tokens to be found by doing this.
  321. int scanToken(TPpToken* ppToken)
  322. {
  323. int token = EndOfInput;
  324. while (! inputStack.empty()) {
  325. token = inputStack.back()->scan(ppToken);
  326. if (token != EndOfInput || inputStack.empty())
  327. break;
  328. popInput();
  329. }
  330. return token;
  331. }
  332. int getChar() { return inputStack.back()->getch(); }
  333. void ungetChar() { inputStack.back()->ungetch(); }
  334. bool peekPasting() { return !inputStack.empty() && inputStack.back()->peekPasting(); }
  335. bool peekContinuedPasting(int a)
  336. {
  337. return !inputStack.empty() && inputStack.back()->peekContinuedPasting(a);
  338. }
  339. bool endOfReplacementList() { return inputStack.empty() || inputStack.back()->endOfReplacementList(); }
  340. bool isMacroInput() { return inputStack.size() > 0 && inputStack.back()->isMacroInput(); }
  341. static const int maxIfNesting = 65;
  342. int ifdepth; // current #if-#else-#endif nesting in the cpp.c file (pre-processor)
  343. bool elseSeen[maxIfNesting]; // Keep a track of whether an else has been seen at a particular depth
  344. int elsetracker; // #if-#else and #endif constructs...Counter.
  345. class tMacroInput : public tInput {
  346. public:
  347. tMacroInput(TPpContext* pp) : tInput(pp), prepaste(false), postpaste(false) { }
  348. virtual ~tMacroInput()
  349. {
  350. for (size_t i = 0; i < args.size(); ++i)
  351. delete args[i];
  352. for (size_t i = 0; i < expandedArgs.size(); ++i)
  353. delete expandedArgs[i];
  354. }
  355. virtual int scan(TPpToken*) override;
  356. virtual int getch() override { assert(0); return EndOfInput; }
  357. virtual void ungetch() override { assert(0); }
  358. bool peekPasting() override { return prepaste; }
  359. bool peekContinuedPasting(int a) override { return mac->body.peekContinuedPasting(a); }
  360. bool endOfReplacementList() override { return mac->body.atEnd(); }
  361. bool isMacroInput() override { return true; }
  362. MacroSymbol *mac;
  363. TVector<TokenStream*> args;
  364. TVector<TokenStream*> expandedArgs;
  365. protected:
  366. bool prepaste; // true if we are just before ##
  367. bool postpaste; // true if we are right after ##
  368. };
  369. class tMarkerInput : public tInput {
  370. public:
  371. tMarkerInput(TPpContext* pp) : tInput(pp) { }
  372. virtual int scan(TPpToken*) override
  373. {
  374. if (done)
  375. return EndOfInput;
  376. done = true;
  377. return marker;
  378. }
  379. virtual int getch() override { assert(0); return EndOfInput; }
  380. virtual void ungetch() override { assert(0); }
  381. static const int marker = -3;
  382. };
  383. class tZeroInput : public tInput {
  384. public:
  385. tZeroInput(TPpContext* pp) : tInput(pp) { }
  386. virtual int scan(TPpToken*) override;
  387. virtual int getch() override { assert(0); return EndOfInput; }
  388. virtual void ungetch() override { assert(0); }
  389. };
  390. std::vector<tInput*> inputStack;
  391. bool errorOnVersion;
  392. bool versionSeen;
  393. //
  394. // from Pp.cpp
  395. //
  396. // Used to obtain #include content.
  397. TShader::Includer& includer;
  398. int CPPdefine(TPpToken * ppToken);
  399. int CPPundef(TPpToken * ppToken);
  400. int CPPelse(int matchelse, TPpToken * ppToken);
  401. int extraTokenCheck(int atom, TPpToken* ppToken, int token);
  402. int eval(int token, int precedence, bool shortCircuit, int& res, bool& err, TPpToken * ppToken);
  403. int evalToToken(int token, bool shortCircuit, int& res, bool& err, TPpToken * ppToken);
  404. int CPPif (TPpToken * ppToken);
  405. int CPPifdef(int defined, TPpToken * ppToken);
  406. int CPPinclude(TPpToken * ppToken);
  407. int CPPline(TPpToken * ppToken);
  408. int CPPerror(TPpToken * ppToken);
  409. int CPPpragma(TPpToken * ppToken);
  410. int CPPversion(TPpToken * ppToken);
  411. int CPPextension(TPpToken * ppToken);
  412. int readCPPline(TPpToken * ppToken);
  413. int scanHeaderName(TPpToken* ppToken, char delimit);
  414. TokenStream* PrescanMacroArg(TokenStream&, TPpToken*, bool newLineOkay);
  415. MacroExpandResult MacroExpand(TPpToken* ppToken, bool expandUndef, bool newLineOkay);
  416. //
  417. // From PpTokens.cpp
  418. //
  419. void pushTokenStreamInput(TokenStream&, bool pasting = false);
  420. void UngetToken(int token, TPpToken*);
  421. class tTokenInput : public tInput {
  422. public:
  423. tTokenInput(TPpContext* pp, TokenStream* t, bool prepasting) :
  424. tInput(pp),
  425. tokens(t),
  426. lastTokenPastes(prepasting) { }
  427. virtual int scan(TPpToken *ppToken) override { return tokens->getToken(pp->parseContext, ppToken); }
  428. virtual int getch() override { assert(0); return EndOfInput; }
  429. virtual void ungetch() override { assert(0); }
  430. virtual bool peekPasting() override { return tokens->peekTokenizedPasting(lastTokenPastes); }
  431. bool peekContinuedPasting(int a) override { return tokens->peekContinuedPasting(a); }
  432. protected:
  433. TokenStream* tokens;
  434. bool lastTokenPastes; // true if the last token in the input is to be pasted, rather than consumed as a token
  435. };
  436. class tUngotTokenInput : public tInput {
  437. public:
  438. tUngotTokenInput(TPpContext* pp, int t, TPpToken* p) : tInput(pp), token(t), lval(*p) { }
  439. virtual int scan(TPpToken *) override;
  440. virtual int getch() override { assert(0); return EndOfInput; }
  441. virtual void ungetch() override { assert(0); }
  442. protected:
  443. int token;
  444. TPpToken lval;
  445. };
  446. //
  447. // From PpScanner.cpp
  448. //
  449. class tStringInput : public tInput {
  450. public:
  451. tStringInput(TPpContext* pp, TInputScanner& i) : tInput(pp), input(&i) { }
  452. virtual int scan(TPpToken*) override;
  453. // Scanner used to get source stream characters.
  454. // - Escaped newlines are handled here, invisibly to the caller.
  455. // - All forms of newline are handled, and turned into just a '\n'.
  456. int getch() override
  457. {
  458. int ch = input->get();
  459. if (ch == '\\') {
  460. // Move past escaped newlines, as many as sequentially exist
  461. do {
  462. if (input->peek() == '\r' || input->peek() == '\n') {
  463. bool allowed = pp->parseContext.lineContinuationCheck(input->getSourceLoc(), pp->inComment);
  464. if (! allowed && pp->inComment)
  465. return '\\';
  466. // escape one newline now
  467. ch = input->get();
  468. int nextch = input->get();
  469. if (ch == '\r' && nextch == '\n')
  470. ch = input->get();
  471. else
  472. ch = nextch;
  473. } else
  474. return '\\';
  475. } while (ch == '\\');
  476. }
  477. // handle any non-escaped newline
  478. if (ch == '\r' || ch == '\n') {
  479. if (ch == '\r' && input->peek() == '\n')
  480. input->get();
  481. return '\n';
  482. }
  483. return ch;
  484. }
  485. // Scanner used to backup the source stream characters. Newlines are
  486. // handled here, invisibly to the caller, meaning have to undo exactly
  487. // what getch() above does (e.g., don't leave things in the middle of a
  488. // sequence of escaped newlines).
  489. void ungetch() override
  490. {
  491. input->unget();
  492. do {
  493. int ch = input->peek();
  494. if (ch == '\r' || ch == '\n') {
  495. if (ch == '\n') {
  496. // correct for two-character newline
  497. input->unget();
  498. if (input->peek() != '\r')
  499. input->get();
  500. }
  501. // now in front of a complete newline, move past an escape character
  502. input->unget();
  503. if (input->peek() == '\\')
  504. input->unget();
  505. else {
  506. input->get();
  507. break;
  508. }
  509. } else
  510. break;
  511. } while (true);
  512. }
  513. protected:
  514. TInputScanner* input;
  515. };
  516. // Holds a reference to included file data, as well as a
  517. // prologue and an epilogue string. This can be scanned using the tInput
  518. // interface and acts as a single source string.
  519. class TokenizableIncludeFile : public tInput {
  520. public:
  521. // Copies prologue and epilogue. The includedFile must remain valid
  522. // until this TokenizableIncludeFile is no longer used.
  523. TokenizableIncludeFile(const TSourceLoc& startLoc,
  524. const std::string& prologue,
  525. TShader::Includer::IncludeResult* includedFile,
  526. const std::string& epilogue,
  527. TPpContext* pp)
  528. : tInput(pp),
  529. prologue_(prologue),
  530. epilogue_(epilogue),
  531. includedFile_(includedFile),
  532. scanner(3, strings, lengths, nullptr, 0, 0, true),
  533. prevScanner(nullptr),
  534. stringInput(pp, scanner)
  535. {
  536. strings[0] = prologue_.data();
  537. strings[1] = includedFile_->headerData;
  538. strings[2] = epilogue_.data();
  539. lengths[0] = prologue_.size();
  540. lengths[1] = includedFile_->headerLength;
  541. lengths[2] = epilogue_.size();
  542. scanner.setLine(startLoc.line);
  543. scanner.setString(startLoc.string);
  544. scanner.setFile(startLoc.getFilenameStr(), 0);
  545. scanner.setFile(startLoc.getFilenameStr(), 1);
  546. scanner.setFile(startLoc.getFilenameStr(), 2);
  547. }
  548. // tInput methods:
  549. int scan(TPpToken* t) override { return stringInput.scan(t); }
  550. int getch() override { return stringInput.getch(); }
  551. void ungetch() override { stringInput.ungetch(); }
  552. void notifyActivated() override
  553. {
  554. prevScanner = pp->parseContext.getScanner();
  555. pp->parseContext.setScanner(&scanner);
  556. pp->push_include(includedFile_);
  557. }
  558. void notifyDeleted() override
  559. {
  560. pp->parseContext.setScanner(prevScanner);
  561. pp->pop_include();
  562. }
  563. private:
  564. TokenizableIncludeFile& operator=(const TokenizableIncludeFile&);
  565. // Stores the prologue for this string.
  566. const std::string prologue_;
  567. // Stores the epilogue for this string.
  568. const std::string epilogue_;
  569. // Points to the IncludeResult that this TokenizableIncludeFile represents.
  570. TShader::Includer::IncludeResult* includedFile_;
  571. // Will point to prologue_, includedFile_->headerData and epilogue_
  572. // This is passed to scanner constructor.
  573. // These do not own the storage and it must remain valid until this
  574. // object has been destroyed.
  575. const char* strings[3];
  576. // Length of str_, passed to scanner constructor.
  577. size_t lengths[3];
  578. // Scans over str_.
  579. TInputScanner scanner;
  580. // The previous effective scanner before the scanner in this instance
  581. // has been activated.
  582. TInputScanner* prevScanner;
  583. // Delegate object implementing the tInput interface.
  584. tStringInput stringInput;
  585. };
  586. int ScanFromString(char* s);
  587. void missingEndifCheck();
  588. int lFloatConst(int len, int ch, TPpToken* ppToken);
  589. int characterLiteral(TPpToken* ppToken);
  590. void push_include(TShader::Includer::IncludeResult* result)
  591. {
  592. currentSourceFile = result->headerName;
  593. includeStack.push(result);
  594. }
  595. void pop_include()
  596. {
  597. TShader::Includer::IncludeResult* include = includeStack.top();
  598. includeStack.pop();
  599. includer.releaseInclude(include);
  600. if (includeStack.empty()) {
  601. currentSourceFile = rootFileName;
  602. } else {
  603. currentSourceFile = includeStack.top()->headerName;
  604. }
  605. }
  606. bool inComment;
  607. std::string rootFileName;
  608. std::stack<TShader::Includer::IncludeResult*> includeStack;
  609. std::string currentSourceFile;
  610. std::istringstream strtodStream;
  611. bool disableEscapeSequences;
  612. };
  613. } // end namespace glslang
  614. #endif // PPCONTEXT_H