FormatTokenLexer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. //===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief This file implements FormatTokenLexer, which tokenizes a source file
  12. /// into a FormatToken stream suitable for ClangFormat.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "FormatTokenLexer.h"
  16. #include "FormatToken.h"
  17. #include "clang/Basic/SourceLocation.h"
  18. #include "clang/Basic/SourceManager.h"
  19. #include "clang/Format/Format.h"
  20. #include "llvm/Support/Regex.h"
  21. namespace clang {
  22. namespace format {
  23. FormatTokenLexer::FormatTokenLexer(const SourceManager &SourceMgr, FileID ID,
  24. const FormatStyle &Style,
  25. encoding::Encoding Encoding)
  26. : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}),
  27. Column(0), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
  28. Style(Style), IdentTable(getFormattingLangOpts(Style)),
  29. Keywords(IdentTable), Encoding(Encoding), FirstInLineIndex(0),
  30. FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin),
  31. MacroBlockEndRegex(Style.MacroBlockEnd) {
  32. Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
  33. getFormattingLangOpts(Style)));
  34. Lex->SetKeepWhitespaceMode(true);
  35. for (const std::string &ForEachMacro : Style.ForEachMacros)
  36. ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
  37. std::sort(ForEachMacros.begin(), ForEachMacros.end());
  38. }
  39. ArrayRef<FormatToken *> FormatTokenLexer::lex() {
  40. assert(Tokens.empty());
  41. assert(FirstInLineIndex == 0);
  42. do {
  43. Tokens.push_back(getNextToken());
  44. if (Style.Language == FormatStyle::LK_JavaScript) {
  45. tryParseJSRegexLiteral();
  46. handleTemplateStrings();
  47. }
  48. tryMergePreviousTokens();
  49. if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
  50. FirstInLineIndex = Tokens.size() - 1;
  51. } while (Tokens.back()->Tok.isNot(tok::eof));
  52. return Tokens;
  53. }
  54. void FormatTokenLexer::tryMergePreviousTokens() {
  55. if (tryMerge_TMacro())
  56. return;
  57. if (tryMergeConflictMarkers())
  58. return;
  59. if (tryMergeLessLess())
  60. return;
  61. if (tryMergeNSStringLiteral())
  62. return;
  63. if (Style.Language == FormatStyle::LK_JavaScript) {
  64. static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
  65. static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
  66. tok::equal};
  67. static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
  68. tok::greaterequal};
  69. static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
  70. static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
  71. static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
  72. tok::starequal};
  73. // FIXME: Investigate what token type gives the correct operator priority.
  74. if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
  75. return;
  76. if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
  77. return;
  78. if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
  79. return;
  80. if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
  81. return;
  82. if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
  83. return;
  84. if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
  85. Tokens.back()->Tok.setKind(tok::starequal);
  86. return;
  87. }
  88. }
  89. if (Style.Language == FormatStyle::LK_Java) {
  90. static const tok::TokenKind JavaRightLogicalShift[] = {
  91. tok::greater, tok::greater, tok::greater};
  92. static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
  93. tok::greater, tok::greater, tok::greaterequal};
  94. if (tryMergeTokens(JavaRightLogicalShift, TT_BinaryOperator))
  95. return;
  96. if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
  97. return;
  98. }
  99. }
  100. bool FormatTokenLexer::tryMergeNSStringLiteral() {
  101. if (Tokens.size() < 2)
  102. return false;
  103. auto &At = *(Tokens.end() - 2);
  104. auto &String = *(Tokens.end() - 1);
  105. if (!At->is(tok::at) || !String->is(tok::string_literal))
  106. return false;
  107. At->Tok.setKind(tok::string_literal);
  108. At->TokenText = StringRef(At->TokenText.begin(),
  109. String->TokenText.end() - At->TokenText.begin());
  110. At->ColumnWidth += String->ColumnWidth;
  111. At->Type = TT_ObjCStringLiteral;
  112. Tokens.erase(Tokens.end() - 1);
  113. return true;
  114. }
  115. bool FormatTokenLexer::tryMergeLessLess() {
  116. // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
  117. if (Tokens.size() < 3)
  118. return false;
  119. bool FourthTokenIsLess = false;
  120. if (Tokens.size() > 3)
  121. FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
  122. auto First = Tokens.end() - 3;
  123. if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
  124. First[0]->isNot(tok::less) || FourthTokenIsLess)
  125. return false;
  126. // Only merge if there currently is no whitespace between the two "<".
  127. if (First[1]->WhitespaceRange.getBegin() !=
  128. First[1]->WhitespaceRange.getEnd())
  129. return false;
  130. First[0]->Tok.setKind(tok::lessless);
  131. First[0]->TokenText = "<<";
  132. First[0]->ColumnWidth += 1;
  133. Tokens.erase(Tokens.end() - 2);
  134. return true;
  135. }
  136. bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
  137. TokenType NewType) {
  138. if (Tokens.size() < Kinds.size())
  139. return false;
  140. SmallVectorImpl<FormatToken *>::const_iterator First =
  141. Tokens.end() - Kinds.size();
  142. if (!First[0]->is(Kinds[0]))
  143. return false;
  144. unsigned AddLength = 0;
  145. for (unsigned i = 1; i < Kinds.size(); ++i) {
  146. if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
  147. First[i]->WhitespaceRange.getEnd())
  148. return false;
  149. AddLength += First[i]->TokenText.size();
  150. }
  151. Tokens.resize(Tokens.size() - Kinds.size() + 1);
  152. First[0]->TokenText = StringRef(First[0]->TokenText.data(),
  153. First[0]->TokenText.size() + AddLength);
  154. First[0]->ColumnWidth += AddLength;
  155. First[0]->Type = NewType;
  156. return true;
  157. }
  158. // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
  159. bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
  160. // NB: This is not entirely correct, as an r_paren can introduce an operand
  161. // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
  162. // corner case to not matter in practice, though.
  163. return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
  164. tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
  165. tok::colon, tok::question, tok::tilde) ||
  166. Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
  167. tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
  168. tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
  169. Tok->isBinaryOperator();
  170. }
  171. bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
  172. if (!Prev)
  173. return true;
  174. // Regex literals can only follow after prefix unary operators, not after
  175. // postfix unary operators. If the '++' is followed by a non-operand
  176. // introducing token, the slash here is the operand and not the start of a
  177. // regex.
  178. // `!` is an unary prefix operator, but also a post-fix operator that casts
  179. // away nullability, so the same check applies.
  180. if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
  181. return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
  182. // The previous token must introduce an operand location where regex
  183. // literals can occur.
  184. if (!precedesOperand(Prev))
  185. return false;
  186. return true;
  187. }
  188. // Tries to parse a JavaScript Regex literal starting at the current token,
  189. // if that begins with a slash and is in a location where JavaScript allows
  190. // regex literals. Changes the current token to a regex literal and updates
  191. // its text if successful.
  192. void FormatTokenLexer::tryParseJSRegexLiteral() {
  193. FormatToken *RegexToken = Tokens.back();
  194. if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
  195. return;
  196. FormatToken *Prev = nullptr;
  197. for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
  198. // NB: Because previous pointers are not initialized yet, this cannot use
  199. // Token.getPreviousNonComment.
  200. if ((*I)->isNot(tok::comment)) {
  201. Prev = *I;
  202. break;
  203. }
  204. }
  205. if (!canPrecedeRegexLiteral(Prev))
  206. return;
  207. // 'Manually' lex ahead in the current file buffer.
  208. const char *Offset = Lex->getBufferLocation();
  209. const char *RegexBegin = Offset - RegexToken->TokenText.size();
  210. StringRef Buffer = Lex->getBuffer();
  211. bool InCharacterClass = false;
  212. bool HaveClosingSlash = false;
  213. for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
  214. // Regular expressions are terminated with a '/', which can only be
  215. // escaped using '\' or a character class between '[' and ']'.
  216. // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
  217. switch (*Offset) {
  218. case '\\':
  219. // Skip the escaped character.
  220. ++Offset;
  221. break;
  222. case '[':
  223. InCharacterClass = true;
  224. break;
  225. case ']':
  226. InCharacterClass = false;
  227. break;
  228. case '/':
  229. if (!InCharacterClass)
  230. HaveClosingSlash = true;
  231. break;
  232. }
  233. }
  234. RegexToken->Type = TT_RegexLiteral;
  235. // Treat regex literals like other string_literals.
  236. RegexToken->Tok.setKind(tok::string_literal);
  237. RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
  238. RegexToken->ColumnWidth = RegexToken->TokenText.size();
  239. resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
  240. }
  241. void FormatTokenLexer::handleTemplateStrings() {
  242. FormatToken *BacktickToken = Tokens.back();
  243. if (BacktickToken->is(tok::l_brace)) {
  244. StateStack.push(LexerState::NORMAL);
  245. return;
  246. }
  247. if (BacktickToken->is(tok::r_brace)) {
  248. if (StateStack.size() == 1)
  249. return;
  250. StateStack.pop();
  251. if (StateStack.top() != LexerState::TEMPLATE_STRING)
  252. return;
  253. // If back in TEMPLATE_STRING, fallthrough and continue parsing the
  254. } else if (BacktickToken->is(tok::unknown) &&
  255. BacktickToken->TokenText == "`") {
  256. StateStack.push(LexerState::TEMPLATE_STRING);
  257. } else {
  258. return; // Not actually a template
  259. }
  260. // 'Manually' lex ahead in the current file buffer.
  261. const char *Offset = Lex->getBufferLocation();
  262. const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
  263. for (; Offset != Lex->getBuffer().end(); ++Offset) {
  264. if (Offset[0] == '`') {
  265. StateStack.pop();
  266. break;
  267. }
  268. if (Offset[0] == '\\') {
  269. ++Offset; // Skip the escaped character.
  270. } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
  271. Offset[1] == '{') {
  272. // '${' introduces an expression interpolation in the template string.
  273. StateStack.push(LexerState::NORMAL);
  274. ++Offset;
  275. break;
  276. }
  277. }
  278. StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
  279. BacktickToken->Type = TT_TemplateString;
  280. BacktickToken->Tok.setKind(tok::string_literal);
  281. BacktickToken->TokenText = LiteralText;
  282. // Adjust width for potentially multiline string literals.
  283. size_t FirstBreak = LiteralText.find('\n');
  284. StringRef FirstLineText = FirstBreak == StringRef::npos
  285. ? LiteralText
  286. : LiteralText.substr(0, FirstBreak);
  287. BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
  288. FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
  289. size_t LastBreak = LiteralText.rfind('\n');
  290. if (LastBreak != StringRef::npos) {
  291. BacktickToken->IsMultiline = true;
  292. unsigned StartColumn = 0; // The template tail spans the entire line.
  293. BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
  294. LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
  295. Style.TabWidth, Encoding);
  296. }
  297. SourceLocation loc = Offset < Lex->getBuffer().end()
  298. ? Lex->getSourceLocation(Offset + 1)
  299. : SourceMgr.getLocForEndOfFile(ID);
  300. resetLexer(SourceMgr.getFileOffset(loc));
  301. }
  302. bool FormatTokenLexer::tryMerge_TMacro() {
  303. if (Tokens.size() < 4)
  304. return false;
  305. FormatToken *Last = Tokens.back();
  306. if (!Last->is(tok::r_paren))
  307. return false;
  308. FormatToken *String = Tokens[Tokens.size() - 2];
  309. if (!String->is(tok::string_literal) || String->IsMultiline)
  310. return false;
  311. if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
  312. return false;
  313. FormatToken *Macro = Tokens[Tokens.size() - 4];
  314. if (Macro->TokenText != "_T")
  315. return false;
  316. const char *Start = Macro->TokenText.data();
  317. const char *End = Last->TokenText.data() + Last->TokenText.size();
  318. String->TokenText = StringRef(Start, End - Start);
  319. String->IsFirst = Macro->IsFirst;
  320. String->LastNewlineOffset = Macro->LastNewlineOffset;
  321. String->WhitespaceRange = Macro->WhitespaceRange;
  322. String->OriginalColumn = Macro->OriginalColumn;
  323. String->ColumnWidth = encoding::columnWidthWithTabs(
  324. String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
  325. String->NewlinesBefore = Macro->NewlinesBefore;
  326. String->HasUnescapedNewline = Macro->HasUnescapedNewline;
  327. Tokens.pop_back();
  328. Tokens.pop_back();
  329. Tokens.pop_back();
  330. Tokens.back() = String;
  331. return true;
  332. }
  333. bool FormatTokenLexer::tryMergeConflictMarkers() {
  334. if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
  335. return false;
  336. // Conflict lines look like:
  337. // <marker> <text from the vcs>
  338. // For example:
  339. // >>>>>>> /file/in/file/system at revision 1234
  340. //
  341. // We merge all tokens in a line that starts with a conflict marker
  342. // into a single token with a special token type that the unwrapped line
  343. // parser will use to correctly rebuild the underlying code.
  344. FileID ID;
  345. // Get the position of the first token in the line.
  346. unsigned FirstInLineOffset;
  347. std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
  348. Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
  349. StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
  350. // Calculate the offset of the start of the current line.
  351. auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
  352. if (LineOffset == StringRef::npos) {
  353. LineOffset = 0;
  354. } else {
  355. ++LineOffset;
  356. }
  357. auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
  358. StringRef LineStart;
  359. if (FirstSpace == StringRef::npos) {
  360. LineStart = Buffer.substr(LineOffset);
  361. } else {
  362. LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
  363. }
  364. TokenType Type = TT_Unknown;
  365. if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
  366. Type = TT_ConflictStart;
  367. } else if (LineStart == "|||||||" || LineStart == "=======" ||
  368. LineStart == "====") {
  369. Type = TT_ConflictAlternative;
  370. } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
  371. Type = TT_ConflictEnd;
  372. }
  373. if (Type != TT_Unknown) {
  374. FormatToken *Next = Tokens.back();
  375. Tokens.resize(FirstInLineIndex + 1);
  376. // We do not need to build a complete token here, as we will skip it
  377. // during parsing anyway (as we must not touch whitespace around conflict
  378. // markers).
  379. Tokens.back()->Type = Type;
  380. Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
  381. Tokens.push_back(Next);
  382. return true;
  383. }
  384. return false;
  385. }
  386. FormatToken *FormatTokenLexer::getStashedToken() {
  387. // Create a synthesized second '>' or '<' token.
  388. Token Tok = FormatTok->Tok;
  389. StringRef TokenText = FormatTok->TokenText;
  390. unsigned OriginalColumn = FormatTok->OriginalColumn;
  391. FormatTok = new (Allocator.Allocate()) FormatToken;
  392. FormatTok->Tok = Tok;
  393. SourceLocation TokLocation =
  394. FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
  395. FormatTok->Tok.setLocation(TokLocation);
  396. FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
  397. FormatTok->TokenText = TokenText;
  398. FormatTok->ColumnWidth = 1;
  399. FormatTok->OriginalColumn = OriginalColumn + 1;
  400. return FormatTok;
  401. }
  402. FormatToken *FormatTokenLexer::getNextToken() {
  403. if (StateStack.top() == LexerState::TOKEN_STASHED) {
  404. StateStack.pop();
  405. return getStashedToken();
  406. }
  407. FormatTok = new (Allocator.Allocate()) FormatToken;
  408. readRawToken(*FormatTok);
  409. SourceLocation WhitespaceStart =
  410. FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
  411. FormatTok->IsFirst = IsFirstToken;
  412. IsFirstToken = false;
  413. // Consume and record whitespace until we find a significant token.
  414. unsigned WhitespaceLength = TrailingWhitespace;
  415. while (FormatTok->Tok.is(tok::unknown)) {
  416. StringRef Text = FormatTok->TokenText;
  417. auto EscapesNewline = [&](int pos) {
  418. // A '\r' here is just part of '\r\n'. Skip it.
  419. if (pos >= 0 && Text[pos] == '\r')
  420. --pos;
  421. // See whether there is an odd number of '\' before this.
  422. // FIXME: This is wrong. A '\' followed by a newline is always removed,
  423. // regardless of whether there is another '\' before it.
  424. // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
  425. unsigned count = 0;
  426. for (; pos >= 0; --pos, ++count)
  427. if (Text[pos] != '\\')
  428. break;
  429. return count & 1;
  430. };
  431. // FIXME: This miscounts tok:unknown tokens that are not just
  432. // whitespace, e.g. a '`' character.
  433. for (int i = 0, e = Text.size(); i != e; ++i) {
  434. switch (Text[i]) {
  435. case '\n':
  436. ++FormatTok->NewlinesBefore;
  437. FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
  438. FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
  439. Column = 0;
  440. break;
  441. case '\r':
  442. FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
  443. Column = 0;
  444. break;
  445. case '\f':
  446. case '\v':
  447. Column = 0;
  448. break;
  449. case ' ':
  450. ++Column;
  451. break;
  452. case '\t':
  453. Column += Style.TabWidth - Column % Style.TabWidth;
  454. break;
  455. case '\\':
  456. if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
  457. FormatTok->Type = TT_ImplicitStringLiteral;
  458. break;
  459. default:
  460. FormatTok->Type = TT_ImplicitStringLiteral;
  461. break;
  462. }
  463. if (FormatTok->Type == TT_ImplicitStringLiteral)
  464. break;
  465. }
  466. if (FormatTok->is(TT_ImplicitStringLiteral))
  467. break;
  468. WhitespaceLength += FormatTok->Tok.getLength();
  469. readRawToken(*FormatTok);
  470. }
  471. // JavaScript and Java do not allow to escape the end of the line with a
  472. // backslash. Backslashes are syntax errors in plain source, but can occur in
  473. // comments. When a single line comment ends with a \, it'll cause the next
  474. // line of code to be lexed as a comment, breaking formatting. The code below
  475. // finds comments that contain a backslash followed by a line break, truncates
  476. // the comment token at the backslash, and resets the lexer to restart behind
  477. // the backslash.
  478. if ((Style.Language == FormatStyle::LK_JavaScript ||
  479. Style.Language == FormatStyle::LK_Java) &&
  480. FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
  481. size_t BackslashPos = FormatTok->TokenText.find('\\');
  482. while (BackslashPos != StringRef::npos) {
  483. if (BackslashPos + 1 < FormatTok->TokenText.size() &&
  484. FormatTok->TokenText[BackslashPos + 1] == '\n') {
  485. const char *Offset = Lex->getBufferLocation();
  486. Offset -= FormatTok->TokenText.size();
  487. Offset += BackslashPos + 1;
  488. resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
  489. FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
  490. FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
  491. FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
  492. Encoding);
  493. break;
  494. }
  495. BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
  496. }
  497. }
  498. // In case the token starts with escaped newlines, we want to
  499. // take them into account as whitespace - this pattern is quite frequent
  500. // in macro definitions.
  501. // FIXME: Add a more explicit test.
  502. while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
  503. FormatTok->TokenText[1] == '\n') {
  504. ++FormatTok->NewlinesBefore;
  505. WhitespaceLength += 2;
  506. FormatTok->LastNewlineOffset = 2;
  507. Column = 0;
  508. FormatTok->TokenText = FormatTok->TokenText.substr(2);
  509. }
  510. FormatTok->WhitespaceRange = SourceRange(
  511. WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
  512. FormatTok->OriginalColumn = Column;
  513. TrailingWhitespace = 0;
  514. if (FormatTok->Tok.is(tok::comment)) {
  515. // FIXME: Add the trimmed whitespace to Column.
  516. StringRef UntrimmedText = FormatTok->TokenText;
  517. FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
  518. TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
  519. } else if (FormatTok->Tok.is(tok::raw_identifier)) {
  520. IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
  521. FormatTok->Tok.setIdentifierInfo(&Info);
  522. FormatTok->Tok.setKind(Info.getTokenID());
  523. if (Style.Language == FormatStyle::LK_Java &&
  524. FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
  525. tok::kw_operator)) {
  526. FormatTok->Tok.setKind(tok::identifier);
  527. FormatTok->Tok.setIdentifierInfo(nullptr);
  528. } else if (Style.Language == FormatStyle::LK_JavaScript &&
  529. FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
  530. tok::kw_operator)) {
  531. FormatTok->Tok.setKind(tok::identifier);
  532. FormatTok->Tok.setIdentifierInfo(nullptr);
  533. }
  534. } else if (FormatTok->Tok.is(tok::greatergreater)) {
  535. FormatTok->Tok.setKind(tok::greater);
  536. FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
  537. ++Column;
  538. StateStack.push(LexerState::TOKEN_STASHED);
  539. } else if (FormatTok->Tok.is(tok::lessless)) {
  540. FormatTok->Tok.setKind(tok::less);
  541. FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
  542. ++Column;
  543. StateStack.push(LexerState::TOKEN_STASHED);
  544. }
  545. // Now FormatTok is the next non-whitespace token.
  546. StringRef Text = FormatTok->TokenText;
  547. size_t FirstNewlinePos = Text.find('\n');
  548. if (FirstNewlinePos == StringRef::npos) {
  549. // FIXME: ColumnWidth actually depends on the start column, we need to
  550. // take this into account when the token is moved.
  551. FormatTok->ColumnWidth =
  552. encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
  553. Column += FormatTok->ColumnWidth;
  554. } else {
  555. FormatTok->IsMultiline = true;
  556. // FIXME: ColumnWidth actually depends on the start column, we need to
  557. // take this into account when the token is moved.
  558. FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
  559. Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
  560. // The last line of the token always starts in column 0.
  561. // Thus, the length can be precomputed even in the presence of tabs.
  562. FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
  563. Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
  564. Column = FormatTok->LastLineColumnWidth;
  565. }
  566. if (Style.isCpp()) {
  567. if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
  568. Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
  569. tok::pp_define) &&
  570. std::find(ForEachMacros.begin(), ForEachMacros.end(),
  571. FormatTok->Tok.getIdentifierInfo()) != ForEachMacros.end()) {
  572. FormatTok->Type = TT_ForEachMacro;
  573. } else if (FormatTok->is(tok::identifier)) {
  574. if (MacroBlockBeginRegex.match(Text)) {
  575. FormatTok->Type = TT_MacroBlockBegin;
  576. } else if (MacroBlockEndRegex.match(Text)) {
  577. FormatTok->Type = TT_MacroBlockEnd;
  578. }
  579. }
  580. }
  581. return FormatTok;
  582. }
  583. void FormatTokenLexer::readRawToken(FormatToken &Tok) {
  584. Lex->LexFromRawLexer(Tok.Tok);
  585. Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
  586. Tok.Tok.getLength());
  587. // For formatting, treat unterminated string literals like normal string
  588. // literals.
  589. if (Tok.is(tok::unknown)) {
  590. if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
  591. Tok.Tok.setKind(tok::string_literal);
  592. Tok.IsUnterminatedLiteral = true;
  593. } else if (Style.Language == FormatStyle::LK_JavaScript &&
  594. Tok.TokenText == "''") {
  595. Tok.Tok.setKind(tok::string_literal);
  596. }
  597. }
  598. if (Style.Language == FormatStyle::LK_JavaScript &&
  599. Tok.is(tok::char_constant)) {
  600. Tok.Tok.setKind(tok::string_literal);
  601. }
  602. if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
  603. Tok.TokenText == "/* clang-format on */")) {
  604. FormattingDisabled = false;
  605. }
  606. Tok.Finalized = FormattingDisabled;
  607. if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
  608. Tok.TokenText == "/* clang-format off */")) {
  609. FormattingDisabled = true;
  610. }
  611. }
  612. void FormatTokenLexer::resetLexer(unsigned Offset) {
  613. StringRef Buffer = SourceMgr.getBufferData(ID);
  614. Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
  615. getFormattingLangOpts(Style), Buffer.begin(),
  616. Buffer.begin() + Offset, Buffer.end()));
  617. Lex->SetKeepWhitespaceMode(true);
  618. TrailingWhitespace = 0;
  619. }
  620. } // namespace format
  621. } // namespace clang