FormatTokenLexer.cpp 32 KB

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