PageRenderTime 59ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/src/qt/qtbase/src/tools/qdoc/yyindent.cpp

https://gitlab.com/x33n/phantomjs
C++ | 1190 lines | 538 code | 119 blank | 533 comment | 180 complexity | 1dff98ce12742e8c26fc6739ede25494 MD5 | raw file
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
  4. ** Contact: http://www.qt-project.org/legal
  5. **
  6. ** This file is part of the tools applications of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and Digia. For licensing terms and
  14. ** conditions see http://qt.digia.com/licensing. For further information
  15. ** use the contact form at http://qt.digia.com/contact-us.
  16. **
  17. ** GNU Lesser General Public License Usage
  18. ** Alternatively, this file may be used under the terms of the GNU Lesser
  19. ** General Public License version 2.1 as published by the Free Software
  20. ** Foundation and appearing in the file LICENSE.LGPL included in the
  21. ** packaging of this file. Please review the following information to
  22. ** ensure the GNU Lesser General Public License version 2.1 requirements
  23. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  24. **
  25. ** In addition, as a special exception, Digia gives you certain additional
  26. ** rights. These rights are described in the Digia Qt LGPL Exception
  27. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  28. **
  29. ** GNU General Public License Usage
  30. ** Alternatively, this file may be used under the terms of the GNU
  31. ** General Public License version 3.0 as published by the Free Software
  32. ** Foundation and appearing in the file LICENSE.GPL included in the
  33. ** packaging of this file. Please review the following information to
  34. ** ensure the GNU General Public License version 3.0 requirements will be
  35. ** met: http://www.gnu.org/copyleft/gpl.html.
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. /*
  42. This file is a self-contained interactive indenter for C++ and Qt
  43. Script.
  44. The general problem of indenting a C++ program is ill posed. On
  45. the one hand, an indenter has to analyze programs written in a
  46. free-form formal language that is best described in terms of
  47. tokens, not characters, not lines. On the other hand, indentation
  48. applies to lines and white space characters matter, and otherwise
  49. the programs to indent are formally invalid in general, as they
  50. are begin edited.
  51. The approach taken here works line by line. We receive a program
  52. consisting of N lines or more, and we want to compute the
  53. indentation appropriate for the Nth line. Lines beyond the Nth
  54. lines are of no concern to us, so for simplicity we pretend the
  55. program has exactly N lines and we call the Nth line the "bottom
  56. line". Typically, we have to indent the bottom line when it's
  57. still empty, so we concentrate our analysis on the N - 1 lines
  58. that precede.
  59. By inspecting the (N - 1)-th line, the (N - 2)-th line, ...
  60. backwards, we determine the kind of the bottom line and indent it
  61. accordingly.
  62. * The bottom line is a comment line. See
  63. bottomLineStartsInCComment() and
  64. indentWhenBottomLineStartsInCComment().
  65. * The bottom line is a continuation line. See isContinuationLine()
  66. and indentForContinuationLine().
  67. * The bottom line is a standalone line. See
  68. indentForStandaloneLine().
  69. Certain tokens that influence the indentation, notably braces,
  70. are looked for in the lines. This is done by simple string
  71. comparison, without a real tokenizer. Confusing constructs such
  72. as comments and string literals are removed beforehand.
  73. */
  74. #include <qregexp.h>
  75. #include <qstringlist.h>
  76. QT_BEGIN_NAMESPACE
  77. /* qmake ignore Q_OBJECT */
  78. /*
  79. The indenter avoids getting stuck in almost infinite loops by
  80. imposing arbitrary limits on the number of lines it analyzes when
  81. looking for a construct.
  82. For example, the indenter never considers more than BigRoof lines
  83. backwards when looking for the start of a C-style comment.
  84. */
  85. static const int SmallRoof = 40;
  86. static const int BigRoof = 400;
  87. /*
  88. The indenter supports a few parameters:
  89. * ppHardwareTabSize is the size of a '\t' in your favorite editor.
  90. * ppIndentSize is the size of an indentation, or software tab
  91. size.
  92. * ppContinuationIndentSize is the extra indent for a continuation
  93. line, when there is nothing to align against on the previous
  94. line.
  95. * ppCommentOffset is the indentation within a C-style comment,
  96. when it cannot be picked up.
  97. */
  98. static int ppHardwareTabSize = 8;
  99. static int ppIndentSize = 4;
  100. static int ppContinuationIndentSize = 8;
  101. static const int ppCommentOffset = 2;
  102. void setTabSize( int size )
  103. {
  104. ppHardwareTabSize = size;
  105. }
  106. void setIndentSize( int size )
  107. {
  108. ppIndentSize = size;
  109. ppContinuationIndentSize = 2 * size;
  110. }
  111. static QRegExp *literal = 0;
  112. static QRegExp *label = 0;
  113. static QRegExp *inlineCComment = 0;
  114. static QRegExp *braceX = 0;
  115. static QRegExp *iflikeKeyword = 0;
  116. /*
  117. Returns the first non-space character in the string t, or
  118. QChar::Null if the string is made only of white space.
  119. */
  120. static QChar firstNonWhiteSpace( const QString& t )
  121. {
  122. int i = 0;
  123. while ( i < (int) t.length() ) {
  124. if ( !t[i].isSpace() )
  125. return t[i];
  126. i++;
  127. }
  128. return QChar::Null;
  129. }
  130. /*
  131. Returns \c true if string t is made only of white space; otherwise
  132. returns \c false.
  133. */
  134. static bool isOnlyWhiteSpace( const QString& t )
  135. {
  136. return firstNonWhiteSpace( t ).isNull();
  137. }
  138. /*
  139. Assuming string t is a line, returns the column number of a given
  140. index. Column numbers and index are identical for strings that don't
  141. contain '\t's.
  142. */
  143. int columnForIndex( const QString& t, int index )
  144. {
  145. int col = 0;
  146. if ( index > (int) t.length() )
  147. index = t.length();
  148. for ( int i = 0; i < index; i++ ) {
  149. if ( t[i] == QChar('\t') ) {
  150. col = ( (col / ppHardwareTabSize) + 1 ) * ppHardwareTabSize;
  151. } else {
  152. col++;
  153. }
  154. }
  155. return col;
  156. }
  157. /*
  158. Returns the indentation size of string t.
  159. */
  160. int indentOfLine( const QString& t )
  161. {
  162. return columnForIndex( t, t.indexOf(firstNonWhiteSpace(t)) );
  163. }
  164. /*
  165. Replaces t[k] by ch, unless t[k] is '\t'. Tab characters are better
  166. left alone since they break the "index equals column" rule. No
  167. provisions are taken against '\n' or '\r', which shouldn't occur in
  168. t anyway.
  169. */
  170. static inline void eraseChar( QString& t, int k, QChar ch )
  171. {
  172. if ( t[k] != '\t' )
  173. t[k] = ch;
  174. }
  175. /*
  176. Removes some nefast constructs from a code line and returns the
  177. resulting line.
  178. */
  179. static QString trimmedCodeLine( const QString& t )
  180. {
  181. QString trimmed = t;
  182. int k;
  183. /*
  184. Replace character and string literals by X's, since they may
  185. contain confusing characters (such as '{' and ';'). "Hello!" is
  186. replaced by XXXXXXXX. The literals are rigourously of the same
  187. length before and after; otherwise, we would break alignment of
  188. continuation lines.
  189. */
  190. k = 0;
  191. while ( (k = trimmed.indexOf(*literal, k)) != -1 ) {
  192. for ( int i = 0; i < literal->matchedLength(); i++ )
  193. eraseChar( trimmed, k + i, 'X' );
  194. k += literal->matchedLength();
  195. }
  196. /*
  197. Replace inline C-style comments by spaces. Other comments are
  198. handled elsewhere.
  199. */
  200. k = 0;
  201. while ( (k = trimmed.indexOf(*inlineCComment, k)) != -1 ) {
  202. for ( int i = 0; i < inlineCComment->matchedLength(); i++ )
  203. eraseChar( trimmed, k + i, ' ' );
  204. k += inlineCComment->matchedLength();
  205. }
  206. /*
  207. Replace goto and switch labels by whitespace, but be careful
  208. with this case:
  209. foo1: bar1;
  210. bar2;
  211. */
  212. while ( trimmed.lastIndexOf(':') != -1 && trimmed.indexOf(*label) != -1 ) {
  213. QString cap1 = label->cap( 1 );
  214. int pos1 = label->pos( 1 );
  215. int stop = cap1.length();
  216. if ( pos1 + stop < (int) trimmed.length() && ppIndentSize < stop )
  217. stop = ppIndentSize;
  218. int i = 0;
  219. while ( i < stop ) {
  220. eraseChar( trimmed, pos1 + i, ' ' );
  221. i++;
  222. }
  223. while ( i < (int) cap1.length() ) {
  224. eraseChar( trimmed, pos1 + i, ';' );
  225. i++;
  226. }
  227. }
  228. /*
  229. Remove C++-style comments.
  230. */
  231. k = trimmed.indexOf( "//" );
  232. if ( k != -1 )
  233. trimmed.truncate( k );
  234. return trimmed;
  235. }
  236. /*
  237. Returns '(' if the last parenthesis is opening, ')' if it is
  238. closing, and QChar::Null if there are no parentheses in t.
  239. */
  240. static inline QChar lastParen( const QString& t )
  241. {
  242. int i = t.length();
  243. while ( i > 0 ) {
  244. i--;
  245. if ( t[i] == QChar('(') || t[i] == QChar(')') )
  246. return t[i];
  247. }
  248. return QChar::Null;
  249. }
  250. /*
  251. Returns \c true if typedIn the same as okayCh or is null; otherwise
  252. returns \c false.
  253. */
  254. static inline bool okay( QChar typedIn, QChar okayCh )
  255. {
  256. return typedIn == QChar::Null || typedIn == okayCh;
  257. }
  258. /*
  259. The "linizer" is a group of functions and variables to iterate
  260. through the source code of the program to indent. The program is
  261. given as a list of strings, with the bottom line being the line
  262. to indent. The actual program might contain extra lines, but
  263. those are uninteresting and not passed over to us.
  264. */
  265. struct LinizerState
  266. {
  267. QString line;
  268. int braceDepth;
  269. bool leftBraceFollows;
  270. QStringList::ConstIterator iter;
  271. bool inCComment;
  272. bool pendingRightBrace;
  273. };
  274. static QStringList *yyProgram = 0;
  275. static LinizerState *yyLinizerState = 0;
  276. // shorthands
  277. static const QString *yyLine = 0;
  278. static const int *yyBraceDepth = 0;
  279. static const bool *yyLeftBraceFollows = 0;
  280. /*
  281. Saves and restores the state of the global linizer. This enables
  282. backtracking.
  283. */
  284. #define YY_SAVE() \
  285. LinizerState savedState = *yyLinizerState
  286. #define YY_RESTORE() \
  287. *yyLinizerState = savedState
  288. /*
  289. Advances to the previous line in yyProgram and update yyLine
  290. accordingly. yyLine is cleaned from comments and other damageable
  291. constructs. Empty lines are skipped.
  292. */
  293. static bool readLine()
  294. {
  295. int k;
  296. yyLinizerState->leftBraceFollows =
  297. ( firstNonWhiteSpace(yyLinizerState->line) == QChar('{') );
  298. do {
  299. if ( yyLinizerState->iter == yyProgram->constBegin() ) {
  300. yyLinizerState->line.clear();
  301. return false;
  302. }
  303. --yyLinizerState->iter;
  304. yyLinizerState->line = *yyLinizerState->iter;
  305. yyLinizerState->line = trimmedCodeLine( yyLinizerState->line );
  306. /*
  307. Remove C-style comments that span multiple lines. If the
  308. bottom line starts in a C-style comment, we are not aware
  309. of that and eventually yyLine will contain a slash-aster.
  310. Notice that both if's can be executed, since
  311. yyLinizerState->inCComment is potentially set to false in
  312. the first if. The order of the if's is also important.
  313. */
  314. if ( yyLinizerState->inCComment ) {
  315. QString slashAster( "/*" );
  316. k = yyLinizerState->line.indexOf( slashAster );
  317. if ( k == -1 ) {
  318. yyLinizerState->line.clear();
  319. } else {
  320. yyLinizerState->line.truncate( k );
  321. yyLinizerState->inCComment = false;
  322. }
  323. }
  324. if ( !yyLinizerState->inCComment ) {
  325. QString asterSlash( "*/" );
  326. k = yyLinizerState->line.indexOf( asterSlash );
  327. if ( k != -1 ) {
  328. for ( int i = 0; i < k + 2; i++ )
  329. eraseChar( yyLinizerState->line, i, ' ' );
  330. yyLinizerState->inCComment = true;
  331. }
  332. }
  333. /*
  334. Remove preprocessor directives.
  335. */
  336. k = 0;
  337. while ( k < (int) yyLinizerState->line.length() ) {
  338. QChar ch = yyLinizerState->line[k];
  339. if ( ch == QChar('#') ) {
  340. yyLinizerState->line.clear();
  341. } else if ( !ch.isSpace() ) {
  342. break;
  343. }
  344. k++;
  345. }
  346. /*
  347. Remove trailing spaces.
  348. */
  349. k = yyLinizerState->line.length();
  350. while ( k > 0 && yyLinizerState->line[k - 1].isSpace() )
  351. k--;
  352. yyLinizerState->line.truncate( k );
  353. /*
  354. '}' increment the brace depth and '{' decrements it and not
  355. the other way around, as we are parsing backwards.
  356. */
  357. yyLinizerState->braceDepth +=
  358. yyLinizerState->line.count( '}' ) -
  359. yyLinizerState->line.count( '{' );
  360. /*
  361. We use a dirty trick for
  362. } else ...
  363. We don't count the '}' yet, so that it's more or less
  364. equivalent to the friendly construct
  365. }
  366. else ...
  367. */
  368. if ( yyLinizerState->pendingRightBrace )
  369. yyLinizerState->braceDepth++;
  370. yyLinizerState->pendingRightBrace =
  371. ( yyLinizerState->line.indexOf(*braceX) == 0 );
  372. if ( yyLinizerState->pendingRightBrace )
  373. yyLinizerState->braceDepth--;
  374. } while ( yyLinizerState->line.isEmpty() );
  375. return true;
  376. }
  377. /*
  378. Resets the linizer to its initial state, with yyLine containing the
  379. line above the bottom line of the program.
  380. */
  381. static void startLinizer()
  382. {
  383. yyLinizerState->braceDepth = 0;
  384. yyLinizerState->inCComment = false;
  385. yyLinizerState->pendingRightBrace = false;
  386. yyLine = &yyLinizerState->line;
  387. yyBraceDepth = &yyLinizerState->braceDepth;
  388. yyLeftBraceFollows = &yyLinizerState->leftBraceFollows;
  389. yyLinizerState->iter = yyProgram->constEnd();
  390. --yyLinizerState->iter;
  391. yyLinizerState->line = *yyLinizerState->iter;
  392. readLine();
  393. }
  394. /*
  395. Returns \c true if the start of the bottom line of yyProgram (and
  396. potentially the whole line) is part of a C-style comment;
  397. otherwise returns \c false.
  398. */
  399. static bool bottomLineStartsInCComment()
  400. {
  401. QString slashAster( "/*" );
  402. QString asterSlash( "*/" );
  403. /*
  404. We could use the linizer here, but that would slow us down
  405. terribly. We are better to trim only the code lines we need.
  406. */
  407. QStringList::ConstIterator p = yyProgram->constEnd();
  408. --p; // skip bottom line
  409. for ( int i = 0; i < BigRoof; i++ ) {
  410. if ( p == yyProgram->constBegin() )
  411. return false;
  412. --p;
  413. if ( (*p).indexOf(slashAster) != -1 || (*p).indexOf(asterSlash) != -1 ) {
  414. QString trimmed = trimmedCodeLine( *p );
  415. if ( trimmed.indexOf(slashAster) != -1 ) {
  416. return true;
  417. } else if ( trimmed.indexOf(asterSlash) != -1 ) {
  418. return false;
  419. }
  420. }
  421. }
  422. return false;
  423. }
  424. /*
  425. Returns the recommended indent for the bottom line of yyProgram
  426. assuming that it starts in a C-style comment, a condition that is
  427. tested elsewhere.
  428. Essentially, we're trying to align against some text on the
  429. previous line.
  430. */
  431. static int indentWhenBottomLineStartsInCComment()
  432. {
  433. int k = yyLine->lastIndexOf( "/*" );
  434. if ( k == -1 ) {
  435. /*
  436. We found a normal text line in a comment. Align the
  437. bottom line with the text on this line.
  438. */
  439. return indentOfLine( *yyLine );
  440. } else {
  441. /*
  442. The C-style comment starts on this line. If there is
  443. text on the same line, align with it. Otherwise, align
  444. with the slash-aster plus a given offset.
  445. */
  446. int indent = columnForIndex( *yyLine, k );
  447. k += 2;
  448. while ( k < (int) yyLine->length() ) {
  449. if ( !(*yyLine)[k].isSpace() )
  450. return columnForIndex( *yyLine, k );
  451. k++;
  452. }
  453. return indent + ppCommentOffset;
  454. }
  455. }
  456. /*
  457. A function called match...() modifies the linizer state. If it
  458. returns \c true, yyLine is the top line of the matched construct;
  459. otherwise, the linizer is left in an unknown state.
  460. A function called is...() keeps the linizer state intact.
  461. */
  462. /*
  463. Returns \c true if the current line (and upwards) forms a braceless
  464. control statement; otherwise returns \c false.
  465. The first line of the following example is a "braceless control
  466. statement":
  467. if ( x )
  468. y;
  469. */
  470. static bool matchBracelessControlStatement()
  471. {
  472. int delimDepth = 0;
  473. if ( yyLine->endsWith("else") )
  474. return true;
  475. if ( !yyLine->endsWith(QLatin1Char(')')) )
  476. return false;
  477. for ( int i = 0; i < SmallRoof; i++ ) {
  478. int j = yyLine->length();
  479. while ( j > 0 ) {
  480. j--;
  481. QChar ch = (*yyLine)[j];
  482. switch ( ch.unicode() ) {
  483. case ')':
  484. delimDepth++;
  485. break;
  486. case '(':
  487. delimDepth--;
  488. if ( delimDepth == 0 ) {
  489. if ( yyLine->indexOf(*iflikeKeyword) != -1 ) {
  490. /*
  491. We have
  492. if ( x )
  493. y
  494. "if ( x )" is not part of the statement
  495. "y".
  496. */
  497. return true;
  498. }
  499. }
  500. if ( delimDepth == -1 ) {
  501. /*
  502. We have
  503. if ( (1 +
  504. 2)
  505. and not
  506. if ( 1 +
  507. 2 )
  508. */
  509. return false;
  510. }
  511. break;
  512. case '{':
  513. case '}':
  514. case ';':
  515. /*
  516. We met a statement separator, but not where we
  517. expected it. What follows is probably a weird
  518. continuation line. Be careful with ';' in for,
  519. though.
  520. */
  521. if ( ch != QChar(';') || delimDepth == 0 )
  522. return false;
  523. }
  524. }
  525. if ( !readLine() )
  526. break;
  527. }
  528. return false;
  529. }
  530. /*
  531. Returns \c true if yyLine is an unfinished line; otherwise returns
  532. false.
  533. In many places we'll use the terms "standalone line", "unfinished
  534. line" and "continuation line". The meaning of these should be
  535. evident from this code example:
  536. a = b; // standalone line
  537. c = d + // unfinished line
  538. e + // unfinished continuation line
  539. f + // unfinished continuation line
  540. g; // continuation line
  541. */
  542. static bool isUnfinishedLine()
  543. {
  544. bool unf = false;
  545. YY_SAVE();
  546. if ( yyLine->isEmpty() )
  547. return false;
  548. QChar lastCh = (*yyLine)[(int) yyLine->length() - 1];
  549. if ( QString("{};").indexOf(lastCh) == -1 && !yyLine->endsWith("...") ) {
  550. /*
  551. It doesn't end with ';' or similar. If it's neither
  552. "Q_OBJECT" nor "if ( x )", it must be an unfinished line.
  553. */
  554. unf = ( yyLine->indexOf("Q_OBJECT") == -1 &&
  555. !matchBracelessControlStatement() );
  556. } else if ( lastCh == QChar(';') ) {
  557. if ( lastParen(*yyLine) == QChar('(') ) {
  558. /*
  559. Exception:
  560. for ( int i = 1; i < 10;
  561. */
  562. unf = true;
  563. } else if ( readLine() && yyLine->endsWith(QLatin1Char(';')) &&
  564. lastParen(*yyLine) == QChar('(') ) {
  565. /*
  566. Exception:
  567. for ( int i = 1;
  568. i < 10;
  569. */
  570. unf = true;
  571. }
  572. }
  573. YY_RESTORE();
  574. return unf;
  575. }
  576. /*
  577. Returns \c true if yyLine is a continuation line; otherwise returns
  578. false.
  579. */
  580. static bool isContinuationLine()
  581. {
  582. bool cont = false;
  583. YY_SAVE();
  584. if ( readLine() )
  585. cont = isUnfinishedLine();
  586. YY_RESTORE();
  587. return cont;
  588. }
  589. /*
  590. Returns the recommended indent for the bottom line of yyProgram,
  591. assuming it's a continuation line.
  592. We're trying to align the continuation line against some parenthesis
  593. or other bracked left opened on a previous line, or some interesting
  594. operator such as '='.
  595. */
  596. static int indentForContinuationLine()
  597. {
  598. int braceDepth = 0;
  599. int delimDepth = 0;
  600. bool leftBraceFollowed = *yyLeftBraceFollows;
  601. for ( int i = 0; i < SmallRoof; i++ ) {
  602. int hook = -1;
  603. int j = yyLine->length();
  604. while ( j > 0 && hook < 0 ) {
  605. j--;
  606. QChar ch = (*yyLine)[j];
  607. switch ( ch.unicode() ) {
  608. case ')':
  609. case ']':
  610. delimDepth++;
  611. break;
  612. case '}':
  613. braceDepth++;
  614. break;
  615. case '(':
  616. case '[':
  617. delimDepth--;
  618. /*
  619. An unclosed delimiter is a good place to align at,
  620. at least for some styles (including Qt's).
  621. */
  622. if ( delimDepth == -1 )
  623. hook = j;
  624. break;
  625. case '{':
  626. braceDepth--;
  627. /*
  628. A left brace followed by other stuff on the same
  629. line is typically for an enum or an initializer.
  630. Such a brace must be treated just like the other
  631. delimiters.
  632. */
  633. if ( braceDepth == -1 ) {
  634. if ( j < (int) yyLine->length() - 1 ) {
  635. hook = j;
  636. } else {
  637. return 0; // shouldn't happen
  638. }
  639. }
  640. break;
  641. case '=':
  642. /*
  643. An equal sign is a very natural alignment hook
  644. because it's usually the operator with the lowest
  645. precedence in statements it appears in. Case in
  646. point:
  647. int x = 1 +
  648. 2;
  649. However, we have to beware of constructs such as
  650. default arguments and explicit enum constant
  651. values:
  652. void foo( int x = 0,
  653. int y = 0 );
  654. And not
  655. void foo( int x = 0,
  656. int y = 0 );
  657. These constructs are caracterized by a ',' at the
  658. end of the unfinished lines or by unbalanced
  659. parentheses.
  660. */
  661. if ( QString("!=<>").indexOf((*yyLine)[j - 1]) == -1 &&
  662. (*yyLine)[j + 1] != '=' ) {
  663. if ( braceDepth == 0 && delimDepth == 0 &&
  664. j < (int) yyLine->length() - 1 &&
  665. !yyLine->endsWith(QLatin1Char(',')) &&
  666. (yyLine->contains('(') == yyLine->contains(')')) )
  667. hook = j;
  668. }
  669. }
  670. }
  671. if ( hook >= 0 ) {
  672. /*
  673. Yes, we have a delimiter or an operator to align
  674. against! We don't really align against it, but rather
  675. against the following token, if any. In this example,
  676. the following token is "11":
  677. int x = ( 11 +
  678. 2 );
  679. If there is no such token, we use a continuation indent:
  680. static QRegExp foo( QString(
  681. "foo foo foo foo foo foo foo foo foo") );
  682. */
  683. hook++;
  684. while ( hook < (int) yyLine->length() ) {
  685. if ( !(*yyLine)[hook].isSpace() )
  686. return columnForIndex( *yyLine, hook );
  687. hook++;
  688. }
  689. return indentOfLine( *yyLine ) + ppContinuationIndentSize;
  690. }
  691. if ( braceDepth != 0 )
  692. break;
  693. /*
  694. The line's delimiters are balanced. It looks like a
  695. continuation line or something.
  696. */
  697. if ( delimDepth == 0 ) {
  698. if ( leftBraceFollowed ) {
  699. /*
  700. We have
  701. int main()
  702. {
  703. or
  704. Bar::Bar()
  705. : Foo( x )
  706. {
  707. The "{" should be flush left.
  708. */
  709. if ( !isContinuationLine() )
  710. return indentOfLine( *yyLine );
  711. } else if ( isContinuationLine() || yyLine->endsWith(QLatin1Char(',')) ) {
  712. /*
  713. We have
  714. x = a +
  715. b +
  716. c;
  717. or
  718. int t[] = {
  719. 1, 2, 3,
  720. 4, 5, 6
  721. The "c;" should fall right under the "b +", and the
  722. "4, 5, 6" right under the "1, 2, 3,".
  723. */
  724. return indentOfLine( *yyLine );
  725. } else {
  726. /*
  727. We have
  728. stream << 1 +
  729. 2;
  730. We could, but we don't, try to analyze which
  731. operator has precedence over which and so on, to
  732. obtain the excellent result
  733. stream << 1 +
  734. 2;
  735. We do have a special trick above for the assignment
  736. operator above, though.
  737. */
  738. return indentOfLine( *yyLine ) + ppContinuationIndentSize;
  739. }
  740. }
  741. if ( !readLine() )
  742. break;
  743. }
  744. return 0;
  745. }
  746. /*
  747. Returns the recommended indent for the bottom line of yyProgram if
  748. that line is standalone (or should be indented likewise).
  749. Indenting a standalone line is tricky, mostly because of braceless
  750. control statements. Grossly, we are looking backwards for a special
  751. line, a "hook line", that we can use as a starting point to indent,
  752. and then modify the indentation level according to the braces met
  753. along the way to that hook.
  754. Let's consider a few examples. In all cases, we want to indent the
  755. bottom line.
  756. Example 1:
  757. x = 1;
  758. y = 2;
  759. The hook line is "x = 1;". We met 0 opening braces and 0 closing
  760. braces. Therefore, "y = 2;" inherits the indent of "x = 1;".
  761. Example 2:
  762. if ( x ) {
  763. y;
  764. The hook line is "if ( x ) {". No matter what precedes it, "y;" has
  765. to be indented one level deeper than the hook line, since we met one
  766. opening brace along the way.
  767. Example 3:
  768. if ( a )
  769. while ( b ) {
  770. c;
  771. }
  772. d;
  773. To indent "d;" correctly, we have to go as far as the "if ( a )".
  774. Compare with
  775. if ( a ) {
  776. while ( b ) {
  777. c;
  778. }
  779. d;
  780. Still, we're striving to go back as little as possible to
  781. accommodate people with irregular indentation schemes. A hook line
  782. near at hand is much more reliable than a remote one.
  783. */
  784. static int indentForStandaloneLine()
  785. {
  786. for ( int i = 0; i < SmallRoof; i++ ) {
  787. if ( !*yyLeftBraceFollows ) {
  788. YY_SAVE();
  789. if ( matchBracelessControlStatement() ) {
  790. /*
  791. The situation is this, and we want to indent "z;":
  792. if ( x &&
  793. y )
  794. z;
  795. yyLine is "if ( x &&".
  796. */
  797. return indentOfLine( *yyLine ) + ppIndentSize;
  798. }
  799. YY_RESTORE();
  800. }
  801. if ( yyLine->endsWith(QLatin1Char(';')) || yyLine->contains('{') ) {
  802. /*
  803. The situation is possibly this, and we want to indent
  804. "z;":
  805. while ( x )
  806. y;
  807. z;
  808. We return the indent of "while ( x )". In place of "y;",
  809. any arbitrarily complex compound statement can appear.
  810. */
  811. if ( *yyBraceDepth > 0 ) {
  812. do {
  813. if ( !readLine() )
  814. break;
  815. } while ( *yyBraceDepth > 0 );
  816. }
  817. LinizerState hookState;
  818. while ( isContinuationLine() )
  819. readLine();
  820. hookState = *yyLinizerState;
  821. readLine();
  822. if ( *yyBraceDepth <= 0 ) {
  823. do {
  824. if ( !matchBracelessControlStatement() )
  825. break;
  826. hookState = *yyLinizerState;
  827. } while ( readLine() );
  828. }
  829. *yyLinizerState = hookState;
  830. while ( isContinuationLine() )
  831. readLine();
  832. /*
  833. Never trust lines containing only '{' or '}', as some
  834. people (Richard M. Stallman) format them weirdly.
  835. */
  836. if ( yyLine->trimmed().length() > 1 )
  837. return indentOfLine( *yyLine ) - *yyBraceDepth * ppIndentSize;
  838. }
  839. if ( !readLine() )
  840. return -*yyBraceDepth * ppIndentSize;
  841. }
  842. return 0;
  843. }
  844. /*
  845. Constructs global variables used by the indenter.
  846. */
  847. static void initializeIndenter()
  848. {
  849. literal = new QRegExp( "([\"'])(?:\\\\.|[^\\\\])*\\1" );
  850. literal->setMinimal( true );
  851. label = new QRegExp(
  852. "^\\s*((?:case\\b([^:]|::)+|[a-zA-Z_0-9]+)(?:\\s+slots)?:)(?!:)" );
  853. inlineCComment = new QRegExp( "/\\*.*\\*/" );
  854. inlineCComment->setMinimal( true );
  855. braceX = new QRegExp( "^\\s*\\}\\s*(?:else|catch)\\b" );
  856. iflikeKeyword = new QRegExp( "\\b(?:catch|do|for|if|while)\\b" );
  857. yyLinizerState = new LinizerState;
  858. }
  859. /*
  860. Destroys global variables used by the indenter.
  861. */
  862. static void terminateIndenter()
  863. {
  864. delete literal;
  865. delete label;
  866. delete inlineCComment;
  867. delete braceX;
  868. delete iflikeKeyword;
  869. delete yyLinizerState;
  870. }
  871. /*
  872. Returns the recommended indent for the bottom line of program.
  873. Unless null, typedIn stores the character of yyProgram that
  874. triggered reindentation.
  875. This function works better if typedIn is set properly; it is
  876. slightly more conservative if typedIn is completely wild, and
  877. slighly more liberal if typedIn is always null. The user might be
  878. annoyed by the liberal behavior.
  879. */
  880. int indentForBottomLine( const QStringList& program, QChar typedIn )
  881. {
  882. if ( program.isEmpty() )
  883. return 0;
  884. initializeIndenter();
  885. yyProgram = new QStringList( program );
  886. startLinizer();
  887. const QString& bottomLine = program.last();
  888. QChar firstCh = firstNonWhiteSpace( bottomLine );
  889. int indent;
  890. if ( bottomLineStartsInCComment() ) {
  891. /*
  892. The bottom line starts in a C-style comment. Indent it
  893. smartly, unless the user has already played around with it,
  894. in which case it's better to leave her stuff alone.
  895. */
  896. if ( isOnlyWhiteSpace(bottomLine) ) {
  897. indent = indentWhenBottomLineStartsInCComment();
  898. } else {
  899. indent = indentOfLine( bottomLine );
  900. }
  901. } else if ( okay(typedIn, '#') && firstCh == QChar('#') ) {
  902. /*
  903. Preprocessor directives go flush left.
  904. */
  905. indent = 0;
  906. } else {
  907. if ( isUnfinishedLine() ) {
  908. indent = indentForContinuationLine();
  909. } else {
  910. indent = indentForStandaloneLine();
  911. }
  912. if ( okay(typedIn, '}') && firstCh == QChar('}') ) {
  913. /*
  914. A closing brace is one level more to the left than the
  915. code it follows.
  916. */
  917. indent -= ppIndentSize;
  918. } else if ( okay(typedIn, ':') ) {
  919. QRegExp caseLabel(
  920. "\\s*(?:case\\b(?:[^:]|::)+"
  921. "|(?:public|protected|private|signals|default)(?:\\s+slots)?\\s*"
  922. ")?:.*" );
  923. if ( caseLabel.exactMatch(bottomLine) ) {
  924. /*
  925. Move a case label (or the ':' in front of a
  926. constructor initialization list) one level to the
  927. left, but only if the user did not play around with
  928. it yet. Some users have exotic tastes in the
  929. matter, and most users probably are not patient
  930. enough to wait for the final ':' to format their
  931. code properly.
  932. We don't attempt the same for goto labels, as the
  933. user is probably the middle of "foo::bar". (Who
  934. uses goto, anyway?)
  935. */
  936. if ( indentOfLine(bottomLine) <= indent )
  937. indent -= ppIndentSize;
  938. else
  939. indent = indentOfLine( bottomLine );
  940. }
  941. }
  942. }
  943. delete yyProgram;
  944. terminateIndenter();
  945. return qMax( 0, indent );
  946. }
  947. QT_END_NAMESPACE
  948. #ifdef Q_TEST_YYINDENT
  949. /*
  950. Test driver.
  951. */
  952. #include <qfile.h>
  953. #include <qtextstream.h>
  954. #include <errno.h>
  955. QT_BEGIN_NAMESPACE
  956. static QString fileContents( const QString& fileName )
  957. {
  958. QFile f( fileName );
  959. if ( !f.open(QFile::ReadOnly) ) {
  960. qWarning( "yyindent error: Cannot open file '%s' for reading: %s",
  961. fileName.toLatin1().data(), strerror(errno) );
  962. return QString();
  963. }
  964. QTextStream t( &f );
  965. QString contents = t.read();
  966. f.close();
  967. if ( contents.isEmpty() )
  968. qWarning( "yyindent error: File '%s' is empty", fileName.toLatin1().data() );
  969. return contents;
  970. }
  971. QT_END_NAMESPACE
  972. int main( int argc, char **argv )
  973. {
  974. QT_USE_NAMESPACE
  975. if ( argc != 2 ) {
  976. qWarning( "usage: yyindent file.cpp" );
  977. return 1;
  978. }
  979. QString code = fileContents( argv[1] );
  980. QStringList program = QStringList::split( '\n', code, true );
  981. QStringList p;
  982. QString out;
  983. while ( !program.isEmpty() && program.last().trimmed().isEmpty() )
  984. program.remove( program.fromLast() );
  985. QStringList::ConstIterator line = program.constBegin();
  986. while ( line != program.constEnd() ) {
  987. p.push_back( *line );
  988. QChar typedIn = firstNonWhiteSpace( *line );
  989. if ( p.last().endsWith(QLatin1Char(':')) )
  990. typedIn = ':';
  991. int indent = indentForBottomLine( p, typedIn );
  992. if ( !(*line).trimmed().isEmpty() ) {
  993. for ( int j = 0; j < indent; j++ )
  994. out += QLatin1Char(' ');
  995. out += (*line).trimmed();
  996. }
  997. out += QLatin1Char('\n');
  998. ++line;
  999. }
  1000. while ( out.endsWith(QLatin1Char('\n')) )
  1001. out.truncate( out.length() - 1 );
  1002. printf( "%s\n", out.toLatin1().data() );
  1003. return 0;
  1004. }
  1005. #endif // Q_TEST_YYINDENT