FormatTokenLexer.cpp 25 KB

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