PageRenderTime 31ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/RenderSystems/GL3Plus/src/GLSL/src/OgreGLSLPreprocessor.cpp

https://bitbucket.org/masterfalcon/ogre-gl3plus/
C++ | 1286 lines | 1199 code | 48 blank | 39 comment | 80 complexity | bcaab47e9c57315693f72565f0fff5eb MD5 | raw file
Possible License(s): MIT, LGPL-2.1
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2009 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "OgreGLSLPreprocessor.h"
  25. #include "OgreLogManager.h"
  26. namespace Ogre {
  27. // Limit max number of macro arguments to this
  28. #define MAX_MACRO_ARGS 16
  29. #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 && !defined( __MINGW32__ )
  30. #define snprintf _snprintf
  31. #endif
  32. //---------------------------------------------------------------------------//
  33. /// Return closest power of two not smaller than given number
  34. static size_t ClosestPow2 (size_t x)
  35. {
  36. if (!(x & (x - 1)))
  37. return x;
  38. while (x & (x + 1))
  39. x |= (x + 1);
  40. return x + 1;
  41. }
  42. void CPreprocessor::Token::Append (const char *iString, size_t iLength)
  43. {
  44. Token t (Token::TK_TEXT, iString, iLength);
  45. Append (t);
  46. }
  47. void CPreprocessor::Token::Append (const Token &iOther)
  48. {
  49. if (!iOther.String)
  50. return;
  51. if (!String)
  52. {
  53. String = iOther.String;
  54. Length = iOther.Length;
  55. Allocated = iOther.Allocated;
  56. iOther.Allocated = 0; // !!! not quite correct but effective
  57. return;
  58. }
  59. if (Allocated)
  60. {
  61. size_t new_alloc = ClosestPow2 (Length + iOther.Length);
  62. if (new_alloc < 64)
  63. new_alloc = 64;
  64. if (new_alloc != Allocated)
  65. {
  66. Allocated = new_alloc;
  67. Buffer = (char *)realloc (Buffer, Allocated);
  68. }
  69. }
  70. else if (String + Length != iOther.String)
  71. {
  72. Allocated = ClosestPow2 (Length + iOther.Length);
  73. if (Allocated < 64)
  74. Allocated = 64;
  75. char *newstr = (char *)malloc (Allocated);
  76. memcpy (newstr, String, Length);
  77. Buffer = newstr;
  78. }
  79. if (Allocated)
  80. memcpy (Buffer + Length, iOther.String, iOther.Length);
  81. Length += iOther.Length;
  82. }
  83. bool CPreprocessor::Token::GetValue (long &oValue) const
  84. {
  85. long val = 0;
  86. size_t i = 0;
  87. while (isspace (String [i]))
  88. i++;
  89. long base = 10;
  90. if (String [i] == '0')
  91. if (Length > i + 1 && String [i + 1] == 'x')
  92. base = 16, i += 2;
  93. else
  94. base = 8;
  95. for (; i < Length; i++)
  96. {
  97. long c = long (String [i]);
  98. if (isspace (c))
  99. // Possible end of number
  100. break;
  101. if (c >= 'a' && c <= 'z')
  102. c -= ('a' - 'A');
  103. c -= '0';
  104. if (c < 0)
  105. return false;
  106. if (c > 9)
  107. c -= ('A' - '9' - 1);
  108. if (c >= base)
  109. return false;
  110. val = (val * base) + c;
  111. }
  112. // Check that all other characters are just spaces
  113. for (; i < Length; i++)
  114. if (!isspace (String [i]))
  115. return false;
  116. oValue = val;
  117. return true;
  118. }
  119. void CPreprocessor::Token::SetValue (long iValue)
  120. {
  121. char tmp [21];
  122. int len = snprintf (tmp, sizeof (tmp), "%ld", iValue);
  123. Length = 0;
  124. Append (tmp, len);
  125. Type = TK_NUMBER;
  126. }
  127. void CPreprocessor::Token::AppendNL (int iCount)
  128. {
  129. static const char newlines [8] =
  130. { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' };
  131. while (iCount > 8)
  132. {
  133. Append (newlines, 8);
  134. iCount -= 8;
  135. }
  136. if (iCount > 0)
  137. Append (newlines, iCount);
  138. }
  139. int CPreprocessor::Token::CountNL ()
  140. {
  141. if (Type == TK_EOS || Type == TK_ERROR)
  142. return 0;
  143. const char *s = String;
  144. int l = Length;
  145. int c = 0;
  146. while (l > 0)
  147. {
  148. const char *n = (const char *)memchr (s, '\n', l);
  149. if (!n)
  150. return c;
  151. c++;
  152. l -= (n - s + 1);
  153. s = n + 1;
  154. }
  155. return c;
  156. }
  157. //---------------------------------------------------------------------------//
  158. CPreprocessor::Token CPreprocessor::Macro::Expand (
  159. int iNumArgs, CPreprocessor::Token *iArgs, Macro *iMacros)
  160. {
  161. Expanding = true;
  162. CPreprocessor cpp;
  163. cpp.MacroList = iMacros;
  164. // Define a new macro for every argument
  165. int i;
  166. for (i = 0; i < iNumArgs; i++)
  167. cpp.Define (Args [i].String, Args [i].Length,
  168. iArgs [i].String, iArgs [i].Length);
  169. // The rest arguments are empty
  170. for (; i < NumArgs; i++)
  171. cpp.Define (Args [i].String, Args [i].Length, "", 0);
  172. // Now run the macro expansion through the supplimentary preprocessor
  173. Token xt = cpp.Parse (Value);
  174. Expanding = false;
  175. // Remove the extra macros we have defined
  176. for (int i = NumArgs - 1; i >= 0; i--)
  177. cpp.Undef (Args [i].String, Args [i].Length);
  178. cpp.MacroList = NULL;
  179. return xt;
  180. }
  181. //---------------------------------------------------------------------------//
  182. static void DefaultError (void *iData, int iLine, const char *iError,
  183. const char *iToken, size_t iTokenLen)
  184. {
  185. (void)iData;
  186. char line [1000];
  187. if (iToken)
  188. snprintf (line, sizeof (line), "line %d: %s: `%.*s'\n",
  189. iLine, iError, int (iTokenLen), iToken);
  190. else
  191. snprintf (line, sizeof (line), "line %d: %s\n", iLine, iError);
  192. LogManager::getSingleton ().logMessage (line);
  193. }
  194. //---------------------------------------------------------------------------//
  195. CPreprocessor::ErrorHandlerFunc CPreprocessor::ErrorHandler = DefaultError;
  196. CPreprocessor::CPreprocessor (const Token &iToken, int iLine) : MacroList (NULL)
  197. {
  198. Source = iToken.String;
  199. SourceEnd = iToken.String + iToken.Length;
  200. EnableOutput = 1;
  201. Line = iLine;
  202. BOL = true;
  203. }
  204. CPreprocessor::~CPreprocessor ()
  205. {
  206. delete MacroList;
  207. }
  208. void CPreprocessor::Error (int iLine, const char *iError, const Token *iToken)
  209. {
  210. if (iToken)
  211. ErrorHandler (ErrorData, iLine, iError, iToken->String, iToken->Length);
  212. else
  213. ErrorHandler (ErrorData, iLine, iError, NULL, 0);
  214. }
  215. CPreprocessor::Token CPreprocessor::GetToken (bool iExpand)
  216. {
  217. if (Source >= SourceEnd)
  218. return Token (Token::TK_EOS);
  219. const char *begin = Source;
  220. char c = *Source++;
  221. if (c == '\n' || (c == '\r' && *Source == '\n'))
  222. {
  223. Line++;
  224. BOL = true;
  225. if (c == '\r')
  226. Source++;
  227. return Token (Token::TK_NEWLINE, begin, Source - begin);
  228. }
  229. else if (isspace (c))
  230. {
  231. while (Source < SourceEnd &&
  232. *Source != '\r' &&
  233. *Source != '\n' &&
  234. isspace (*Source))
  235. Source++;
  236. return Token (Token::TK_WHITESPACE, begin, Source - begin);
  237. }
  238. else if (isdigit (c))
  239. {
  240. BOL = false;
  241. if (c == '0' && Source < SourceEnd && Source [0] == 'x') // hex numbers
  242. {
  243. Source++;
  244. while (Source < SourceEnd && isxdigit (*Source))
  245. Source++;
  246. }
  247. else
  248. while (Source < SourceEnd && isdigit (*Source))
  249. Source++;
  250. return Token (Token::TK_NUMBER, begin, Source - begin);
  251. }
  252. else if (c == '_' || isalnum (c))
  253. {
  254. BOL = false;
  255. while (Source < SourceEnd && (*Source == '_' || isalnum (*Source)))
  256. Source++;
  257. Token t (Token::TK_KEYWORD, begin, Source - begin);
  258. if (iExpand)
  259. t = ExpandMacro (t);
  260. return t;
  261. }
  262. else if (c == '"' || c == '\'')
  263. {
  264. BOL = false;
  265. while (Source < SourceEnd && *Source != c)
  266. {
  267. if (*Source == '\\')
  268. {
  269. Source++;
  270. if (Source >= SourceEnd)
  271. break;
  272. }
  273. if (*Source == '\n')
  274. Line++;
  275. Source++;
  276. }
  277. if (Source < SourceEnd)
  278. Source++;
  279. return Token (Token::TK_STRING, begin, Source - begin);
  280. }
  281. else if (c == '/' && *Source == '/')
  282. {
  283. BOL = false;
  284. Source++;
  285. while (Source < SourceEnd && *Source != '\r' && *Source != '\n')
  286. Source++;
  287. return Token (Token::TK_LINECOMMENT, begin, Source - begin);
  288. }
  289. else if (c == '/' && *Source == '*')
  290. {
  291. BOL = false;
  292. Source++;
  293. while (Source < SourceEnd && (Source [0] != '*' || Source [1] != '/'))
  294. {
  295. if (*Source == '\n')
  296. Line++;
  297. Source++;
  298. }
  299. if (Source < SourceEnd && *Source == '*')
  300. Source++;
  301. if (Source < SourceEnd && *Source == '/')
  302. Source++;
  303. return Token (Token::TK_COMMENT, begin, Source - begin);
  304. }
  305. else if (c == '#' && BOL)
  306. {
  307. // Skip all whitespaces after '#'
  308. while (Source < SourceEnd && isspace (*Source))
  309. Source++;
  310. while (Source < SourceEnd && !isspace (*Source))
  311. Source++;
  312. return Token (Token::TK_DIRECTIVE, begin, Source - begin);
  313. }
  314. else if (c == '\\' && Source < SourceEnd && (*Source == '\r' || *Source == '\n'))
  315. {
  316. // Treat backslash-newline as a whole token
  317. if (*Source == '\r')
  318. Source++;
  319. if (*Source == '\n')
  320. Source++;
  321. Line++;
  322. BOL = true;
  323. return Token (Token::TK_LINECONT, begin, Source - begin);
  324. }
  325. else
  326. {
  327. BOL = false;
  328. // Handle double-char operators here
  329. if (c == '>' && (*Source == '>' || *Source == '='))
  330. Source++;
  331. else if (c == '<' && (*Source == '<' || *Source == '='))
  332. Source++;
  333. else if (c == '!' && *Source == '=')
  334. Source++;
  335. else if (c == '=' && *Source == '=')
  336. Source++;
  337. else if ((c == '|' || c == '&' || c == '^') && *Source == c)
  338. Source++;
  339. return Token (Token::TK_PUNCTUATION, begin, Source - begin);
  340. }
  341. }
  342. CPreprocessor::Macro *CPreprocessor::IsDefined (const Token &iToken)
  343. {
  344. for (Macro *cur = MacroList; cur; cur = cur->Next)
  345. if (cur->Name == iToken)
  346. return cur;
  347. return NULL;
  348. }
  349. CPreprocessor::Token CPreprocessor::ExpandMacro (const Token &iToken)
  350. {
  351. Macro *cur = IsDefined (iToken);
  352. if (cur && !cur->Expanding)
  353. {
  354. Token *args = NULL;
  355. int nargs = 0;
  356. int old_line = Line;
  357. if (cur->NumArgs != 0)
  358. {
  359. Token t = GetArguments (nargs, args, cur->ExpandFunc ? false : true);
  360. if (t.Type == Token::TK_ERROR)
  361. {
  362. delete [] args;
  363. return t;
  364. }
  365. // Put the token back into the source pool; we'll handle it later
  366. if (t.String)
  367. {
  368. // Returned token should never be allocated on heap
  369. assert (t.Allocated == 0);
  370. Source = t.String;
  371. Line -= t.CountNL ();
  372. }
  373. }
  374. if (nargs > cur->NumArgs)
  375. {
  376. char tmp [60];
  377. snprintf (tmp, sizeof (tmp), "Macro `%.*s' passed %d arguments, but takes just %d",
  378. int (cur->Name.Length), cur->Name.String,
  379. nargs, cur->NumArgs);
  380. Error (old_line, tmp);
  381. return Token (Token::TK_ERROR);
  382. }
  383. Token t = cur->ExpandFunc ?
  384. cur->ExpandFunc (this, nargs, args) :
  385. cur->Expand (nargs, args, MacroList);
  386. t.AppendNL (Line - old_line);
  387. delete [] args;
  388. return t;
  389. }
  390. return iToken;
  391. }
  392. /**
  393. * Operator priority:
  394. * 0: Whole expression
  395. * 1: '(' ')'
  396. * 2: ||
  397. * 3: &&
  398. * 4: |
  399. * 5: ^
  400. * 6: &
  401. * 7: '==' '!='
  402. * 8: '<' '<=' '>' '>='
  403. * 9: '<<' '>>'
  404. * 10: '+' '-'
  405. * 11: '*' '/' '%'
  406. * 12: unary '+' '-' '!' '~'
  407. */
  408. CPreprocessor::Token CPreprocessor::GetExpression (
  409. Token &oResult, int iLine, int iOpPriority)
  410. {
  411. char tmp [40];
  412. do
  413. {
  414. oResult = GetToken (true);
  415. } while (oResult.Type == Token::TK_WHITESPACE ||
  416. oResult.Type == Token::TK_NEWLINE ||
  417. oResult.Type == Token::TK_COMMENT ||
  418. oResult.Type == Token::TK_LINECOMMENT ||
  419. oResult.Type == Token::TK_LINECONT);
  420. Token op (Token::TK_WHITESPACE, "", 0);
  421. // Handle unary operators here
  422. if (oResult.Type == Token::TK_PUNCTUATION && oResult.Length == 1)
  423. if (strchr ("+-!~", oResult.String [0]))
  424. {
  425. char uop = oResult.String [0];
  426. op = GetExpression (oResult, iLine, 12);
  427. long val;
  428. if (!GetValue (oResult, val, iLine))
  429. {
  430. snprintf (tmp, sizeof (tmp), "Unary '%c' not applicable", uop);
  431. Error (iLine, tmp, &oResult);
  432. return Token (Token::TK_ERROR);
  433. }
  434. if (uop == '-')
  435. oResult.SetValue (-val);
  436. else if (uop == '!')
  437. oResult.SetValue (!val);
  438. else if (uop == '~')
  439. oResult.SetValue (~val);
  440. }
  441. else if (oResult.String [0] == '(')
  442. {
  443. op = GetExpression (oResult, iLine, 1);
  444. if (op.Type == Token::TK_ERROR)
  445. return op;
  446. if (op.Type == Token::TK_EOS)
  447. {
  448. Error (iLine, "Unclosed parenthesis in #if expression");
  449. return Token (Token::TK_ERROR);
  450. }
  451. assert (op.Type == Token::TK_PUNCTUATION &&
  452. op.Length == 1 &&
  453. op.String [0] == ')');
  454. op = GetToken (true);
  455. }
  456. while (op.Type == Token::TK_WHITESPACE ||
  457. op.Type == Token::TK_NEWLINE ||
  458. op.Type == Token::TK_COMMENT ||
  459. op.Type == Token::TK_LINECOMMENT ||
  460. op.Type == Token::TK_LINECONT)
  461. op = GetToken (true);
  462. while (true)
  463. {
  464. if (op.Type != Token::TK_PUNCTUATION)
  465. return op;
  466. int prio = 0;
  467. if (op.Length == 1)
  468. switch (op.String [0])
  469. {
  470. case ')': return op;
  471. case '|': prio = 4; break;
  472. case '^': prio = 5; break;
  473. case '&': prio = 6; break;
  474. case '<':
  475. case '>': prio = 8; break;
  476. case '+':
  477. case '-': prio = 10; break;
  478. case '*':
  479. case '/':
  480. case '%': prio = 11; break;
  481. }
  482. else if (op.Length == 2)
  483. switch (op.String [0])
  484. {
  485. case '|': if (op.String [1] == '|') prio = 2; break;
  486. case '&': if (op.String [1] == '&') prio = 3; break;
  487. case '=': if (op.String [1] == '=') prio = 7; break;
  488. case '!': if (op.String [1] == '=') prio = 7; break;
  489. case '<':
  490. if (op.String [1] == '=')
  491. prio = 8;
  492. else if (op.String [1] == '<')
  493. prio = 9;
  494. break;
  495. case '>':
  496. if (op.String [1] == '=')
  497. prio = 8;
  498. else if (op.String [1] == '>')
  499. prio = 9;
  500. break;
  501. }
  502. if (!prio)
  503. {
  504. Error (iLine, "Expecting operator, got", &op);
  505. return Token (Token::TK_ERROR);
  506. }
  507. if (iOpPriority >= prio)
  508. return op;
  509. Token rop;
  510. Token nextop = GetExpression (rop, iLine, prio);
  511. long vlop, vrop;
  512. if (!GetValue (oResult, vlop, iLine))
  513. {
  514. snprintf (tmp, sizeof (tmp), "Left operand of '%.*s' is not a number",
  515. int (op.Length), op.String);
  516. Error (iLine, tmp, &oResult);
  517. return Token (Token::TK_ERROR);
  518. }
  519. if (!GetValue (rop, vrop, iLine))
  520. {
  521. snprintf (tmp, sizeof (tmp), "Right operand of '%.*s' is not a number",
  522. int (op.Length), op.String);
  523. Error (iLine, tmp, &rop);
  524. return Token (Token::TK_ERROR);
  525. }
  526. switch (op.String [0])
  527. {
  528. case '|':
  529. if (prio == 2)
  530. oResult.SetValue (vlop || vrop);
  531. else
  532. oResult.SetValue (vlop | vrop);
  533. break;
  534. case '&':
  535. if (prio == 3)
  536. oResult.SetValue (vlop && vrop);
  537. else
  538. oResult.SetValue (vlop & vrop);
  539. break;
  540. case '<':
  541. if (op.Length == 1)
  542. oResult.SetValue (vlop < vrop);
  543. else if (prio == 8)
  544. oResult.SetValue (vlop <= vrop);
  545. else if (prio == 9)
  546. oResult.SetValue (vlop << vrop);
  547. break;
  548. case '>':
  549. if (op.Length == 1)
  550. oResult.SetValue (vlop > vrop);
  551. else if (prio == 8)
  552. oResult.SetValue (vlop >= vrop);
  553. else if (prio == 9)
  554. oResult.SetValue (vlop >> vrop);
  555. break;
  556. case '^': oResult.SetValue (vlop ^ vrop); break;
  557. case '!': oResult.SetValue (vlop != vrop); break;
  558. case '=': oResult.SetValue (vlop == vrop); break;
  559. case '+': oResult.SetValue (vlop + vrop); break;
  560. case '-': oResult.SetValue (vlop - vrop); break;
  561. case '*': oResult.SetValue (vlop * vrop); break;
  562. case '/':
  563. case '%':
  564. if (vrop == 0)
  565. {
  566. Error (iLine, "Division by zero");
  567. return Token (Token::TK_ERROR);
  568. }
  569. if (op.String [0] == '/')
  570. oResult.SetValue (vlop / vrop);
  571. else
  572. oResult.SetValue (vlop % vrop);
  573. break;
  574. }
  575. op = nextop;
  576. }
  577. }
  578. bool CPreprocessor::GetValue (const Token &iToken, long &oValue, int iLine)
  579. {
  580. Token r;
  581. const Token *vt = &iToken;
  582. if ((vt->Type == Token::TK_KEYWORD ||
  583. vt->Type == Token::TK_TEXT ||
  584. vt->Type == Token::TK_NUMBER) &&
  585. !vt->String)
  586. {
  587. Error (iLine, "Trying to evaluate an empty expression");
  588. return false;
  589. }
  590. if (vt->Type == Token::TK_TEXT)
  591. {
  592. CPreprocessor cpp (iToken, iLine);
  593. cpp.MacroList = MacroList;
  594. Token t;
  595. t = cpp.GetExpression (r, iLine);
  596. cpp.MacroList = NULL;
  597. if (t.Type == Token::TK_ERROR)
  598. return false;
  599. if (t.Type != Token::TK_EOS)
  600. {
  601. Error (iLine, "Garbage after expression", &t);
  602. return false;
  603. }
  604. vt = &r;
  605. }
  606. Macro *m;
  607. switch (vt->Type)
  608. {
  609. case Token::TK_EOS:
  610. case Token::TK_ERROR:
  611. return false;
  612. case Token::TK_KEYWORD:
  613. // Try to expand the macro
  614. if ((m = IsDefined (*vt)) && !m->Expanding)
  615. {
  616. Token x = ExpandMacro (*vt);
  617. m->Expanding = true;
  618. bool rc = GetValue (x, oValue, iLine);
  619. m->Expanding = false;
  620. return rc;
  621. }
  622. // Undefined macro, "expand" to 0 (mimic cpp behaviour)
  623. oValue = 0;
  624. break;
  625. case Token::TK_TEXT:
  626. case Token::TK_NUMBER:
  627. if (!vt->GetValue (oValue))
  628. {
  629. Error (iLine, "Not a numeric expression", vt);
  630. return false;
  631. }
  632. break;
  633. default:
  634. Error (iLine, "Unexpected token", vt);
  635. return false;
  636. }
  637. return true;
  638. }
  639. CPreprocessor::Token CPreprocessor::GetArgument (Token &oArg, bool iExpand)
  640. {
  641. do
  642. {
  643. oArg = GetToken (iExpand);
  644. } while (oArg.Type == Token::TK_WHITESPACE ||
  645. oArg.Type == Token::TK_NEWLINE ||
  646. oArg.Type == Token::TK_COMMENT ||
  647. oArg.Type == Token::TK_LINECOMMENT ||
  648. oArg.Type == Token::TK_LINECONT);
  649. if (!iExpand)
  650. if (oArg.Type == Token::TK_EOS)
  651. return oArg;
  652. else if (oArg.Type == Token::TK_PUNCTUATION &&
  653. (oArg.String [0] == ',' ||
  654. oArg.String [0] == ')'))
  655. {
  656. Token t = oArg;
  657. oArg = Token (Token::TK_TEXT, "", 0);
  658. return t;
  659. }
  660. else if (oArg.Type != Token::TK_KEYWORD)
  661. {
  662. Error (Line, "Unexpected token", &oArg);
  663. return Token (Token::TK_ERROR);
  664. }
  665. uint len = oArg.Length;
  666. while (true)
  667. {
  668. Token t = GetToken (iExpand);
  669. switch (t.Type)
  670. {
  671. case Token::TK_EOS:
  672. Error (Line, "Unfinished list of arguments");
  673. case Token::TK_ERROR:
  674. return Token (Token::TK_ERROR);
  675. case Token::TK_PUNCTUATION:
  676. if (t.String [0] == ',' ||
  677. t.String [0] == ')')
  678. {
  679. // Trim whitespaces at the end
  680. oArg.Length = len;
  681. return t;
  682. }
  683. break;
  684. case Token::TK_LINECONT:
  685. case Token::TK_COMMENT:
  686. case Token::TK_LINECOMMENT:
  687. case Token::TK_NEWLINE:
  688. // ignore these tokens
  689. continue;
  690. default:
  691. break;
  692. }
  693. if (!iExpand && t.Type != Token::TK_WHITESPACE)
  694. {
  695. Error (Line, "Unexpected token", &oArg);
  696. return Token (Token::TK_ERROR);
  697. }
  698. oArg.Append (t);
  699. if (t.Type != Token::TK_WHITESPACE)
  700. len = oArg.Length;
  701. }
  702. }
  703. CPreprocessor::Token CPreprocessor::GetArguments (int &oNumArgs, Token *&oArgs,
  704. bool iExpand)
  705. {
  706. Token args [MAX_MACRO_ARGS];
  707. int nargs = 0;
  708. // Suppose we'll leave by the wrong path
  709. oNumArgs = 0;
  710. oArgs = NULL;
  711. Token t;
  712. do
  713. {
  714. t = GetToken (iExpand);
  715. } while (t.Type == Token::TK_WHITESPACE ||
  716. t.Type == Token::TK_COMMENT ||
  717. t.Type == Token::TK_LINECOMMENT);
  718. if (t.Type != Token::TK_PUNCTUATION || t.String [0] != '(')
  719. {
  720. oNumArgs = 0;
  721. oArgs = NULL;
  722. return t;
  723. }
  724. while (true)
  725. {
  726. if (nargs == MAX_MACRO_ARGS)
  727. {
  728. Error (Line, "Too many arguments to macro");
  729. return Token (Token::TK_ERROR);
  730. }
  731. t = GetArgument (args [nargs++], iExpand);
  732. switch (t.Type)
  733. {
  734. case Token::TK_EOS:
  735. Error (Line, "Unfinished list of arguments");
  736. case Token::TK_ERROR:
  737. return Token (Token::TK_ERROR);
  738. case Token::TK_PUNCTUATION:
  739. if (t.String [0] == ')')
  740. {
  741. t = GetToken (iExpand);
  742. goto Done;
  743. } // otherwise we've got a ','
  744. break;
  745. default:
  746. Error (Line, "Unexpected token", &t);
  747. break;
  748. }
  749. }
  750. Done:
  751. oNumArgs = nargs;
  752. oArgs = new Token [nargs];
  753. for (int i = 0; i < nargs; i++)
  754. oArgs [i] = args [i];
  755. return t;
  756. }
  757. bool CPreprocessor::HandleDefine (Token &iBody, int iLine)
  758. {
  759. // Create an additional preprocessor to process macro body
  760. CPreprocessor cpp (iBody, iLine);
  761. Token t = cpp.GetToken (false);
  762. if (t.Type != Token::TK_KEYWORD)
  763. {
  764. Error (iLine, "Macro name expected after #define");
  765. return false;
  766. }
  767. Macro *m = new Macro (t);
  768. m->Body = iBody;
  769. t = cpp.GetArguments (m->NumArgs, m->Args, false);
  770. while (t.Type == Token::TK_WHITESPACE)
  771. t = cpp.GetToken (false);
  772. switch (t.Type)
  773. {
  774. case Token::TK_NEWLINE:
  775. case Token::TK_EOS:
  776. // Assign "" to token
  777. t = Token (Token::TK_TEXT, "", 0);
  778. break;
  779. case Token::TK_ERROR:
  780. delete m;
  781. return false;
  782. default:
  783. t.Type = Token::TK_TEXT;
  784. assert (t.String + t.Length == cpp.Source);
  785. t.Length = cpp.SourceEnd - t.String;
  786. break;
  787. }
  788. m->Value = t;
  789. m->Next = MacroList;
  790. MacroList = m;
  791. return true;
  792. }
  793. bool CPreprocessor::HandleUnDef (Token &iBody, int iLine)
  794. {
  795. CPreprocessor cpp (iBody, iLine);
  796. Token t = cpp.GetToken (false);
  797. if (t.Type != Token::TK_KEYWORD)
  798. {
  799. Error (iLine, "Expecting a macro name after #undef, got", &t);
  800. return false;
  801. }
  802. // Don't barf if macro does not exist - standard C behaviour
  803. Undef (t.String, t.Length);
  804. do
  805. {
  806. t = cpp.GetToken (false);
  807. } while (t.Type == Token::TK_WHITESPACE ||
  808. t.Type == Token::TK_COMMENT ||
  809. t.Type == Token::TK_LINECOMMENT);
  810. if (t.Type != Token::TK_EOS)
  811. Error (iLine, "Warning: Ignoring garbage after directive", &t);
  812. return true;
  813. }
  814. bool CPreprocessor::HandleIfDef (Token &iBody, int iLine)
  815. {
  816. if (EnableOutput & (1 << 31))
  817. {
  818. Error (iLine, "Too many embedded #if directives");
  819. return false;
  820. }
  821. CPreprocessor cpp (iBody, iLine);
  822. Token t = cpp.GetToken (false);
  823. if (t.Type != Token::TK_KEYWORD)
  824. {
  825. Error (iLine, "Expecting a macro name after #ifdef, got", &t);
  826. return false;
  827. }
  828. EnableOutput <<= 1;
  829. if (IsDefined (t))
  830. EnableOutput |= 1;
  831. do
  832. {
  833. t = cpp.GetToken (false);
  834. } while (t.Type == Token::TK_WHITESPACE ||
  835. t.Type == Token::TK_COMMENT ||
  836. t.Type == Token::TK_LINECOMMENT);
  837. if (t.Type != Token::TK_EOS)
  838. Error (iLine, "Warning: Ignoring garbage after directive", &t);
  839. return true;
  840. }
  841. CPreprocessor::Token CPreprocessor::ExpandDefined (CPreprocessor *iParent, int iNumArgs, Token *iArgs)
  842. {
  843. if (iNumArgs != 1)
  844. {
  845. iParent->Error (iParent->Line, "The defined() function takes exactly one argument");
  846. return Token (Token::TK_ERROR);
  847. }
  848. const char *v = iParent->IsDefined (iArgs [0]) ? "1" : "0";
  849. return Token (Token::TK_NUMBER, v, 1);
  850. }
  851. bool CPreprocessor::HandleIf (Token &iBody, int iLine)
  852. {
  853. Macro defined (Token (Token::TK_KEYWORD, "defined", 7));
  854. defined.Next = MacroList;
  855. defined.ExpandFunc = ExpandDefined;
  856. defined.NumArgs = 1;
  857. // Temporary add the defined() function to the macro list
  858. MacroList = &defined;
  859. long val;
  860. bool rc = GetValue (iBody, val, iLine);
  861. // Restore the macro list
  862. MacroList = defined.Next;
  863. defined.Next = NULL;
  864. if (!rc)
  865. return false;
  866. EnableOutput <<= 1;
  867. if (val)
  868. EnableOutput |= 1;
  869. return true;
  870. }
  871. bool CPreprocessor::HandleElse (Token &iBody, int iLine)
  872. {
  873. if (EnableOutput == 1)
  874. {
  875. Error (iLine, "#else without #if");
  876. return false;
  877. }
  878. // Negate the result of last #if
  879. EnableOutput ^= 1;
  880. if (iBody.Length)
  881. Error (iLine, "Warning: Ignoring garbage after #else", &iBody);
  882. return true;
  883. }
  884. bool CPreprocessor::HandleEndIf (Token &iBody, int iLine)
  885. {
  886. EnableOutput >>= 1;
  887. if (EnableOutput == 0)
  888. {
  889. Error (iLine, "#endif without #if");
  890. return false;
  891. }
  892. if (iBody.Length)
  893. Error (iLine, "Warning: Ignoring garbage after #endif", &iBody);
  894. return true;
  895. }
  896. CPreprocessor::Token CPreprocessor::HandleDirective (Token &iToken, int iLine)
  897. {
  898. // Analyze preprocessor directive
  899. const char *directive = iToken.String + 1;
  900. int dirlen = iToken.Length - 1;
  901. while (dirlen && isspace (*directive))
  902. dirlen--, directive++;
  903. int old_line = Line;
  904. // Collect the remaining part of the directive until EOL
  905. Token t, last;
  906. do
  907. {
  908. t = GetToken (false);
  909. if (t.Type == Token::TK_NEWLINE)
  910. {
  911. // No directive arguments
  912. last = t;
  913. t.Length = 0;
  914. goto Done;
  915. }
  916. } while (t.Type == Token::TK_WHITESPACE ||
  917. t.Type == Token::TK_LINECONT ||
  918. t.Type == Token::TK_COMMENT ||
  919. t.Type == Token::TK_LINECOMMENT);
  920. for (;;)
  921. {
  922. last = GetToken (false);
  923. switch (last.Type)
  924. {
  925. case Token::TK_EOS:
  926. // Can happen and is not an error
  927. goto Done;
  928. case Token::TK_LINECOMMENT:
  929. case Token::TK_COMMENT:
  930. // Skip comments in macros
  931. continue;
  932. case Token::TK_ERROR:
  933. return last;
  934. case Token::TK_LINECONT:
  935. continue;
  936. case Token::TK_NEWLINE:
  937. goto Done;
  938. default:
  939. break;
  940. }
  941. t.Append (last);
  942. t.Type = Token::TK_TEXT;
  943. }
  944. Done:
  945. #define IS_DIRECTIVE(s) ((dirlen == sizeof (s) - 1) && (strncmp (directive, s, sizeof (s) - 1) == 0))
  946. bool rc;
  947. if (IS_DIRECTIVE ("define"))
  948. rc = HandleDefine (t, iLine);
  949. else if (IS_DIRECTIVE ("undef"))
  950. rc = HandleUnDef (t, iLine);
  951. else if (IS_DIRECTIVE ("ifdef"))
  952. rc = HandleIfDef (t, iLine);
  953. else if (IS_DIRECTIVE ("ifndef"))
  954. {
  955. rc = HandleIfDef (t, iLine);
  956. if (rc)
  957. EnableOutput ^= 1;
  958. }
  959. else if (IS_DIRECTIVE ("if"))
  960. rc = HandleIf (t, iLine);
  961. else if (IS_DIRECTIVE ("else"))
  962. rc = HandleElse (t, iLine);
  963. else if (IS_DIRECTIVE ("endif"))
  964. rc = HandleEndIf (t, iLine);
  965. else
  966. {
  967. //Error (iLine, "Unknown preprocessor directive", &iToken);
  968. //return Token (Token::TK_ERROR);
  969. // Unknown preprocessor directive, roll back and pass through
  970. Line = old_line;
  971. Source = iToken.String + iToken.Length;
  972. iToken.Type = Token::TK_TEXT;
  973. return iToken;
  974. }
  975. #undef IS_DIRECTIVE
  976. if (!rc)
  977. return Token (Token::TK_ERROR);
  978. return last;
  979. }
  980. void CPreprocessor::Define (const char *iMacroName, size_t iMacroNameLen,
  981. const char *iMacroValue, size_t iMacroValueLen)
  982. {
  983. Macro *m = new Macro (Token (Token::TK_KEYWORD, iMacroName, iMacroNameLen));
  984. m->Value = Token (Token::TK_TEXT, iMacroValue, iMacroValueLen);
  985. m->Next = MacroList;
  986. MacroList = m;
  987. }
  988. void CPreprocessor::Define (const char *iMacroName, size_t iMacroNameLen,
  989. long iMacroValue)
  990. {
  991. Macro *m = new Macro (Token (Token::TK_KEYWORD, iMacroName, iMacroNameLen));
  992. m->Value.SetValue (iMacroValue);
  993. m->Next = MacroList;
  994. MacroList = m;
  995. }
  996. bool CPreprocessor::Undef (const char *iMacroName, size_t iMacroNameLen)
  997. {
  998. Macro **cur = &MacroList;
  999. Token name (Token::TK_KEYWORD, iMacroName, iMacroNameLen);
  1000. while (*cur)
  1001. {
  1002. if ((*cur)->Name == name)
  1003. {
  1004. Macro *next = (*cur)->Next;
  1005. (*cur)->Next = NULL;
  1006. delete (*cur);
  1007. *cur = next;
  1008. return true;
  1009. }
  1010. cur = &(*cur)->Next;
  1011. }
  1012. return false;
  1013. }
  1014. CPreprocessor::Token CPreprocessor::Parse (const Token &iSource)
  1015. {
  1016. Source = iSource.String;
  1017. SourceEnd = Source + iSource.Length;
  1018. Line = 1;
  1019. BOL = true;
  1020. EnableOutput = 1;
  1021. // Accumulate output into this token
  1022. Token output (Token::TK_TEXT);
  1023. int empty_lines = 0;
  1024. // Enable output only if all embedded #if's were true
  1025. bool old_output_enabled = true;
  1026. bool output_enabled = true;
  1027. int output_disabled_line = 0;
  1028. while (Source < SourceEnd)
  1029. {
  1030. int old_line = Line;
  1031. Token t = GetToken (true);
  1032. NextToken:
  1033. switch (t.Type)
  1034. {
  1035. case Token::TK_ERROR:
  1036. return t;
  1037. case Token::TK_EOS:
  1038. return output; // Force termination
  1039. case Token::TK_COMMENT:
  1040. // C comments are replaced with single spaces.
  1041. if (output_enabled)
  1042. {
  1043. output.Append (" ", 1);
  1044. output.AppendNL (Line - old_line);
  1045. }
  1046. break;
  1047. case Token::TK_LINECOMMENT:
  1048. // C++ comments are ignored
  1049. continue;
  1050. case Token::TK_DIRECTIVE:
  1051. // Handle preprocessor directives
  1052. t = HandleDirective (t, old_line);
  1053. output_enabled = ((EnableOutput & (EnableOutput + 1)) == 0);
  1054. if (output_enabled != old_output_enabled)
  1055. {
  1056. if (output_enabled)
  1057. output.AppendNL (old_line - output_disabled_line);
  1058. else
  1059. output_disabled_line = old_line;
  1060. old_output_enabled = output_enabled;
  1061. }
  1062. if (output_enabled)
  1063. output.AppendNL (Line - old_line - t.CountNL ());
  1064. goto NextToken;
  1065. case Token::TK_LINECONT:
  1066. // Backslash-Newline sequences are deleted, no matter where.
  1067. empty_lines++;
  1068. break;
  1069. case Token::TK_NEWLINE:
  1070. if (empty_lines)
  1071. {
  1072. // Compensate for the backslash-newline combinations
  1073. // we have encountered, otherwise line numeration is broken
  1074. if (output_enabled)
  1075. output.AppendNL (empty_lines);
  1076. empty_lines = 0;
  1077. }
  1078. // Fallthrough to default
  1079. case Token::TK_WHITESPACE:
  1080. // Fallthrough to default
  1081. default:
  1082. // Passthrough all other tokens
  1083. if (output_enabled)
  1084. output.Append (t);
  1085. break;
  1086. }
  1087. }
  1088. if (EnableOutput != 1)
  1089. {
  1090. Error (Line, "Unclosed #if at end of source");
  1091. return Token (Token::TK_ERROR);
  1092. }
  1093. return output;
  1094. }
  1095. char *CPreprocessor::Parse (const char *iSource, size_t iLength, size_t &oLength)
  1096. {
  1097. Token retval = Parse (Token (Token::TK_TEXT, iSource, iLength));
  1098. if (retval.Type == Token::TK_ERROR)
  1099. return NULL;
  1100. oLength = retval.Length;
  1101. retval.Allocated = 0;
  1102. return retval.Buffer;
  1103. }
  1104. } // namespace Ogre