FormatTokenLexer.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  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(
  23. const SourceManager &SourceMgr, FileID ID, unsigned Column,
  24. const FormatStyle &Style, encoding::Encoding Encoding,
  25. llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
  26. IdentifierTable &IdentTable)
  27. : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}),
  28. Column(Column), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
  29. Style(Style), IdentTable(IdentTable), Keywords(IdentTable),
  30. Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0),
  31. FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin),
  32. MacroBlockEndRegex(Style.MacroBlockEnd) {
  33. Lex.reset(new Lexer(ID, SourceMgr.getBufferOrFake(ID), SourceMgr,
  34. getFormattingLangOpts(Style)));
  35. Lex->SetKeepWhitespaceMode(true);
  36. for (const std::string &ForEachMacro : Style.ForEachMacros) {
  37. auto Identifier = &IdentTable.get(ForEachMacro);
  38. Macros.insert({Identifier, TT_ForEachMacro});
  39. }
  40. for (const std::string &IfMacro : Style.IfMacros) {
  41. auto Identifier = &IdentTable.get(IfMacro);
  42. Macros.insert({Identifier, TT_IfMacro});
  43. }
  44. for (const std::string &AttributeMacro : Style.AttributeMacros) {
  45. auto Identifier = &IdentTable.get(AttributeMacro);
  46. Macros.insert({Identifier, TT_AttributeMacro});
  47. }
  48. for (const std::string &StatementMacro : Style.StatementMacros) {
  49. auto Identifier = &IdentTable.get(StatementMacro);
  50. Macros.insert({Identifier, TT_StatementMacro});
  51. }
  52. for (const std::string &TypenameMacro : Style.TypenameMacros) {
  53. auto Identifier = &IdentTable.get(TypenameMacro);
  54. Macros.insert({Identifier, TT_TypenameMacro});
  55. }
  56. for (const std::string &NamespaceMacro : Style.NamespaceMacros) {
  57. auto Identifier = &IdentTable.get(NamespaceMacro);
  58. Macros.insert({Identifier, TT_NamespaceMacro});
  59. }
  60. for (const std::string &WhitespaceSensitiveMacro :
  61. Style.WhitespaceSensitiveMacros) {
  62. auto Identifier = &IdentTable.get(WhitespaceSensitiveMacro);
  63. Macros.insert({Identifier, TT_UntouchableMacroFunc});
  64. }
  65. for (const std::string &StatementAttributeLikeMacro :
  66. Style.StatementAttributeLikeMacros) {
  67. auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
  68. Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
  69. }
  70. }
  71. ArrayRef<FormatToken *> FormatTokenLexer::lex() {
  72. assert(Tokens.empty());
  73. assert(FirstInLineIndex == 0);
  74. do {
  75. Tokens.push_back(getNextToken());
  76. if (Style.isJavaScript()) {
  77. tryParseJSRegexLiteral();
  78. handleTemplateStrings();
  79. }
  80. if (Style.Language == FormatStyle::LK_TextProto)
  81. tryParsePythonComment();
  82. tryMergePreviousTokens();
  83. if (Style.isCSharp())
  84. // This needs to come after tokens have been merged so that C#
  85. // string literals are correctly identified.
  86. handleCSharpVerbatimAndInterpolatedStrings();
  87. if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
  88. FirstInLineIndex = Tokens.size() - 1;
  89. } while (Tokens.back()->Tok.isNot(tok::eof));
  90. return Tokens;
  91. }
  92. void FormatTokenLexer::tryMergePreviousTokens() {
  93. if (tryMerge_TMacro())
  94. return;
  95. if (tryMergeConflictMarkers())
  96. return;
  97. if (tryMergeLessLess())
  98. return;
  99. if (tryMergeForEach())
  100. return;
  101. if (Style.isCpp() && tryTransformTryUsageForC())
  102. return;
  103. if (Style.isJavaScript() || Style.isCSharp()) {
  104. static const tok::TokenKind NullishCoalescingOperator[] = {tok::question,
  105. tok::question};
  106. static const tok::TokenKind NullPropagatingOperator[] = {tok::question,
  107. tok::period};
  108. static const tok::TokenKind FatArrow[] = {tok::equal, tok::greater};
  109. if (tryMergeTokens(FatArrow, TT_FatArrow))
  110. return;
  111. if (tryMergeTokens(NullishCoalescingOperator, TT_NullCoalescingOperator)) {
  112. // Treat like the "||" operator (as opposed to the ternary ?).
  113. Tokens.back()->Tok.setKind(tok::pipepipe);
  114. return;
  115. }
  116. if (tryMergeTokens(NullPropagatingOperator, TT_NullPropagatingOperator)) {
  117. // Treat like a regular "." access.
  118. Tokens.back()->Tok.setKind(tok::period);
  119. return;
  120. }
  121. if (tryMergeNullishCoalescingEqual()) {
  122. return;
  123. }
  124. }
  125. if (Style.isCSharp()) {
  126. static const tok::TokenKind CSharpNullConditionalLSquare[] = {
  127. tok::question, tok::l_square};
  128. if (tryMergeCSharpKeywordVariables())
  129. return;
  130. if (tryMergeCSharpStringLiteral())
  131. return;
  132. if (tryTransformCSharpForEach())
  133. return;
  134. if (tryMergeTokens(CSharpNullConditionalLSquare,
  135. TT_CSharpNullConditionalLSquare)) {
  136. // Treat like a regular "[" operator.
  137. Tokens.back()->Tok.setKind(tok::l_square);
  138. return;
  139. }
  140. }
  141. if (tryMergeNSStringLiteral())
  142. return;
  143. if (Style.isJavaScript()) {
  144. static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
  145. static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
  146. tok::equal};
  147. static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
  148. tok::greaterequal};
  149. static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
  150. static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
  151. tok::starequal};
  152. static const tok::TokenKind JSPipePipeEqual[] = {tok::pipepipe, tok::equal};
  153. static const tok::TokenKind JSAndAndEqual[] = {tok::ampamp, tok::equal};
  154. // FIXME: Investigate what token type gives the correct operator priority.
  155. if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
  156. return;
  157. if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
  158. return;
  159. if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
  160. return;
  161. if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
  162. return;
  163. if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
  164. Tokens.back()->Tok.setKind(tok::starequal);
  165. return;
  166. }
  167. if (tryMergeTokens(JSAndAndEqual, TT_JsAndAndEqual) ||
  168. tryMergeTokens(JSPipePipeEqual, TT_JsPipePipeEqual)) {
  169. // Treat like the "=" assignment operator.
  170. Tokens.back()->Tok.setKind(tok::equal);
  171. return;
  172. }
  173. if (tryMergeJSPrivateIdentifier())
  174. return;
  175. }
  176. if (Style.Language == FormatStyle::LK_Java) {
  177. static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
  178. tok::greater, tok::greater, tok::greaterequal};
  179. if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
  180. return;
  181. }
  182. }
  183. bool FormatTokenLexer::tryMergeNSStringLiteral() {
  184. if (Tokens.size() < 2)
  185. return false;
  186. auto &At = *(Tokens.end() - 2);
  187. auto &String = *(Tokens.end() - 1);
  188. if (!At->is(tok::at) || !String->is(tok::string_literal))
  189. return false;
  190. At->Tok.setKind(tok::string_literal);
  191. At->TokenText = StringRef(At->TokenText.begin(),
  192. String->TokenText.end() - At->TokenText.begin());
  193. At->ColumnWidth += String->ColumnWidth;
  194. At->setType(TT_ObjCStringLiteral);
  195. Tokens.erase(Tokens.end() - 1);
  196. return true;
  197. }
  198. bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
  199. // Merges #idenfier into a single identifier with the text #identifier
  200. // but the token tok::identifier.
  201. if (Tokens.size() < 2)
  202. return false;
  203. auto &Hash = *(Tokens.end() - 2);
  204. auto &Identifier = *(Tokens.end() - 1);
  205. if (!Hash->is(tok::hash) || !Identifier->is(tok::identifier))
  206. return false;
  207. Hash->Tok.setKind(tok::identifier);
  208. Hash->TokenText =
  209. StringRef(Hash->TokenText.begin(),
  210. Identifier->TokenText.end() - Hash->TokenText.begin());
  211. Hash->ColumnWidth += Identifier->ColumnWidth;
  212. Hash->setType(TT_JsPrivateIdentifier);
  213. Tokens.erase(Tokens.end() - 1);
  214. return true;
  215. }
  216. // Search for verbatim or interpolated string literals @"ABC" or
  217. // $"aaaaa{abc}aaaaa" i and mark the token as TT_CSharpStringLiteral, and to
  218. // prevent splitting of @, $ and ".
  219. // Merging of multiline verbatim strings with embedded '"' is handled in
  220. // handleCSharpVerbatimAndInterpolatedStrings with lower-level lexing.
  221. bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
  222. if (Tokens.size() < 2)
  223. return false;
  224. // Interpolated strings could contain { } with " characters inside.
  225. // $"{x ?? "null"}"
  226. // should not be split into $"{x ?? ", null, "}" but should treated as a
  227. // single string-literal.
  228. //
  229. // We opt not to try and format expressions inside {} within a C#
  230. // interpolated string. Formatting expressions within an interpolated string
  231. // would require similar work as that done for JavaScript template strings
  232. // in `handleTemplateStrings()`.
  233. auto &CSharpInterpolatedString = *(Tokens.end() - 2);
  234. if (CSharpInterpolatedString->getType() == TT_CSharpStringLiteral &&
  235. (CSharpInterpolatedString->TokenText.startswith(R"($")") ||
  236. CSharpInterpolatedString->TokenText.startswith(R"($@")"))) {
  237. int UnmatchedOpeningBraceCount = 0;
  238. auto TokenTextSize = CSharpInterpolatedString->TokenText.size();
  239. for (size_t Index = 0; Index < TokenTextSize; ++Index) {
  240. char C = CSharpInterpolatedString->TokenText[Index];
  241. if (C == '{') {
  242. // "{{" inside an interpolated string is an escaped '{' so skip it.
  243. if (Index + 1 < TokenTextSize &&
  244. CSharpInterpolatedString->TokenText[Index + 1] == '{') {
  245. ++Index;
  246. continue;
  247. }
  248. ++UnmatchedOpeningBraceCount;
  249. } else if (C == '}') {
  250. // "}}" inside an interpolated string is an escaped '}' so skip it.
  251. if (Index + 1 < TokenTextSize &&
  252. CSharpInterpolatedString->TokenText[Index + 1] == '}') {
  253. ++Index;
  254. continue;
  255. }
  256. --UnmatchedOpeningBraceCount;
  257. }
  258. }
  259. if (UnmatchedOpeningBraceCount > 0) {
  260. auto &NextToken = *(Tokens.end() - 1);
  261. CSharpInterpolatedString->TokenText =
  262. StringRef(CSharpInterpolatedString->TokenText.begin(),
  263. NextToken->TokenText.end() -
  264. CSharpInterpolatedString->TokenText.begin());
  265. CSharpInterpolatedString->ColumnWidth += NextToken->ColumnWidth;
  266. Tokens.erase(Tokens.end() - 1);
  267. return true;
  268. }
  269. }
  270. // Look for @"aaaaaa" or $"aaaaaa".
  271. auto &String = *(Tokens.end() - 1);
  272. if (!String->is(tok::string_literal))
  273. return false;
  274. auto &At = *(Tokens.end() - 2);
  275. if (!(At->is(tok::at) || At->TokenText == "$"))
  276. return false;
  277. if (Tokens.size() > 2 && At->is(tok::at)) {
  278. auto &Dollar = *(Tokens.end() - 3);
  279. if (Dollar->TokenText == "$") {
  280. // This looks like $@"aaaaa" so we need to combine all 3 tokens.
  281. Dollar->Tok.setKind(tok::string_literal);
  282. Dollar->TokenText =
  283. StringRef(Dollar->TokenText.begin(),
  284. String->TokenText.end() - Dollar->TokenText.begin());
  285. Dollar->ColumnWidth += (At->ColumnWidth + String->ColumnWidth);
  286. Dollar->setType(TT_CSharpStringLiteral);
  287. Tokens.erase(Tokens.end() - 2);
  288. Tokens.erase(Tokens.end() - 1);
  289. return true;
  290. }
  291. }
  292. // Convert back into just a string_literal.
  293. At->Tok.setKind(tok::string_literal);
  294. At->TokenText = StringRef(At->TokenText.begin(),
  295. String->TokenText.end() - At->TokenText.begin());
  296. At->ColumnWidth += String->ColumnWidth;
  297. At->setType(TT_CSharpStringLiteral);
  298. Tokens.erase(Tokens.end() - 1);
  299. return true;
  300. }
  301. // Valid C# attribute targets:
  302. // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
  303. const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
  304. "assembly", "module", "field", "event", "method",
  305. "param", "property", "return", "type",
  306. };
  307. bool FormatTokenLexer::tryMergeNullishCoalescingEqual() {
  308. if (Tokens.size() < 2)
  309. return false;
  310. auto &NullishCoalescing = *(Tokens.end() - 2);
  311. auto &Equal = *(Tokens.end() - 1);
  312. if (NullishCoalescing->getType() != TT_NullCoalescingOperator ||
  313. !Equal->is(tok::equal))
  314. return false;
  315. NullishCoalescing->Tok.setKind(tok::equal); // no '??=' in clang tokens.
  316. NullishCoalescing->TokenText =
  317. StringRef(NullishCoalescing->TokenText.begin(),
  318. Equal->TokenText.end() - NullishCoalescing->TokenText.begin());
  319. NullishCoalescing->ColumnWidth += Equal->ColumnWidth;
  320. NullishCoalescing->setType(TT_NullCoalescingEqual);
  321. Tokens.erase(Tokens.end() - 1);
  322. return true;
  323. }
  324. bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
  325. if (Tokens.size() < 2)
  326. return false;
  327. auto &At = *(Tokens.end() - 2);
  328. auto &Keyword = *(Tokens.end() - 1);
  329. if (!At->is(tok::at))
  330. return false;
  331. if (!Keywords.isCSharpKeyword(*Keyword))
  332. return false;
  333. At->Tok.setKind(tok::identifier);
  334. At->TokenText = StringRef(At->TokenText.begin(),
  335. Keyword->TokenText.end() - At->TokenText.begin());
  336. At->ColumnWidth += Keyword->ColumnWidth;
  337. At->setType(Keyword->getType());
  338. Tokens.erase(Tokens.end() - 1);
  339. return true;
  340. }
  341. // In C# transform identifier foreach into kw_foreach
  342. bool FormatTokenLexer::tryTransformCSharpForEach() {
  343. if (Tokens.size() < 1)
  344. return false;
  345. auto &Identifier = *(Tokens.end() - 1);
  346. if (!Identifier->is(tok::identifier))
  347. return false;
  348. if (Identifier->TokenText != "foreach")
  349. return false;
  350. Identifier->setType(TT_ForEachMacro);
  351. Identifier->Tok.setKind(tok::kw_for);
  352. return true;
  353. }
  354. bool FormatTokenLexer::tryMergeForEach() {
  355. if (Tokens.size() < 2)
  356. return false;
  357. auto &For = *(Tokens.end() - 2);
  358. auto &Each = *(Tokens.end() - 1);
  359. if (!For->is(tok::kw_for))
  360. return false;
  361. if (!Each->is(tok::identifier))
  362. return false;
  363. if (Each->TokenText != "each")
  364. return false;
  365. For->setType(TT_ForEachMacro);
  366. For->Tok.setKind(tok::kw_for);
  367. For->TokenText = StringRef(For->TokenText.begin(),
  368. Each->TokenText.end() - For->TokenText.begin());
  369. For->ColumnWidth += Each->ColumnWidth;
  370. Tokens.erase(Tokens.end() - 1);
  371. return true;
  372. }
  373. bool FormatTokenLexer::tryTransformTryUsageForC() {
  374. if (Tokens.size() < 2)
  375. return false;
  376. auto &Try = *(Tokens.end() - 2);
  377. if (!Try->is(tok::kw_try))
  378. return false;
  379. auto &Next = *(Tokens.end() - 1);
  380. if (Next->isOneOf(tok::l_brace, tok::colon, tok::hash, tok::comment))
  381. return false;
  382. if (Tokens.size() > 2) {
  383. auto &At = *(Tokens.end() - 3);
  384. if (At->is(tok::at))
  385. return false;
  386. }
  387. Try->Tok.setKind(tok::identifier);
  388. return true;
  389. }
  390. bool FormatTokenLexer::tryMergeLessLess() {
  391. // Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
  392. if (Tokens.size() < 3)
  393. return false;
  394. auto First = Tokens.end() - 3;
  395. if (First[0]->isNot(tok::less) || First[1]->isNot(tok::less))
  396. return false;
  397. // Only merge if there currently is no whitespace between the two "<".
  398. if (First[1]->hasWhitespaceBefore())
  399. return false;
  400. auto X = Tokens.size() > 3 ? First[-1] : nullptr;
  401. auto Y = First[2];
  402. if ((X && X->is(tok::less)) || Y->is(tok::less))
  403. return false;
  404. // Do not remove a whitespace between the two "<" e.g. "operator< <>".
  405. if (X && X->is(tok::kw_operator) && Y->is(tok::greater))
  406. return false;
  407. First[0]->Tok.setKind(tok::lessless);
  408. First[0]->TokenText = "<<";
  409. First[0]->ColumnWidth += 1;
  410. Tokens.erase(Tokens.end() - 2);
  411. return true;
  412. }
  413. bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
  414. TokenType NewType) {
  415. if (Tokens.size() < Kinds.size())
  416. return false;
  417. SmallVectorImpl<FormatToken *>::const_iterator First =
  418. Tokens.end() - Kinds.size();
  419. if (!First[0]->is(Kinds[0]))
  420. return false;
  421. unsigned AddLength = 0;
  422. for (unsigned i = 1; i < Kinds.size(); ++i) {
  423. if (!First[i]->is(Kinds[i]) || First[i]->hasWhitespaceBefore())
  424. return false;
  425. AddLength += First[i]->TokenText.size();
  426. }
  427. Tokens.resize(Tokens.size() - Kinds.size() + 1);
  428. First[0]->TokenText = StringRef(First[0]->TokenText.data(),
  429. First[0]->TokenText.size() + AddLength);
  430. First[0]->ColumnWidth += AddLength;
  431. First[0]->setType(NewType);
  432. return true;
  433. }
  434. // Returns \c true if \p Tok can only be followed by an operand in JavaScript.
  435. bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
  436. // NB: This is not entirely correct, as an r_paren can introduce an operand
  437. // location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
  438. // corner case to not matter in practice, though.
  439. return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
  440. tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
  441. tok::colon, tok::question, tok::tilde) ||
  442. Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
  443. tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
  444. tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
  445. Tok->isBinaryOperator();
  446. }
  447. bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
  448. if (!Prev)
  449. return true;
  450. // Regex literals can only follow after prefix unary operators, not after
  451. // postfix unary operators. If the '++' is followed by a non-operand
  452. // introducing token, the slash here is the operand and not the start of a
  453. // regex.
  454. // `!` is an unary prefix operator, but also a post-fix operator that casts
  455. // away nullability, so the same check applies.
  456. if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
  457. return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
  458. // The previous token must introduce an operand location where regex
  459. // literals can occur.
  460. if (!precedesOperand(Prev))
  461. return false;
  462. return true;
  463. }
  464. // Tries to parse a JavaScript Regex literal starting at the current token,
  465. // if that begins with a slash and is in a location where JavaScript allows
  466. // regex literals. Changes the current token to a regex literal and updates
  467. // its text if successful.
  468. void FormatTokenLexer::tryParseJSRegexLiteral() {
  469. FormatToken *RegexToken = Tokens.back();
  470. if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
  471. return;
  472. FormatToken *Prev = nullptr;
  473. for (FormatToken *FT : llvm::drop_begin(llvm::reverse(Tokens))) {
  474. // NB: Because previous pointers are not initialized yet, this cannot use
  475. // Token.getPreviousNonComment.
  476. if (FT->isNot(tok::comment)) {
  477. Prev = FT;
  478. break;
  479. }
  480. }
  481. if (!canPrecedeRegexLiteral(Prev))
  482. return;
  483. // 'Manually' lex ahead in the current file buffer.
  484. const char *Offset = Lex->getBufferLocation();
  485. const char *RegexBegin = Offset - RegexToken->TokenText.size();
  486. StringRef Buffer = Lex->getBuffer();
  487. bool InCharacterClass = false;
  488. bool HaveClosingSlash = false;
  489. for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
  490. // Regular expressions are terminated with a '/', which can only be
  491. // escaped using '\' or a character class between '[' and ']'.
  492. // See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
  493. switch (*Offset) {
  494. case '\\':
  495. // Skip the escaped character.
  496. ++Offset;
  497. break;
  498. case '[':
  499. InCharacterClass = true;
  500. break;
  501. case ']':
  502. InCharacterClass = false;
  503. break;
  504. case '/':
  505. if (!InCharacterClass)
  506. HaveClosingSlash = true;
  507. break;
  508. }
  509. }
  510. RegexToken->setType(TT_RegexLiteral);
  511. // Treat regex literals like other string_literals.
  512. RegexToken->Tok.setKind(tok::string_literal);
  513. RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
  514. RegexToken->ColumnWidth = RegexToken->TokenText.size();
  515. resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
  516. }
  517. void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
  518. FormatToken *CSharpStringLiteral = Tokens.back();
  519. if (CSharpStringLiteral->getType() != TT_CSharpStringLiteral)
  520. return;
  521. // Deal with multiline strings.
  522. if (!(CSharpStringLiteral->TokenText.startswith(R"(@")") ||
  523. CSharpStringLiteral->TokenText.startswith(R"($@")")))
  524. return;
  525. const char *StrBegin =
  526. Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size();
  527. const char *Offset = StrBegin;
  528. if (CSharpStringLiteral->TokenText.startswith(R"(@")"))
  529. Offset += 2;
  530. else // CSharpStringLiteral->TokenText.startswith(R"($@")")
  531. Offset += 3;
  532. // Look for a terminating '"' in the current file buffer.
  533. // Make no effort to format code within an interpolated or verbatim string.
  534. for (; Offset != Lex->getBuffer().end(); ++Offset) {
  535. if (Offset[0] == '"') {
  536. // "" within a verbatim string is an escaped double quote: skip it.
  537. if (Offset + 1 < Lex->getBuffer().end() && Offset[1] == '"')
  538. ++Offset;
  539. else
  540. break;
  541. }
  542. }
  543. // Make no attempt to format code properly if a verbatim string is
  544. // unterminated.
  545. if (Offset == Lex->getBuffer().end())
  546. return;
  547. StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
  548. CSharpStringLiteral->TokenText = LiteralText;
  549. // Adjust width for potentially multiline string literals.
  550. size_t FirstBreak = LiteralText.find('\n');
  551. StringRef FirstLineText = FirstBreak == StringRef::npos
  552. ? LiteralText
  553. : LiteralText.substr(0, FirstBreak);
  554. CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs(
  555. FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
  556. Encoding);
  557. size_t LastBreak = LiteralText.rfind('\n');
  558. if (LastBreak != StringRef::npos) {
  559. CSharpStringLiteral->IsMultiline = true;
  560. unsigned StartColumn = 0;
  561. CSharpStringLiteral->LastLineColumnWidth = encoding::columnWidthWithTabs(
  562. LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
  563. Style.TabWidth, Encoding);
  564. }
  565. SourceLocation loc = Offset < Lex->getBuffer().end()
  566. ? Lex->getSourceLocation(Offset + 1)
  567. : SourceMgr.getLocForEndOfFile(ID);
  568. resetLexer(SourceMgr.getFileOffset(loc));
  569. }
  570. void FormatTokenLexer::handleTemplateStrings() {
  571. FormatToken *BacktickToken = Tokens.back();
  572. if (BacktickToken->is(tok::l_brace)) {
  573. StateStack.push(LexerState::NORMAL);
  574. return;
  575. }
  576. if (BacktickToken->is(tok::r_brace)) {
  577. if (StateStack.size() == 1)
  578. return;
  579. StateStack.pop();
  580. if (StateStack.top() != LexerState::TEMPLATE_STRING)
  581. return;
  582. // If back in TEMPLATE_STRING, fallthrough and continue parsing the
  583. } else if (BacktickToken->is(tok::unknown) &&
  584. BacktickToken->TokenText == "`") {
  585. StateStack.push(LexerState::TEMPLATE_STRING);
  586. } else {
  587. return; // Not actually a template
  588. }
  589. // 'Manually' lex ahead in the current file buffer.
  590. const char *Offset = Lex->getBufferLocation();
  591. const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
  592. for (; Offset != Lex->getBuffer().end(); ++Offset) {
  593. if (Offset[0] == '`') {
  594. StateStack.pop();
  595. break;
  596. }
  597. if (Offset[0] == '\\') {
  598. ++Offset; // Skip the escaped character.
  599. } else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
  600. Offset[1] == '{') {
  601. // '${' introduces an expression interpolation in the template string.
  602. StateStack.push(LexerState::NORMAL);
  603. ++Offset;
  604. break;
  605. }
  606. }
  607. StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
  608. BacktickToken->setType(TT_TemplateString);
  609. BacktickToken->Tok.setKind(tok::string_literal);
  610. BacktickToken->TokenText = LiteralText;
  611. // Adjust width for potentially multiline string literals.
  612. size_t FirstBreak = LiteralText.find('\n');
  613. StringRef FirstLineText = FirstBreak == StringRef::npos
  614. ? LiteralText
  615. : LiteralText.substr(0, FirstBreak);
  616. BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
  617. FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
  618. size_t LastBreak = LiteralText.rfind('\n');
  619. if (LastBreak != StringRef::npos) {
  620. BacktickToken->IsMultiline = true;
  621. unsigned StartColumn = 0; // The template tail spans the entire line.
  622. BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
  623. LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
  624. Style.TabWidth, Encoding);
  625. }
  626. SourceLocation loc = Offset < Lex->getBuffer().end()
  627. ? Lex->getSourceLocation(Offset + 1)
  628. : SourceMgr.getLocForEndOfFile(ID);
  629. resetLexer(SourceMgr.getFileOffset(loc));
  630. }
  631. void FormatTokenLexer::tryParsePythonComment() {
  632. FormatToken *HashToken = Tokens.back();
  633. if (!HashToken->isOneOf(tok::hash, tok::hashhash))
  634. return;
  635. // Turn the remainder of this line into a comment.
  636. const char *CommentBegin =
  637. Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
  638. size_t From = CommentBegin - Lex->getBuffer().begin();
  639. size_t To = Lex->getBuffer().find_first_of('\n', From);
  640. if (To == StringRef::npos)
  641. To = Lex->getBuffer().size();
  642. size_t Len = To - From;
  643. HashToken->setType(TT_LineComment);
  644. HashToken->Tok.setKind(tok::comment);
  645. HashToken->TokenText = Lex->getBuffer().substr(From, Len);
  646. SourceLocation Loc = To < Lex->getBuffer().size()
  647. ? Lex->getSourceLocation(CommentBegin + Len)
  648. : SourceMgr.getLocForEndOfFile(ID);
  649. resetLexer(SourceMgr.getFileOffset(Loc));
  650. }
  651. bool FormatTokenLexer::tryMerge_TMacro() {
  652. if (Tokens.size() < 4)
  653. return false;
  654. FormatToken *Last = Tokens.back();
  655. if (!Last->is(tok::r_paren))
  656. return false;
  657. FormatToken *String = Tokens[Tokens.size() - 2];
  658. if (!String->is(tok::string_literal) || String->IsMultiline)
  659. return false;
  660. if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
  661. return false;
  662. FormatToken *Macro = Tokens[Tokens.size() - 4];
  663. if (Macro->TokenText != "_T")
  664. return false;
  665. const char *Start = Macro->TokenText.data();
  666. const char *End = Last->TokenText.data() + Last->TokenText.size();
  667. String->TokenText = StringRef(Start, End - Start);
  668. String->IsFirst = Macro->IsFirst;
  669. String->LastNewlineOffset = Macro->LastNewlineOffset;
  670. String->WhitespaceRange = Macro->WhitespaceRange;
  671. String->OriginalColumn = Macro->OriginalColumn;
  672. String->ColumnWidth = encoding::columnWidthWithTabs(
  673. String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
  674. String->NewlinesBefore = Macro->NewlinesBefore;
  675. String->HasUnescapedNewline = Macro->HasUnescapedNewline;
  676. Tokens.pop_back();
  677. Tokens.pop_back();
  678. Tokens.pop_back();
  679. Tokens.back() = String;
  680. if (FirstInLineIndex >= Tokens.size())
  681. FirstInLineIndex = Tokens.size() - 1;
  682. return true;
  683. }
  684. bool FormatTokenLexer::tryMergeConflictMarkers() {
  685. if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
  686. return false;
  687. // Conflict lines look like:
  688. // <marker> <text from the vcs>
  689. // For example:
  690. // >>>>>>> /file/in/file/system at revision 1234
  691. //
  692. // We merge all tokens in a line that starts with a conflict marker
  693. // into a single token with a special token type that the unwrapped line
  694. // parser will use to correctly rebuild the underlying code.
  695. FileID ID;
  696. // Get the position of the first token in the line.
  697. unsigned FirstInLineOffset;
  698. std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
  699. Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
  700. StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
  701. // Calculate the offset of the start of the current line.
  702. auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
  703. if (LineOffset == StringRef::npos) {
  704. LineOffset = 0;
  705. } else {
  706. ++LineOffset;
  707. }
  708. auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
  709. StringRef LineStart;
  710. if (FirstSpace == StringRef::npos) {
  711. LineStart = Buffer.substr(LineOffset);
  712. } else {
  713. LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
  714. }
  715. TokenType Type = TT_Unknown;
  716. if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
  717. Type = TT_ConflictStart;
  718. } else if (LineStart == "|||||||" || LineStart == "=======" ||
  719. LineStart == "====") {
  720. Type = TT_ConflictAlternative;
  721. } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
  722. Type = TT_ConflictEnd;
  723. }
  724. if (Type != TT_Unknown) {
  725. FormatToken *Next = Tokens.back();
  726. Tokens.resize(FirstInLineIndex + 1);
  727. // We do not need to build a complete token here, as we will skip it
  728. // during parsing anyway (as we must not touch whitespace around conflict
  729. // markers).
  730. Tokens.back()->setType(Type);
  731. Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
  732. Tokens.push_back(Next);
  733. return true;
  734. }
  735. return false;
  736. }
  737. FormatToken *FormatTokenLexer::getStashedToken() {
  738. // Create a synthesized second '>' or '<' token.
  739. Token Tok = FormatTok->Tok;
  740. StringRef TokenText = FormatTok->TokenText;
  741. unsigned OriginalColumn = FormatTok->OriginalColumn;
  742. FormatTok = new (Allocator.Allocate()) FormatToken;
  743. FormatTok->Tok = Tok;
  744. SourceLocation TokLocation =
  745. FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
  746. FormatTok->Tok.setLocation(TokLocation);
  747. FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
  748. FormatTok->TokenText = TokenText;
  749. FormatTok->ColumnWidth = 1;
  750. FormatTok->OriginalColumn = OriginalColumn + 1;
  751. return FormatTok;
  752. }
  753. FormatToken *FormatTokenLexer::getNextToken() {
  754. if (StateStack.top() == LexerState::TOKEN_STASHED) {
  755. StateStack.pop();
  756. return getStashedToken();
  757. }
  758. FormatTok = new (Allocator.Allocate()) FormatToken;
  759. readRawToken(*FormatTok);
  760. SourceLocation WhitespaceStart =
  761. FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
  762. FormatTok->IsFirst = IsFirstToken;
  763. IsFirstToken = false;
  764. // Consume and record whitespace until we find a significant token.
  765. unsigned WhitespaceLength = TrailingWhitespace;
  766. while (FormatTok->Tok.is(tok::unknown)) {
  767. StringRef Text = FormatTok->TokenText;
  768. auto EscapesNewline = [&](int pos) {
  769. // A '\r' here is just part of '\r\n'. Skip it.
  770. if (pos >= 0 && Text[pos] == '\r')
  771. --pos;
  772. // See whether there is an odd number of '\' before this.
  773. // FIXME: This is wrong. A '\' followed by a newline is always removed,
  774. // regardless of whether there is another '\' before it.
  775. // FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
  776. unsigned count = 0;
  777. for (; pos >= 0; --pos, ++count)
  778. if (Text[pos] != '\\')
  779. break;
  780. return count & 1;
  781. };
  782. // FIXME: This miscounts tok:unknown tokens that are not just
  783. // whitespace, e.g. a '`' character.
  784. for (int i = 0, e = Text.size(); i != e; ++i) {
  785. switch (Text[i]) {
  786. case '\n':
  787. ++FormatTok->NewlinesBefore;
  788. FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
  789. FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
  790. Column = 0;
  791. break;
  792. case '\r':
  793. FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
  794. Column = 0;
  795. break;
  796. case '\f':
  797. case '\v':
  798. Column = 0;
  799. break;
  800. case ' ':
  801. ++Column;
  802. break;
  803. case '\t':
  804. Column +=
  805. Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
  806. break;
  807. case '\\':
  808. if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
  809. FormatTok->setType(TT_ImplicitStringLiteral);
  810. break;
  811. default:
  812. FormatTok->setType(TT_ImplicitStringLiteral);
  813. break;
  814. }
  815. if (FormatTok->getType() == TT_ImplicitStringLiteral)
  816. break;
  817. }
  818. if (FormatTok->is(TT_ImplicitStringLiteral))
  819. break;
  820. WhitespaceLength += FormatTok->Tok.getLength();
  821. readRawToken(*FormatTok);
  822. }
  823. // JavaScript and Java do not allow to escape the end of the line with a
  824. // backslash. Backslashes are syntax errors in plain source, but can occur in
  825. // comments. When a single line comment ends with a \, it'll cause the next
  826. // line of code to be lexed as a comment, breaking formatting. The code below
  827. // finds comments that contain a backslash followed by a line break, truncates
  828. // the comment token at the backslash, and resets the lexer to restart behind
  829. // the backslash.
  830. if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
  831. FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
  832. size_t BackslashPos = FormatTok->TokenText.find('\\');
  833. while (BackslashPos != StringRef::npos) {
  834. if (BackslashPos + 1 < FormatTok->TokenText.size() &&
  835. FormatTok->TokenText[BackslashPos + 1] == '\n') {
  836. const char *Offset = Lex->getBufferLocation();
  837. Offset -= FormatTok->TokenText.size();
  838. Offset += BackslashPos + 1;
  839. resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
  840. FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
  841. FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
  842. FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
  843. Encoding);
  844. break;
  845. }
  846. BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
  847. }
  848. }
  849. // In case the token starts with escaped newlines, we want to
  850. // take them into account as whitespace - this pattern is quite frequent
  851. // in macro definitions.
  852. // FIXME: Add a more explicit test.
  853. while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') {
  854. unsigned SkippedWhitespace = 0;
  855. if (FormatTok->TokenText.size() > 2 &&
  856. (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n'))
  857. SkippedWhitespace = 3;
  858. else if (FormatTok->TokenText[1] == '\n')
  859. SkippedWhitespace = 2;
  860. else
  861. break;
  862. ++FormatTok->NewlinesBefore;
  863. WhitespaceLength += SkippedWhitespace;
  864. FormatTok->LastNewlineOffset = SkippedWhitespace;
  865. Column = 0;
  866. FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace);
  867. }
  868. FormatTok->WhitespaceRange = SourceRange(
  869. WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
  870. FormatTok->OriginalColumn = Column;
  871. TrailingWhitespace = 0;
  872. if (FormatTok->Tok.is(tok::comment)) {
  873. // FIXME: Add the trimmed whitespace to Column.
  874. StringRef UntrimmedText = FormatTok->TokenText;
  875. FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
  876. TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
  877. } else if (FormatTok->Tok.is(tok::raw_identifier)) {
  878. IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
  879. FormatTok->Tok.setIdentifierInfo(&Info);
  880. FormatTok->Tok.setKind(Info.getTokenID());
  881. if (Style.Language == FormatStyle::LK_Java &&
  882. FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
  883. tok::kw_operator)) {
  884. FormatTok->Tok.setKind(tok::identifier);
  885. FormatTok->Tok.setIdentifierInfo(nullptr);
  886. } else if (Style.isJavaScript() &&
  887. FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
  888. tok::kw_operator)) {
  889. FormatTok->Tok.setKind(tok::identifier);
  890. FormatTok->Tok.setIdentifierInfo(nullptr);
  891. }
  892. } else if (FormatTok->Tok.is(tok::greatergreater)) {
  893. FormatTok->Tok.setKind(tok::greater);
  894. FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
  895. ++Column;
  896. StateStack.push(LexerState::TOKEN_STASHED);
  897. } else if (FormatTok->Tok.is(tok::lessless)) {
  898. FormatTok->Tok.setKind(tok::less);
  899. FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
  900. ++Column;
  901. StateStack.push(LexerState::TOKEN_STASHED);
  902. }
  903. // Now FormatTok is the next non-whitespace token.
  904. StringRef Text = FormatTok->TokenText;
  905. size_t FirstNewlinePos = Text.find('\n');
  906. if (FirstNewlinePos == StringRef::npos) {
  907. // FIXME: ColumnWidth actually depends on the start column, we need to
  908. // take this into account when the token is moved.
  909. FormatTok->ColumnWidth =
  910. encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
  911. Column += FormatTok->ColumnWidth;
  912. } else {
  913. FormatTok->IsMultiline = true;
  914. // FIXME: ColumnWidth actually depends on the start column, we need to
  915. // take this into account when the token is moved.
  916. FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
  917. Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
  918. // The last line of the token always starts in column 0.
  919. // Thus, the length can be precomputed even in the presence of tabs.
  920. FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
  921. Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
  922. Column = FormatTok->LastLineColumnWidth;
  923. }
  924. if (Style.isCpp()) {
  925. auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
  926. if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
  927. Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
  928. tok::pp_define) &&
  929. it != Macros.end()) {
  930. FormatTok->setType(it->second);
  931. if (it->second == TT_IfMacro) {
  932. // The lexer token currently has type tok::kw_unknown. However, for this
  933. // substitution to be treated correctly in the TokenAnnotator, faking
  934. // the tok value seems to be needed. Not sure if there's a more elegant
  935. // way.
  936. FormatTok->Tok.setKind(tok::kw_if);
  937. }
  938. } else if (FormatTok->is(tok::identifier)) {
  939. if (MacroBlockBeginRegex.match(Text)) {
  940. FormatTok->setType(TT_MacroBlockBegin);
  941. } else if (MacroBlockEndRegex.match(Text)) {
  942. FormatTok->setType(TT_MacroBlockEnd);
  943. }
  944. }
  945. }
  946. return FormatTok;
  947. }
  948. void FormatTokenLexer::readRawToken(FormatToken &Tok) {
  949. Lex->LexFromRawLexer(Tok.Tok);
  950. Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
  951. Tok.Tok.getLength());
  952. // For formatting, treat unterminated string literals like normal string
  953. // literals.
  954. if (Tok.is(tok::unknown)) {
  955. if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
  956. Tok.Tok.setKind(tok::string_literal);
  957. Tok.IsUnterminatedLiteral = true;
  958. } else if (Style.isJavaScript() && Tok.TokenText == "''") {
  959. Tok.Tok.setKind(tok::string_literal);
  960. }
  961. }
  962. if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Proto ||
  963. Style.Language == FormatStyle::LK_TextProto) &&
  964. Tok.is(tok::char_constant)) {
  965. Tok.Tok.setKind(tok::string_literal);
  966. }
  967. if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
  968. Tok.TokenText == "/* clang-format on */")) {
  969. FormattingDisabled = false;
  970. }
  971. Tok.Finalized = FormattingDisabled;
  972. if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
  973. Tok.TokenText == "/* clang-format off */")) {
  974. FormattingDisabled = true;
  975. }
  976. }
  977. void FormatTokenLexer::resetLexer(unsigned Offset) {
  978. StringRef Buffer = SourceMgr.getBufferData(ID);
  979. Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
  980. getFormattingLangOpts(Style), Buffer.begin(),
  981. Buffer.begin() + Offset, Buffer.end()));
  982. Lex->SetKeepWhitespaceMode(true);
  983. TrailingWhitespace = 0;
  984. }
  985. } // namespace format
  986. } // namespace clang