FormatTokenLexer.cpp 31 KB

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