TokenAnnotator.cpp 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905
  1. //===--- TokenAnnotator.cpp - Format C++ code -----------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief This file implements a token annotator, i.e. creates
  12. /// \c AnnotatedTokens out of \c FormatTokens with required extra information.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "TokenAnnotator.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/Support/Debug.h"
  19. #define DEBUG_TYPE "format-token-annotator"
  20. namespace clang {
  21. namespace format {
  22. namespace {
  23. /// \brief A parser that gathers additional information about tokens.
  24. ///
  25. /// The \c TokenAnnotator tries to match parenthesis and square brakets and
  26. /// store a parenthesis levels. It also tries to resolve matching "<" and ">"
  27. /// into template parameter lists.
  28. class AnnotatingParser {
  29. public:
  30. AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
  31. const AdditionalKeywords &Keywords)
  32. : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
  33. Keywords(Keywords) {
  34. Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
  35. resetTokenMetadata(CurrentToken);
  36. }
  37. private:
  38. bool parseAngle() {
  39. if (!CurrentToken || !CurrentToken->Previous)
  40. return false;
  41. if (NonTemplateLess.count(CurrentToken->Previous))
  42. return false;
  43. const FormatToken& Previous = *CurrentToken->Previous;
  44. if (Previous.Previous) {
  45. if (Previous.Previous->Tok.isLiteral())
  46. return false;
  47. if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
  48. (!Previous.Previous->MatchingParen ||
  49. !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen)))
  50. return false;
  51. }
  52. FormatToken *Left = CurrentToken->Previous;
  53. Left->ParentBracket = Contexts.back().ContextKind;
  54. ScopedContextCreator ContextCreator(*this, tok::less, 12);
  55. // If this angle is in the context of an expression, we need to be more
  56. // hesitant to detect it as opening template parameters.
  57. bool InExprContext = Contexts.back().IsExpression;
  58. Contexts.back().IsExpression = false;
  59. // If there's a template keyword before the opening angle bracket, this is a
  60. // template parameter, not an argument.
  61. Contexts.back().InTemplateArgument =
  62. Left->Previous && Left->Previous->Tok.isNot(tok::kw_template);
  63. if (Style.Language == FormatStyle::LK_Java &&
  64. CurrentToken->is(tok::question))
  65. next();
  66. while (CurrentToken) {
  67. if (CurrentToken->is(tok::greater)) {
  68. Left->MatchingParen = CurrentToken;
  69. CurrentToken->MatchingParen = Left;
  70. CurrentToken->Type = TT_TemplateCloser;
  71. next();
  72. return true;
  73. }
  74. if (CurrentToken->is(tok::question) &&
  75. Style.Language == FormatStyle::LK_Java) {
  76. next();
  77. continue;
  78. }
  79. if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) ||
  80. (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext &&
  81. Style.Language != FormatStyle::LK_Proto &&
  82. Style.Language != FormatStyle::LK_TextProto))
  83. return false;
  84. // If a && or || is found and interpreted as a binary operator, this set
  85. // of angles is likely part of something like "a < b && c > d". If the
  86. // angles are inside an expression, the ||/&& might also be a binary
  87. // operator that was misinterpreted because we are parsing template
  88. // parameters.
  89. // FIXME: This is getting out of hand, write a decent parser.
  90. if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
  91. CurrentToken->Previous->is(TT_BinaryOperator) &&
  92. Contexts[Contexts.size() - 2].IsExpression &&
  93. !Line.startsWith(tok::kw_template))
  94. return false;
  95. updateParameterCount(Left, CurrentToken);
  96. if (Style.Language == FormatStyle::LK_Proto) {
  97. if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) {
  98. if (CurrentToken->is(tok::colon) ||
  99. (CurrentToken->isOneOf(tok::l_brace, tok::less) &&
  100. Previous->isNot(tok::colon)))
  101. Previous->Type = TT_SelectorName;
  102. }
  103. }
  104. if (!consumeToken())
  105. return false;
  106. }
  107. return false;
  108. }
  109. bool parseParens(bool LookForDecls = false) {
  110. if (!CurrentToken)
  111. return false;
  112. FormatToken *Left = CurrentToken->Previous;
  113. Left->ParentBracket = Contexts.back().ContextKind;
  114. ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
  115. // FIXME: This is a bit of a hack. Do better.
  116. Contexts.back().ColonIsForRangeExpr =
  117. Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
  118. bool StartsObjCMethodExpr = false;
  119. if (CurrentToken->is(tok::caret)) {
  120. // (^ can start a block type.
  121. Left->Type = TT_ObjCBlockLParen;
  122. } else if (FormatToken *MaybeSel = Left->Previous) {
  123. // @selector( starts a selector.
  124. if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
  125. MaybeSel->Previous->is(tok::at)) {
  126. StartsObjCMethodExpr = true;
  127. }
  128. }
  129. if (Left->is(TT_OverloadedOperatorLParen)) {
  130. Contexts.back().IsExpression = false;
  131. } else if (Style.Language == FormatStyle::LK_JavaScript &&
  132. (Line.startsWith(Keywords.kw_type, tok::identifier) ||
  133. Line.startsWith(tok::kw_export, Keywords.kw_type,
  134. tok::identifier))) {
  135. // type X = (...);
  136. // export type X = (...);
  137. Contexts.back().IsExpression = false;
  138. } else if (Left->Previous &&
  139. (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype,
  140. tok::kw_if, tok::kw_while, tok::l_paren,
  141. tok::comma) ||
  142. Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) ||
  143. Left->Previous->is(TT_BinaryOperator))) {
  144. // static_assert, if and while usually contain expressions.
  145. Contexts.back().IsExpression = true;
  146. } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
  147. (Left->Previous->is(Keywords.kw_function) ||
  148. (Left->Previous->endsSequence(tok::identifier,
  149. Keywords.kw_function)))) {
  150. // function(...) or function f(...)
  151. Contexts.back().IsExpression = false;
  152. } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
  153. Left->Previous->is(TT_JsTypeColon)) {
  154. // let x: (SomeType);
  155. Contexts.back().IsExpression = false;
  156. } else if (Left->Previous && Left->Previous->is(tok::r_square) &&
  157. Left->Previous->MatchingParen &&
  158. Left->Previous->MatchingParen->is(TT_LambdaLSquare)) {
  159. // This is a parameter list of a lambda expression.
  160. Contexts.back().IsExpression = false;
  161. } else if (Line.InPPDirective &&
  162. (!Left->Previous || !Left->Previous->is(tok::identifier))) {
  163. Contexts.back().IsExpression = true;
  164. } else if (Contexts[Contexts.size() - 2].CaretFound) {
  165. // This is the parameter list of an ObjC block.
  166. Contexts.back().IsExpression = false;
  167. } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) {
  168. Left->Type = TT_AttributeParen;
  169. } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) {
  170. // The first argument to a foreach macro is a declaration.
  171. Contexts.back().IsForEachMacro = true;
  172. Contexts.back().IsExpression = false;
  173. } else if (Left->Previous && Left->Previous->MatchingParen &&
  174. Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
  175. Contexts.back().IsExpression = false;
  176. } else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
  177. bool IsForOrCatch =
  178. Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch);
  179. Contexts.back().IsExpression = !IsForOrCatch;
  180. }
  181. if (StartsObjCMethodExpr) {
  182. Contexts.back().ColonIsObjCMethodExpr = true;
  183. Left->Type = TT_ObjCMethodExpr;
  184. }
  185. bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
  186. bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
  187. bool HasMultipleLines = false;
  188. bool HasMultipleParametersOnALine = false;
  189. bool MightBeObjCForRangeLoop =
  190. Left->Previous && Left->Previous->is(tok::kw_for);
  191. while (CurrentToken) {
  192. // LookForDecls is set when "if (" has been seen. Check for
  193. // 'identifier' '*' 'identifier' followed by not '=' -- this
  194. // '*' has to be a binary operator but determineStarAmpUsage() will
  195. // categorize it as an unary operator, so set the right type here.
  196. if (LookForDecls && CurrentToken->Next) {
  197. FormatToken *Prev = CurrentToken->getPreviousNonComment();
  198. if (Prev) {
  199. FormatToken *PrevPrev = Prev->getPreviousNonComment();
  200. FormatToken *Next = CurrentToken->Next;
  201. if (PrevPrev && PrevPrev->is(tok::identifier) &&
  202. Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
  203. CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
  204. Prev->Type = TT_BinaryOperator;
  205. LookForDecls = false;
  206. }
  207. }
  208. }
  209. if (CurrentToken->Previous->is(TT_PointerOrReference) &&
  210. CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
  211. tok::coloncolon))
  212. ProbablyFunctionType = true;
  213. if (CurrentToken->is(tok::comma))
  214. MightBeFunctionType = false;
  215. if (CurrentToken->Previous->is(TT_BinaryOperator))
  216. Contexts.back().IsExpression = true;
  217. if (CurrentToken->is(tok::r_paren)) {
  218. if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next &&
  219. (CurrentToken->Next->is(tok::l_paren) ||
  220. (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration)))
  221. Left->Type = TT_FunctionTypeLParen;
  222. Left->MatchingParen = CurrentToken;
  223. CurrentToken->MatchingParen = Left;
  224. if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
  225. Left->Previous && Left->Previous->is(tok::l_paren)) {
  226. // Detect the case where macros are used to generate lambdas or
  227. // function bodies, e.g.:
  228. // auto my_lambda = MARCO((Type *type, int i) { .. body .. });
  229. for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
  230. if (Tok->is(TT_BinaryOperator) &&
  231. Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
  232. Tok->Type = TT_PointerOrReference;
  233. }
  234. }
  235. if (StartsObjCMethodExpr) {
  236. CurrentToken->Type = TT_ObjCMethodExpr;
  237. if (Contexts.back().FirstObjCSelectorName) {
  238. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
  239. Contexts.back().LongestObjCSelectorName;
  240. }
  241. }
  242. if (Left->is(TT_AttributeParen))
  243. CurrentToken->Type = TT_AttributeParen;
  244. if (Left->Previous && Left->Previous->is(TT_JavaAnnotation))
  245. CurrentToken->Type = TT_JavaAnnotation;
  246. if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation))
  247. CurrentToken->Type = TT_LeadingJavaAnnotation;
  248. if (!HasMultipleLines)
  249. Left->PackingKind = PPK_Inconclusive;
  250. else if (HasMultipleParametersOnALine)
  251. Left->PackingKind = PPK_BinPacked;
  252. else
  253. Left->PackingKind = PPK_OnePerLine;
  254. next();
  255. return true;
  256. }
  257. if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
  258. return false;
  259. if (CurrentToken->is(tok::l_brace))
  260. Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen
  261. if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
  262. !CurrentToken->Next->HasUnescapedNewline &&
  263. !CurrentToken->Next->isTrailingComment())
  264. HasMultipleParametersOnALine = true;
  265. if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
  266. CurrentToken->Previous->isSimpleTypeSpecifier()) &&
  267. !CurrentToken->is(tok::l_brace))
  268. Contexts.back().IsExpression = false;
  269. if (CurrentToken->isOneOf(tok::semi, tok::colon))
  270. MightBeObjCForRangeLoop = false;
  271. if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
  272. CurrentToken->Type = TT_ObjCForIn;
  273. // When we discover a 'new', we set CanBeExpression to 'false' in order to
  274. // parse the type correctly. Reset that after a comma.
  275. if (CurrentToken->is(tok::comma))
  276. Contexts.back().CanBeExpression = true;
  277. FormatToken *Tok = CurrentToken;
  278. if (!consumeToken())
  279. return false;
  280. updateParameterCount(Left, Tok);
  281. if (CurrentToken && CurrentToken->HasUnescapedNewline)
  282. HasMultipleLines = true;
  283. }
  284. return false;
  285. }
  286. bool isCppStructuredBinding(const FormatToken *Tok) {
  287. if (!Style.isCpp() || !Tok->is(tok::l_square))
  288. return false;
  289. do {
  290. Tok = Tok->getPreviousNonComment();
  291. } while (Tok && Tok->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
  292. tok::ampamp));
  293. return Tok && Tok->is(tok::kw_auto);
  294. }
  295. bool parseSquare() {
  296. if (!CurrentToken)
  297. return false;
  298. // A '[' could be an index subscript (after an identifier or after
  299. // ')' or ']'), it could be the start of an Objective-C method
  300. // expression, or it could the start of an Objective-C array literal.
  301. FormatToken *Left = CurrentToken->Previous;
  302. Left->ParentBracket = Contexts.back().ContextKind;
  303. FormatToken *Parent = Left->getPreviousNonComment();
  304. // Cases where '>' is followed by '['.
  305. // In C++, this can happen either in array of templates (foo<int>[10])
  306. // or when array is a nested template type (unique_ptr<type1<type2>[]>).
  307. bool CppArrayTemplates =
  308. Style.isCpp() && Parent &&
  309. Parent->is(TT_TemplateCloser) &&
  310. (Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
  311. Contexts.back().InTemplateArgument);
  312. bool StartsObjCMethodExpr =
  313. !CppArrayTemplates && Style.isCpp() &&
  314. Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
  315. CurrentToken->isNot(tok::l_brace) &&
  316. (!Parent ||
  317. Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
  318. tok::kw_return, tok::kw_throw) ||
  319. Parent->isUnaryOperator() ||
  320. Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
  321. getBinOpPrecedence(Parent->Tok.getKind(), true, true) > prec::Unknown);
  322. bool ColonFound = false;
  323. unsigned BindingIncrease = 1;
  324. if (Left->is(TT_Unknown)) {
  325. if (isCppStructuredBinding(Left)) {
  326. Left->Type = TT_StructuredBindingLSquare;
  327. } else if (StartsObjCMethodExpr) {
  328. Left->Type = TT_ObjCMethodExpr;
  329. } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  330. Contexts.back().ContextKind == tok::l_brace &&
  331. Parent->isOneOf(tok::l_brace, tok::comma)) {
  332. Left->Type = TT_JsComputedPropertyName;
  333. } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
  334. Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
  335. Left->Type = TT_DesignatedInitializerLSquare;
  336. } else if (CurrentToken->is(tok::r_square) && Parent &&
  337. Parent->is(TT_TemplateCloser)) {
  338. Left->Type = TT_ArraySubscriptLSquare;
  339. } else if (Style.Language == FormatStyle::LK_Proto ||
  340. (!CppArrayTemplates && Parent &&
  341. Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
  342. tok::comma, tok::l_paren, tok::l_square,
  343. tok::question, tok::colon, tok::kw_return,
  344. // Should only be relevant to JavaScript:
  345. tok::kw_default))) {
  346. Left->Type = TT_ArrayInitializerLSquare;
  347. } else {
  348. BindingIncrease = 10;
  349. Left->Type = TT_ArraySubscriptLSquare;
  350. }
  351. }
  352. ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
  353. Contexts.back().IsExpression = true;
  354. if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  355. Parent->is(TT_JsTypeColon))
  356. Contexts.back().IsExpression = false;
  357. Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
  358. while (CurrentToken) {
  359. if (CurrentToken->is(tok::r_square)) {
  360. if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) &&
  361. Left->is(TT_ObjCMethodExpr)) {
  362. // An ObjC method call is rarely followed by an open parenthesis.
  363. // FIXME: Do we incorrectly label ":" with this?
  364. StartsObjCMethodExpr = false;
  365. Left->Type = TT_Unknown;
  366. }
  367. if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
  368. CurrentToken->Type = TT_ObjCMethodExpr;
  369. // determineStarAmpUsage() thinks that '*' '[' is allocating an
  370. // array of pointers, but if '[' starts a selector then '*' is a
  371. // binary operator.
  372. if (Parent && Parent->is(TT_PointerOrReference))
  373. Parent->Type = TT_BinaryOperator;
  374. }
  375. Left->MatchingParen = CurrentToken;
  376. CurrentToken->MatchingParen = Left;
  377. if (Contexts.back().FirstObjCSelectorName) {
  378. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
  379. Contexts.back().LongestObjCSelectorName;
  380. if (Left->BlockParameterCount > 1)
  381. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
  382. }
  383. next();
  384. return true;
  385. }
  386. if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
  387. return false;
  388. if (CurrentToken->is(tok::colon)) {
  389. if (Left->isOneOf(TT_ArraySubscriptLSquare,
  390. TT_DesignatedInitializerLSquare)) {
  391. Left->Type = TT_ObjCMethodExpr;
  392. StartsObjCMethodExpr = true;
  393. Contexts.back().ColonIsObjCMethodExpr = true;
  394. if (Parent && Parent->is(tok::r_paren))
  395. Parent->Type = TT_CastRParen;
  396. }
  397. ColonFound = true;
  398. }
  399. if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
  400. !ColonFound)
  401. Left->Type = TT_ArrayInitializerLSquare;
  402. FormatToken *Tok = CurrentToken;
  403. if (!consumeToken())
  404. return false;
  405. updateParameterCount(Left, Tok);
  406. }
  407. return false;
  408. }
  409. bool parseBrace() {
  410. if (CurrentToken) {
  411. FormatToken *Left = CurrentToken->Previous;
  412. Left->ParentBracket = Contexts.back().ContextKind;
  413. if (Contexts.back().CaretFound)
  414. Left->Type = TT_ObjCBlockLBrace;
  415. Contexts.back().CaretFound = false;
  416. ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
  417. Contexts.back().ColonIsDictLiteral = true;
  418. if (Left->BlockKind == BK_BracedInit)
  419. Contexts.back().IsExpression = true;
  420. if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous &&
  421. Left->Previous->is(TT_JsTypeColon))
  422. Contexts.back().IsExpression = false;
  423. while (CurrentToken) {
  424. if (CurrentToken->is(tok::r_brace)) {
  425. Left->MatchingParen = CurrentToken;
  426. CurrentToken->MatchingParen = Left;
  427. next();
  428. return true;
  429. }
  430. if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
  431. return false;
  432. updateParameterCount(Left, CurrentToken);
  433. if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
  434. FormatToken *Previous = CurrentToken->getPreviousNonComment();
  435. if (Previous->is(TT_JsTypeOptionalQuestion))
  436. Previous = Previous->getPreviousNonComment();
  437. if (((CurrentToken->is(tok::colon) &&
  438. (!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
  439. Style.Language == FormatStyle::LK_Proto ||
  440. Style.Language == FormatStyle::LK_TextProto) &&
  441. (Previous->Tok.getIdentifierInfo() ||
  442. Previous->is(tok::string_literal)))
  443. Previous->Type = TT_SelectorName;
  444. if (CurrentToken->is(tok::colon) ||
  445. Style.Language == FormatStyle::LK_JavaScript)
  446. Left->Type = TT_DictLiteral;
  447. }
  448. if (CurrentToken->is(tok::comma) &&
  449. Style.Language == FormatStyle::LK_JavaScript)
  450. Left->Type = TT_DictLiteral;
  451. if (!consumeToken())
  452. return false;
  453. }
  454. }
  455. return true;
  456. }
  457. void updateParameterCount(FormatToken *Left, FormatToken *Current) {
  458. if (Current->is(tok::l_brace) && Current->BlockKind == BK_Block)
  459. ++Left->BlockParameterCount;
  460. if (Current->is(tok::comma)) {
  461. ++Left->ParameterCount;
  462. if (!Left->Role)
  463. Left->Role.reset(new CommaSeparatedList(Style));
  464. Left->Role->CommaFound(Current);
  465. } else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
  466. Left->ParameterCount = 1;
  467. }
  468. }
  469. bool parseConditional() {
  470. while (CurrentToken) {
  471. if (CurrentToken->is(tok::colon)) {
  472. CurrentToken->Type = TT_ConditionalExpr;
  473. next();
  474. return true;
  475. }
  476. if (!consumeToken())
  477. return false;
  478. }
  479. return false;
  480. }
  481. bool parseTemplateDeclaration() {
  482. if (CurrentToken && CurrentToken->is(tok::less)) {
  483. CurrentToken->Type = TT_TemplateOpener;
  484. next();
  485. if (!parseAngle())
  486. return false;
  487. if (CurrentToken)
  488. CurrentToken->Previous->ClosesTemplateDeclaration = true;
  489. return true;
  490. }
  491. return false;
  492. }
  493. bool consumeToken() {
  494. FormatToken *Tok = CurrentToken;
  495. next();
  496. switch (Tok->Tok.getKind()) {
  497. case tok::plus:
  498. case tok::minus:
  499. if (!Tok->Previous && Line.MustBeDeclaration)
  500. Tok->Type = TT_ObjCMethodSpecifier;
  501. break;
  502. case tok::colon:
  503. if (!Tok->Previous)
  504. return false;
  505. // Colons from ?: are handled in parseConditional().
  506. if (Style.Language == FormatStyle::LK_JavaScript) {
  507. if (Contexts.back().ColonIsForRangeExpr || // colon in for loop
  508. (Contexts.size() == 1 && // switch/case labels
  509. !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
  510. Contexts.back().ContextKind == tok::l_paren || // function params
  511. Contexts.back().ContextKind == tok::l_square || // array type
  512. (!Contexts.back().IsExpression &&
  513. Contexts.back().ContextKind == tok::l_brace) || // object type
  514. (Contexts.size() == 1 &&
  515. Line.MustBeDeclaration)) { // method/property declaration
  516. Contexts.back().IsExpression = false;
  517. Tok->Type = TT_JsTypeColon;
  518. break;
  519. }
  520. }
  521. if (Contexts.back().ColonIsDictLiteral ||
  522. Style.Language == FormatStyle::LK_Proto ||
  523. Style.Language == FormatStyle::LK_TextProto) {
  524. Tok->Type = TT_DictLiteral;
  525. if (Style.Language == FormatStyle::LK_TextProto) {
  526. if (FormatToken *Previous = Tok->getPreviousNonComment())
  527. Previous->Type = TT_SelectorName;
  528. }
  529. } else if (Contexts.back().ColonIsObjCMethodExpr ||
  530. Line.startsWith(TT_ObjCMethodSpecifier)) {
  531. Tok->Type = TT_ObjCMethodExpr;
  532. const FormatToken *BeforePrevious = Tok->Previous->Previous;
  533. if (!BeforePrevious ||
  534. !(BeforePrevious->is(TT_CastRParen) ||
  535. (BeforePrevious->is(TT_ObjCMethodExpr) &&
  536. BeforePrevious->is(tok::colon))) ||
  537. BeforePrevious->is(tok::r_square) ||
  538. Contexts.back().LongestObjCSelectorName == 0) {
  539. Tok->Previous->Type = TT_SelectorName;
  540. if (Tok->Previous->ColumnWidth >
  541. Contexts.back().LongestObjCSelectorName)
  542. Contexts.back().LongestObjCSelectorName =
  543. Tok->Previous->ColumnWidth;
  544. if (!Contexts.back().FirstObjCSelectorName)
  545. Contexts.back().FirstObjCSelectorName = Tok->Previous;
  546. }
  547. } else if (Contexts.back().ColonIsForRangeExpr) {
  548. Tok->Type = TT_RangeBasedForLoopColon;
  549. } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
  550. Tok->Type = TT_BitFieldColon;
  551. } else if (Contexts.size() == 1 &&
  552. !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) {
  553. if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren,
  554. tok::kw_noexcept))
  555. Tok->Type = TT_CtorInitializerColon;
  556. else
  557. Tok->Type = TT_InheritanceColon;
  558. } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
  559. Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
  560. // This handles a special macro in ObjC code where selectors including
  561. // the colon are passed as macro arguments.
  562. Tok->Type = TT_ObjCMethodExpr;
  563. } else if (Contexts.back().ContextKind == tok::l_paren) {
  564. Tok->Type = TT_InlineASMColon;
  565. }
  566. break;
  567. case tok::pipe:
  568. case tok::amp:
  569. // | and & in declarations/type expressions represent union and
  570. // intersection types, respectively.
  571. if (Style.Language == FormatStyle::LK_JavaScript &&
  572. !Contexts.back().IsExpression)
  573. Tok->Type = TT_JsTypeOperator;
  574. break;
  575. case tok::kw_if:
  576. case tok::kw_while:
  577. if (Tok->is(tok::kw_if) && CurrentToken && CurrentToken->is(tok::kw_constexpr))
  578. next();
  579. if (CurrentToken && CurrentToken->is(tok::l_paren)) {
  580. next();
  581. if (!parseParens(/*LookForDecls=*/true))
  582. return false;
  583. }
  584. break;
  585. case tok::kw_for:
  586. if (Style.Language == FormatStyle::LK_JavaScript) {
  587. if (Tok->Previous && Tok->Previous->is(tok::period))
  588. break;
  589. // JS' for await ( ...
  590. if (CurrentToken && CurrentToken->is(Keywords.kw_await))
  591. next();
  592. }
  593. Contexts.back().ColonIsForRangeExpr = true;
  594. next();
  595. if (!parseParens())
  596. return false;
  597. break;
  598. case tok::l_paren:
  599. // When faced with 'operator()()', the kw_operator handler incorrectly
  600. // marks the first l_paren as a OverloadedOperatorLParen. Here, we make
  601. // the first two parens OverloadedOperators and the second l_paren an
  602. // OverloadedOperatorLParen.
  603. if (Tok->Previous &&
  604. Tok->Previous->is(tok::r_paren) &&
  605. Tok->Previous->MatchingParen &&
  606. Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
  607. Tok->Previous->Type = TT_OverloadedOperator;
  608. Tok->Previous->MatchingParen->Type = TT_OverloadedOperator;
  609. Tok->Type = TT_OverloadedOperatorLParen;
  610. }
  611. if (!parseParens())
  612. return false;
  613. if (Line.MustBeDeclaration && Contexts.size() == 1 &&
  614. !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) &&
  615. (!Tok->Previous ||
  616. !Tok->Previous->isOneOf(tok::kw_decltype, tok::kw___attribute,
  617. TT_LeadingJavaAnnotation)))
  618. Line.MightBeFunctionDecl = true;
  619. break;
  620. case tok::l_square:
  621. if (!parseSquare())
  622. return false;
  623. break;
  624. case tok::l_brace:
  625. if (Style.Language == FormatStyle::LK_TextProto) {
  626. FormatToken *Previous =Tok->getPreviousNonComment();
  627. if (Previous && Previous->Type != TT_DictLiteral)
  628. Previous->Type = TT_SelectorName;
  629. }
  630. if (!parseBrace())
  631. return false;
  632. break;
  633. case tok::less:
  634. if (parseAngle()) {
  635. Tok->Type = TT_TemplateOpener;
  636. if (Style.Language == FormatStyle::LK_TextProto) {
  637. FormatToken *Previous = Tok->getPreviousNonComment();
  638. if (Previous && Previous->Type != TT_DictLiteral)
  639. Previous->Type = TT_SelectorName;
  640. }
  641. } else {
  642. Tok->Type = TT_BinaryOperator;
  643. NonTemplateLess.insert(Tok);
  644. CurrentToken = Tok;
  645. next();
  646. }
  647. break;
  648. case tok::r_paren:
  649. case tok::r_square:
  650. return false;
  651. case tok::r_brace:
  652. // Lines can start with '}'.
  653. if (Tok->Previous)
  654. return false;
  655. break;
  656. case tok::greater:
  657. Tok->Type = TT_BinaryOperator;
  658. break;
  659. case tok::kw_operator:
  660. while (CurrentToken &&
  661. !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) {
  662. if (CurrentToken->isOneOf(tok::star, tok::amp))
  663. CurrentToken->Type = TT_PointerOrReference;
  664. consumeToken();
  665. if (CurrentToken &&
  666. CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma))
  667. CurrentToken->Previous->Type = TT_OverloadedOperator;
  668. }
  669. if (CurrentToken) {
  670. CurrentToken->Type = TT_OverloadedOperatorLParen;
  671. if (CurrentToken->Previous->is(TT_BinaryOperator))
  672. CurrentToken->Previous->Type = TT_OverloadedOperator;
  673. }
  674. break;
  675. case tok::question:
  676. if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next &&
  677. Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
  678. tok::r_brace)) {
  679. // Question marks before semicolons, colons, etc. indicate optional
  680. // types (fields, parameters), e.g.
  681. // function(x?: string, y?) {...}
  682. // class X { y?; }
  683. Tok->Type = TT_JsTypeOptionalQuestion;
  684. break;
  685. }
  686. // Declarations cannot be conditional expressions, this can only be part
  687. // of a type declaration.
  688. if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
  689. Style.Language == FormatStyle::LK_JavaScript)
  690. break;
  691. parseConditional();
  692. break;
  693. case tok::kw_template:
  694. parseTemplateDeclaration();
  695. break;
  696. case tok::comma:
  697. if (Contexts.back().InCtorInitializer)
  698. Tok->Type = TT_CtorInitializerComma;
  699. else if (Contexts.back().InInheritanceList)
  700. Tok->Type = TT_InheritanceComma;
  701. else if (Contexts.back().FirstStartOfName &&
  702. (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
  703. Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
  704. Line.IsMultiVariableDeclStmt = true;
  705. }
  706. if (Contexts.back().IsForEachMacro)
  707. Contexts.back().IsExpression = true;
  708. break;
  709. case tok::identifier:
  710. if (Tok->isOneOf(Keywords.kw___has_include,
  711. Keywords.kw___has_include_next)) {
  712. parseHasInclude();
  713. }
  714. break;
  715. default:
  716. break;
  717. }
  718. return true;
  719. }
  720. void parseIncludeDirective() {
  721. if (CurrentToken && CurrentToken->is(tok::less)) {
  722. next();
  723. while (CurrentToken) {
  724. // Mark tokens up to the trailing line comments as implicit string
  725. // literals.
  726. if (CurrentToken->isNot(tok::comment) &&
  727. !CurrentToken->TokenText.startswith("//"))
  728. CurrentToken->Type = TT_ImplicitStringLiteral;
  729. next();
  730. }
  731. }
  732. }
  733. void parseWarningOrError() {
  734. next();
  735. // We still want to format the whitespace left of the first token of the
  736. // warning or error.
  737. next();
  738. while (CurrentToken) {
  739. CurrentToken->Type = TT_ImplicitStringLiteral;
  740. next();
  741. }
  742. }
  743. void parsePragma() {
  744. next(); // Consume "pragma".
  745. if (CurrentToken &&
  746. CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) {
  747. bool IsMark = CurrentToken->is(Keywords.kw_mark);
  748. next(); // Consume "mark".
  749. next(); // Consume first token (so we fix leading whitespace).
  750. while (CurrentToken) {
  751. if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
  752. CurrentToken->Type = TT_ImplicitStringLiteral;
  753. next();
  754. }
  755. }
  756. }
  757. void parseHasInclude() {
  758. if (!CurrentToken || !CurrentToken->is(tok::l_paren))
  759. return;
  760. next(); // '('
  761. parseIncludeDirective();
  762. next(); // ')'
  763. }
  764. LineType parsePreprocessorDirective() {
  765. bool IsFirstToken = CurrentToken->IsFirst;
  766. LineType Type = LT_PreprocessorDirective;
  767. next();
  768. if (!CurrentToken)
  769. return Type;
  770. if (Style.Language == FormatStyle::LK_JavaScript && IsFirstToken) {
  771. // JavaScript files can contain shebang lines of the form:
  772. // #!/usr/bin/env node
  773. // Treat these like C++ #include directives.
  774. while (CurrentToken) {
  775. // Tokens cannot be comments here.
  776. CurrentToken->Type = TT_ImplicitStringLiteral;
  777. next();
  778. }
  779. return LT_ImportStatement;
  780. }
  781. if (CurrentToken->Tok.is(tok::numeric_constant)) {
  782. CurrentToken->SpacesRequiredBefore = 1;
  783. return Type;
  784. }
  785. // Hashes in the middle of a line can lead to any strange token
  786. // sequence.
  787. if (!CurrentToken->Tok.getIdentifierInfo())
  788. return Type;
  789. switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
  790. case tok::pp_include:
  791. case tok::pp_include_next:
  792. case tok::pp_import:
  793. next();
  794. parseIncludeDirective();
  795. Type = LT_ImportStatement;
  796. break;
  797. case tok::pp_error:
  798. case tok::pp_warning:
  799. parseWarningOrError();
  800. break;
  801. case tok::pp_pragma:
  802. parsePragma();
  803. break;
  804. case tok::pp_if:
  805. case tok::pp_elif:
  806. Contexts.back().IsExpression = true;
  807. parseLine();
  808. break;
  809. default:
  810. break;
  811. }
  812. while (CurrentToken) {
  813. FormatToken *Tok = CurrentToken;
  814. next();
  815. if (Tok->is(tok::l_paren))
  816. parseParens();
  817. else if (Tok->isOneOf(Keywords.kw___has_include,
  818. Keywords.kw___has_include_next))
  819. parseHasInclude();
  820. }
  821. return Type;
  822. }
  823. public:
  824. LineType parseLine() {
  825. NonTemplateLess.clear();
  826. if (CurrentToken->is(tok::hash))
  827. return parsePreprocessorDirective();
  828. // Directly allow to 'import <string-literal>' to support protocol buffer
  829. // definitions (code.google.com/p/protobuf) or missing "#" (either way we
  830. // should not break the line).
  831. IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
  832. if ((Style.Language == FormatStyle::LK_Java &&
  833. CurrentToken->is(Keywords.kw_package)) ||
  834. (Info && Info->getPPKeywordID() == tok::pp_import &&
  835. CurrentToken->Next &&
  836. CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
  837. tok::kw_static))) {
  838. next();
  839. parseIncludeDirective();
  840. return LT_ImportStatement;
  841. }
  842. // If this line starts and ends in '<' and '>', respectively, it is likely
  843. // part of "#define <a/b.h>".
  844. if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
  845. parseIncludeDirective();
  846. return LT_ImportStatement;
  847. }
  848. // In .proto files, top-level options are very similar to import statements
  849. // and should not be line-wrapped.
  850. if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
  851. CurrentToken->is(Keywords.kw_option)) {
  852. next();
  853. if (CurrentToken && CurrentToken->is(tok::identifier))
  854. return LT_ImportStatement;
  855. }
  856. bool KeywordVirtualFound = false;
  857. bool ImportStatement = false;
  858. // import {...} from '...';
  859. if (Style.Language == FormatStyle::LK_JavaScript &&
  860. CurrentToken->is(Keywords.kw_import))
  861. ImportStatement = true;
  862. while (CurrentToken) {
  863. if (CurrentToken->is(tok::kw_virtual))
  864. KeywordVirtualFound = true;
  865. if (Style.Language == FormatStyle::LK_JavaScript) {
  866. // export {...} from '...';
  867. // An export followed by "from 'some string';" is a re-export from
  868. // another module identified by a URI and is treated as a
  869. // LT_ImportStatement (i.e. prevent wraps on it for long URIs).
  870. // Just "export {...};" or "export class ..." should not be treated as
  871. // an import in this sense.
  872. if (Line.First->is(tok::kw_export) &&
  873. CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
  874. CurrentToken->Next->isStringLiteral())
  875. ImportStatement = true;
  876. if (isClosureImportStatement(*CurrentToken))
  877. ImportStatement = true;
  878. }
  879. if (!consumeToken())
  880. return LT_Invalid;
  881. }
  882. if (KeywordVirtualFound)
  883. return LT_VirtualFunctionDecl;
  884. if (ImportStatement)
  885. return LT_ImportStatement;
  886. if (Line.startsWith(TT_ObjCMethodSpecifier)) {
  887. if (Contexts.back().FirstObjCSelectorName)
  888. Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
  889. Contexts.back().LongestObjCSelectorName;
  890. return LT_ObjCMethodDecl;
  891. }
  892. return LT_Other;
  893. }
  894. private:
  895. bool isClosureImportStatement(const FormatToken &Tok) {
  896. // FIXME: Closure-library specific stuff should not be hard-coded but be
  897. // configurable.
  898. return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
  899. Tok.Next->Next && (Tok.Next->Next->TokenText == "module" ||
  900. Tok.Next->Next->TokenText == "provide" ||
  901. Tok.Next->Next->TokenText == "require" ||
  902. Tok.Next->Next->TokenText == "forwardDeclare") &&
  903. Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
  904. }
  905. void resetTokenMetadata(FormatToken *Token) {
  906. if (!Token)
  907. return;
  908. // Reset token type in case we have already looked at it and then
  909. // recovered from an error (e.g. failure to find the matching >).
  910. if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro,
  911. TT_FunctionLBrace, TT_ImplicitStringLiteral,
  912. TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow,
  913. TT_OverloadedOperator, TT_RegexLiteral,
  914. TT_TemplateString, TT_ObjCStringLiteral))
  915. CurrentToken->Type = TT_Unknown;
  916. CurrentToken->Role.reset();
  917. CurrentToken->MatchingParen = nullptr;
  918. CurrentToken->FakeLParens.clear();
  919. CurrentToken->FakeRParens = 0;
  920. }
  921. void next() {
  922. if (CurrentToken) {
  923. CurrentToken->NestingLevel = Contexts.size() - 1;
  924. CurrentToken->BindingStrength = Contexts.back().BindingStrength;
  925. modifyContext(*CurrentToken);
  926. determineTokenType(*CurrentToken);
  927. CurrentToken = CurrentToken->Next;
  928. }
  929. resetTokenMetadata(CurrentToken);
  930. }
  931. /// \brief A struct to hold information valid in a specific context, e.g.
  932. /// a pair of parenthesis.
  933. struct Context {
  934. Context(tok::TokenKind ContextKind, unsigned BindingStrength,
  935. bool IsExpression)
  936. : ContextKind(ContextKind), BindingStrength(BindingStrength),
  937. IsExpression(IsExpression) {}
  938. tok::TokenKind ContextKind;
  939. unsigned BindingStrength;
  940. bool IsExpression;
  941. unsigned LongestObjCSelectorName = 0;
  942. bool ColonIsForRangeExpr = false;
  943. bool ColonIsDictLiteral = false;
  944. bool ColonIsObjCMethodExpr = false;
  945. FormatToken *FirstObjCSelectorName = nullptr;
  946. FormatToken *FirstStartOfName = nullptr;
  947. bool CanBeExpression = true;
  948. bool InTemplateArgument = false;
  949. bool InCtorInitializer = false;
  950. bool InInheritanceList = false;
  951. bool CaretFound = false;
  952. bool IsForEachMacro = false;
  953. };
  954. /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime
  955. /// of each instance.
  956. struct ScopedContextCreator {
  957. AnnotatingParser &P;
  958. ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
  959. unsigned Increase)
  960. : P(P) {
  961. P.Contexts.push_back(Context(ContextKind,
  962. P.Contexts.back().BindingStrength + Increase,
  963. P.Contexts.back().IsExpression));
  964. }
  965. ~ScopedContextCreator() { P.Contexts.pop_back(); }
  966. };
  967. void modifyContext(const FormatToken &Current) {
  968. if (Current.getPrecedence() == prec::Assignment &&
  969. !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) &&
  970. // Type aliases use `type X = ...;` in TypeScript and can be exported
  971. // using `export type ...`.
  972. !(Style.Language == FormatStyle::LK_JavaScript &&
  973. (Line.startsWith(Keywords.kw_type, tok::identifier) ||
  974. Line.startsWith(tok::kw_export, Keywords.kw_type,
  975. tok::identifier))) &&
  976. (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
  977. Contexts.back().IsExpression = true;
  978. if (!Line.startsWith(TT_UnaryOperator)) {
  979. for (FormatToken *Previous = Current.Previous;
  980. Previous && Previous->Previous &&
  981. !Previous->Previous->isOneOf(tok::comma, tok::semi);
  982. Previous = Previous->Previous) {
  983. if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
  984. Previous = Previous->MatchingParen;
  985. if (!Previous)
  986. break;
  987. }
  988. if (Previous->opensScope())
  989. break;
  990. if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
  991. Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
  992. Previous->Previous && Previous->Previous->isNot(tok::equal))
  993. Previous->Type = TT_PointerOrReference;
  994. }
  995. }
  996. } else if (Current.is(tok::lessless) &&
  997. (!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
  998. Contexts.back().IsExpression = true;
  999. } else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
  1000. Contexts.back().IsExpression = true;
  1001. } else if (Current.is(TT_TrailingReturnArrow)) {
  1002. Contexts.back().IsExpression = false;
  1003. } else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
  1004. Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
  1005. } else if (Current.Previous &&
  1006. Current.Previous->is(TT_CtorInitializerColon)) {
  1007. Contexts.back().IsExpression = true;
  1008. Contexts.back().InCtorInitializer = true;
  1009. } else if (Current.Previous &&
  1010. Current.Previous->is(TT_InheritanceColon)) {
  1011. Contexts.back().InInheritanceList = true;
  1012. } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
  1013. for (FormatToken *Previous = Current.Previous;
  1014. Previous && Previous->isOneOf(tok::star, tok::amp);
  1015. Previous = Previous->Previous)
  1016. Previous->Type = TT_PointerOrReference;
  1017. if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer)
  1018. Contexts.back().IsExpression = false;
  1019. } else if (Current.is(tok::kw_new)) {
  1020. Contexts.back().CanBeExpression = false;
  1021. } else if (Current.isOneOf(tok::semi, tok::exclaim)) {
  1022. // This should be the condition or increment in a for-loop.
  1023. Contexts.back().IsExpression = true;
  1024. }
  1025. }
  1026. void determineTokenType(FormatToken &Current) {
  1027. if (!Current.is(TT_Unknown))
  1028. // The token type is already known.
  1029. return;
  1030. if (Style.Language == FormatStyle::LK_JavaScript) {
  1031. if (Current.is(tok::exclaim)) {
  1032. if (Current.Previous &&
  1033. (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace,
  1034. tok::r_paren, tok::r_square,
  1035. tok::r_brace) ||
  1036. Current.Previous->Tok.isLiteral())) {
  1037. Current.Type = TT_JsNonNullAssertion;
  1038. return;
  1039. }
  1040. if (Current.Next &&
  1041. Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
  1042. Current.Type = TT_JsNonNullAssertion;
  1043. return;
  1044. }
  1045. }
  1046. }
  1047. // Line.MightBeFunctionDecl can only be true after the parentheses of a
  1048. // function declaration have been found. In this case, 'Current' is a
  1049. // trailing token of this declaration and thus cannot be a name.
  1050. if (Current.is(Keywords.kw_instanceof)) {
  1051. Current.Type = TT_BinaryOperator;
  1052. } else if (isStartOfName(Current) &&
  1053. (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
  1054. Contexts.back().FirstStartOfName = &Current;
  1055. Current.Type = TT_StartOfName;
  1056. } else if (Current.is(tok::semi)) {
  1057. // Reset FirstStartOfName after finding a semicolon so that a for loop
  1058. // with multiple increment statements is not confused with a for loop
  1059. // having multiple variable declarations.
  1060. Contexts.back().FirstStartOfName = nullptr;
  1061. } else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
  1062. AutoFound = true;
  1063. } else if (Current.is(tok::arrow) &&
  1064. Style.Language == FormatStyle::LK_Java) {
  1065. Current.Type = TT_LambdaArrow;
  1066. } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
  1067. Current.NestingLevel == 0) {
  1068. Current.Type = TT_TrailingReturnArrow;
  1069. } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
  1070. Current.Type =
  1071. determineStarAmpUsage(Current, Contexts.back().CanBeExpression &&
  1072. Contexts.back().IsExpression,
  1073. Contexts.back().InTemplateArgument);
  1074. } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
  1075. Current.Type = determinePlusMinusCaretUsage(Current);
  1076. if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
  1077. Contexts.back().CaretFound = true;
  1078. } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
  1079. Current.Type = determineIncrementUsage(Current);
  1080. } else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
  1081. Current.Type = TT_UnaryOperator;
  1082. } else if (Current.is(tok::question)) {
  1083. if (Style.Language == FormatStyle::LK_JavaScript &&
  1084. Line.MustBeDeclaration && !Contexts.back().IsExpression) {
  1085. // In JavaScript, `interface X { foo?(): bar; }` is an optional method
  1086. // on the interface, not a ternary expression.
  1087. Current.Type = TT_JsTypeOptionalQuestion;
  1088. } else {
  1089. Current.Type = TT_ConditionalExpr;
  1090. }
  1091. } else if (Current.isBinaryOperator() &&
  1092. (!Current.Previous || Current.Previous->isNot(tok::l_square))) {
  1093. Current.Type = TT_BinaryOperator;
  1094. } else if (Current.is(tok::comment)) {
  1095. if (Current.TokenText.startswith("/*")) {
  1096. if (Current.TokenText.endswith("*/"))
  1097. Current.Type = TT_BlockComment;
  1098. else
  1099. // The lexer has for some reason determined a comment here. But we
  1100. // cannot really handle it, if it isn't properly terminated.
  1101. Current.Tok.setKind(tok::unknown);
  1102. } else {
  1103. Current.Type = TT_LineComment;
  1104. }
  1105. } else if (Current.is(tok::r_paren)) {
  1106. if (rParenEndsCast(Current))
  1107. Current.Type = TT_CastRParen;
  1108. if (Current.MatchingParen && Current.Next &&
  1109. !Current.Next->isBinaryOperator() &&
  1110. !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
  1111. tok::comma, tok::period, tok::arrow,
  1112. tok::coloncolon))
  1113. if (FormatToken *AfterParen = Current.MatchingParen->Next) {
  1114. // Make sure this isn't the return type of an Obj-C block declaration
  1115. if (AfterParen->Tok.isNot(tok::caret)) {
  1116. if (FormatToken *BeforeParen = Current.MatchingParen->Previous)
  1117. if (BeforeParen->is(tok::identifier) &&
  1118. BeforeParen->TokenText == BeforeParen->TokenText.upper() &&
  1119. (!BeforeParen->Previous ||
  1120. BeforeParen->Previous->ClosesTemplateDeclaration))
  1121. Current.Type = TT_FunctionAnnotationRParen;
  1122. }
  1123. }
  1124. } else if (Current.is(tok::at) && Current.Next &&
  1125. Style.Language != FormatStyle::LK_JavaScript &&
  1126. Style.Language != FormatStyle::LK_Java) {
  1127. // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it
  1128. // marks declarations and properties that need special formatting.
  1129. switch (Current.Next->Tok.getObjCKeywordID()) {
  1130. case tok::objc_interface:
  1131. case tok::objc_implementation:
  1132. case tok::objc_protocol:
  1133. Current.Type = TT_ObjCDecl;
  1134. break;
  1135. case tok::objc_property:
  1136. Current.Type = TT_ObjCProperty;
  1137. break;
  1138. default:
  1139. break;
  1140. }
  1141. } else if (Current.is(tok::period)) {
  1142. FormatToken *PreviousNoComment = Current.getPreviousNonComment();
  1143. if (PreviousNoComment &&
  1144. PreviousNoComment->isOneOf(tok::comma, tok::l_brace))
  1145. Current.Type = TT_DesignatedInitializerPeriod;
  1146. else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
  1147. Current.Previous->isOneOf(TT_JavaAnnotation,
  1148. TT_LeadingJavaAnnotation)) {
  1149. Current.Type = Current.Previous->Type;
  1150. }
  1151. } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
  1152. Current.Previous &&
  1153. !Current.Previous->isOneOf(tok::equal, tok::at) &&
  1154. Line.MightBeFunctionDecl && Contexts.size() == 1) {
  1155. // Line.MightBeFunctionDecl can only be true after the parentheses of a
  1156. // function declaration have been found.
  1157. Current.Type = TT_TrailingAnnotation;
  1158. } else if ((Style.Language == FormatStyle::LK_Java ||
  1159. Style.Language == FormatStyle::LK_JavaScript) &&
  1160. Current.Previous) {
  1161. if (Current.Previous->is(tok::at) &&
  1162. Current.isNot(Keywords.kw_interface)) {
  1163. const FormatToken &AtToken = *Current.Previous;
  1164. const FormatToken *Previous = AtToken.getPreviousNonComment();
  1165. if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
  1166. Current.Type = TT_LeadingJavaAnnotation;
  1167. else
  1168. Current.Type = TT_JavaAnnotation;
  1169. } else if (Current.Previous->is(tok::period) &&
  1170. Current.Previous->isOneOf(TT_JavaAnnotation,
  1171. TT_LeadingJavaAnnotation)) {
  1172. Current.Type = Current.Previous->Type;
  1173. }
  1174. }
  1175. }
  1176. /// \brief Take a guess at whether \p Tok starts a name of a function or
  1177. /// variable declaration.
  1178. ///
  1179. /// This is a heuristic based on whether \p Tok is an identifier following
  1180. /// something that is likely a type.
  1181. bool isStartOfName(const FormatToken &Tok) {
  1182. if (Tok.isNot(tok::identifier) || !Tok.Previous)
  1183. return false;
  1184. if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
  1185. Keywords.kw_as))
  1186. return false;
  1187. if (Style.Language == FormatStyle::LK_JavaScript &&
  1188. Tok.Previous->is(Keywords.kw_in))
  1189. return false;
  1190. // Skip "const" as it does not have an influence on whether this is a name.
  1191. FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
  1192. while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
  1193. PreviousNotConst = PreviousNotConst->getPreviousNonComment();
  1194. if (!PreviousNotConst)
  1195. return false;
  1196. bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
  1197. PreviousNotConst->Previous &&
  1198. PreviousNotConst->Previous->is(tok::hash);
  1199. if (PreviousNotConst->is(TT_TemplateCloser))
  1200. return PreviousNotConst && PreviousNotConst->MatchingParen &&
  1201. PreviousNotConst->MatchingParen->Previous &&
  1202. PreviousNotConst->MatchingParen->Previous->isNot(tok::period) &&
  1203. PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template);
  1204. if (PreviousNotConst->is(tok::r_paren) && PreviousNotConst->MatchingParen &&
  1205. PreviousNotConst->MatchingParen->Previous &&
  1206. PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype))
  1207. return true;
  1208. return (!IsPPKeyword &&
  1209. PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) ||
  1210. PreviousNotConst->is(TT_PointerOrReference) ||
  1211. PreviousNotConst->isSimpleTypeSpecifier();
  1212. }
  1213. /// \brief Determine whether ')' is ending a cast.
  1214. bool rParenEndsCast(const FormatToken &Tok) {
  1215. // C-style casts are only used in C++ and Java.
  1216. if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java)
  1217. return false;
  1218. // Empty parens aren't casts and there are no casts at the end of the line.
  1219. if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
  1220. return false;
  1221. FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
  1222. if (LeftOfParens) {
  1223. // If there is a closing parenthesis left of the current parentheses,
  1224. // look past it as these might be chained casts.
  1225. if (LeftOfParens->is(tok::r_paren)) {
  1226. if (!LeftOfParens->MatchingParen ||
  1227. !LeftOfParens->MatchingParen->Previous)
  1228. return false;
  1229. LeftOfParens = LeftOfParens->MatchingParen->Previous;
  1230. }
  1231. // If there is an identifier (or with a few exceptions a keyword) right
  1232. // before the parentheses, this is unlikely to be a cast.
  1233. if (LeftOfParens->Tok.getIdentifierInfo() &&
  1234. !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
  1235. tok::kw_delete))
  1236. return false;
  1237. // Certain other tokens right before the parentheses are also signals that
  1238. // this cannot be a cast.
  1239. if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
  1240. TT_TemplateCloser, tok::ellipsis))
  1241. return false;
  1242. }
  1243. if (Tok.Next->is(tok::question))
  1244. return false;
  1245. // As Java has no function types, a "(" after the ")" likely means that this
  1246. // is a cast.
  1247. if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
  1248. return true;
  1249. // If a (non-string) literal follows, this is likely a cast.
  1250. if (Tok.Next->isNot(tok::string_literal) &&
  1251. (Tok.Next->Tok.isLiteral() ||
  1252. Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof)))
  1253. return true;
  1254. // Heuristically try to determine whether the parentheses contain a type.
  1255. bool ParensAreType =
  1256. !Tok.Previous ||
  1257. Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) ||
  1258. Tok.Previous->isSimpleTypeSpecifier();
  1259. bool ParensCouldEndDecl =
  1260. Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
  1261. if (ParensAreType && !ParensCouldEndDecl)
  1262. return true;
  1263. // At this point, we heuristically assume that there are no casts at the
  1264. // start of the line. We assume that we have found most cases where there
  1265. // are by the logic above, e.g. "(void)x;".
  1266. if (!LeftOfParens)
  1267. return false;
  1268. // Certain token types inside the parentheses mean that this can't be a
  1269. // cast.
  1270. for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
  1271. Token = Token->Next)
  1272. if (Token->is(TT_BinaryOperator))
  1273. return false;
  1274. // If the following token is an identifier or 'this', this is a cast. All
  1275. // cases where this can be something else are handled above.
  1276. if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
  1277. return true;
  1278. if (!Tok.Next->Next)
  1279. return false;
  1280. // If the next token after the parenthesis is a unary operator, assume
  1281. // that this is cast, unless there are unexpected tokens inside the
  1282. // parenthesis.
  1283. bool NextIsUnary =
  1284. Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star);
  1285. if (!NextIsUnary || Tok.Next->is(tok::plus) ||
  1286. !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant))
  1287. return false;
  1288. // Search for unexpected tokens.
  1289. for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
  1290. Prev = Prev->Previous) {
  1291. if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
  1292. return false;
  1293. }
  1294. return true;
  1295. }
  1296. /// \brief Return the type of the given token assuming it is * or &.
  1297. TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
  1298. bool InTemplateArgument) {
  1299. if (Style.Language == FormatStyle::LK_JavaScript)
  1300. return TT_BinaryOperator;
  1301. const FormatToken *PrevToken = Tok.getPreviousNonComment();
  1302. if (!PrevToken)
  1303. return TT_UnaryOperator;
  1304. const FormatToken *NextToken = Tok.getNextNonComment();
  1305. if (!NextToken ||
  1306. NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) ||
  1307. (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment()))
  1308. return TT_PointerOrReference;
  1309. if (PrevToken->is(tok::coloncolon))
  1310. return TT_PointerOrReference;
  1311. if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace,
  1312. tok::comma, tok::semi, tok::kw_return, tok::colon,
  1313. tok::equal, tok::kw_delete, tok::kw_sizeof,
  1314. tok::kw_throw) ||
  1315. PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr,
  1316. TT_UnaryOperator, TT_CastRParen))
  1317. return TT_UnaryOperator;
  1318. if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
  1319. return TT_PointerOrReference;
  1320. if (NextToken->is(tok::kw_operator) && !IsExpression)
  1321. return TT_PointerOrReference;
  1322. if (NextToken->isOneOf(tok::comma, tok::semi))
  1323. return TT_PointerOrReference;
  1324. if (PrevToken->is(tok::r_paren) && PrevToken->MatchingParen) {
  1325. FormatToken *TokenBeforeMatchingParen =
  1326. PrevToken->MatchingParen->getPreviousNonComment();
  1327. if (TokenBeforeMatchingParen &&
  1328. TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
  1329. return TT_PointerOrReference;
  1330. }
  1331. if (PrevToken->Tok.isLiteral() ||
  1332. PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
  1333. tok::kw_false, tok::r_brace) ||
  1334. NextToken->Tok.isLiteral() ||
  1335. NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
  1336. NextToken->isUnaryOperator() ||
  1337. // If we know we're in a template argument, there are no named
  1338. // declarations. Thus, having an identifier on the right-hand side
  1339. // indicates a binary operator.
  1340. (InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
  1341. return TT_BinaryOperator;
  1342. // "&&(" is quite unlikely to be two successive unary "&".
  1343. if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren))
  1344. return TT_BinaryOperator;
  1345. // This catches some cases where evaluation order is used as control flow:
  1346. // aaa && aaa->f();
  1347. const FormatToken *NextNextToken = NextToken->getNextNonComment();
  1348. if (NextNextToken && NextNextToken->is(tok::arrow))
  1349. return TT_BinaryOperator;
  1350. // It is very unlikely that we are going to find a pointer or reference type
  1351. // definition on the RHS of an assignment.
  1352. if (IsExpression && !Contexts.back().CaretFound)
  1353. return TT_BinaryOperator;
  1354. return TT_PointerOrReference;
  1355. }
  1356. TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
  1357. const FormatToken *PrevToken = Tok.getPreviousNonComment();
  1358. if (!PrevToken)
  1359. return TT_UnaryOperator;
  1360. if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
  1361. !PrevToken->is(tok::exclaim))
  1362. // There aren't any trailing unary operators except for TypeScript's
  1363. // non-null operator (!). Thus, this must be squence of leading operators.
  1364. return TT_UnaryOperator;
  1365. // Use heuristics to recognize unary operators.
  1366. if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square,
  1367. tok::question, tok::colon, tok::kw_return,
  1368. tok::kw_case, tok::at, tok::l_brace))
  1369. return TT_UnaryOperator;
  1370. // There can't be two consecutive binary operators.
  1371. if (PrevToken->is(TT_BinaryOperator))
  1372. return TT_UnaryOperator;
  1373. // Fall back to marking the token as binary operator.
  1374. return TT_BinaryOperator;
  1375. }
  1376. /// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
  1377. TokenType determineIncrementUsage(const FormatToken &Tok) {
  1378. const FormatToken *PrevToken = Tok.getPreviousNonComment();
  1379. if (!PrevToken || PrevToken->is(TT_CastRParen))
  1380. return TT_UnaryOperator;
  1381. if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
  1382. return TT_TrailingUnaryOperator;
  1383. return TT_UnaryOperator;
  1384. }
  1385. SmallVector<Context, 8> Contexts;
  1386. const FormatStyle &Style;
  1387. AnnotatedLine &Line;
  1388. FormatToken *CurrentToken;
  1389. bool AutoFound;
  1390. const AdditionalKeywords &Keywords;
  1391. // Set of "<" tokens that do not open a template parameter list. If parseAngle
  1392. // determines that a specific token can't be a template opener, it will make
  1393. // same decision irrespective of the decisions for tokens leading up to it.
  1394. // Store this information to prevent this from causing exponential runtime.
  1395. llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
  1396. };
  1397. static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
  1398. static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
  1399. /// \brief Parses binary expressions by inserting fake parenthesis based on
  1400. /// operator precedence.
  1401. class ExpressionParser {
  1402. public:
  1403. ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
  1404. AnnotatedLine &Line)
  1405. : Style(Style), Keywords(Keywords), Current(Line.First) {}
  1406. /// \brief Parse expressions with the given operatore precedence.
  1407. void parse(int Precedence = 0) {
  1408. // Skip 'return' and ObjC selector colons as they are not part of a binary
  1409. // expression.
  1410. while (Current && (Current->is(tok::kw_return) ||
  1411. (Current->is(tok::colon) &&
  1412. Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral))))
  1413. next();
  1414. if (!Current || Precedence > PrecedenceArrowAndPeriod)
  1415. return;
  1416. // Conditional expressions need to be parsed separately for proper nesting.
  1417. if (Precedence == prec::Conditional) {
  1418. parseConditionalExpr();
  1419. return;
  1420. }
  1421. // Parse unary operators, which all have a higher precedence than binary
  1422. // operators.
  1423. if (Precedence == PrecedenceUnaryOperator) {
  1424. parseUnaryOperator();
  1425. return;
  1426. }
  1427. FormatToken *Start = Current;
  1428. FormatToken *LatestOperator = nullptr;
  1429. unsigned OperatorIndex = 0;
  1430. while (Current) {
  1431. // Consume operators with higher precedence.
  1432. parse(Precedence + 1);
  1433. int CurrentPrecedence = getCurrentPrecedence();
  1434. if (Current && Current->is(TT_SelectorName) &&
  1435. Precedence == CurrentPrecedence) {
  1436. if (LatestOperator)
  1437. addFakeParenthesis(Start, prec::Level(Precedence));
  1438. Start = Current;
  1439. }
  1440. // At the end of the line or when an operator with higher precedence is
  1441. // found, insert fake parenthesis and return.
  1442. if (!Current ||
  1443. (Current->closesScope() &&
  1444. (Current->MatchingParen || Current->is(TT_TemplateString))) ||
  1445. (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
  1446. (CurrentPrecedence == prec::Conditional &&
  1447. Precedence == prec::Assignment && Current->is(tok::colon))) {
  1448. break;
  1449. }
  1450. // Consume scopes: (), [], <> and {}
  1451. if (Current->opensScope()) {
  1452. // In fragment of a JavaScript template string can look like '}..${' and
  1453. // thus close a scope and open a new one at the same time.
  1454. while (Current && (!Current->closesScope() || Current->opensScope())) {
  1455. next();
  1456. parse();
  1457. }
  1458. next();
  1459. } else {
  1460. // Operator found.
  1461. if (CurrentPrecedence == Precedence) {
  1462. if (LatestOperator)
  1463. LatestOperator->NextOperator = Current;
  1464. LatestOperator = Current;
  1465. Current->OperatorIndex = OperatorIndex;
  1466. ++OperatorIndex;
  1467. }
  1468. next(/*SkipPastLeadingComments=*/Precedence > 0);
  1469. }
  1470. }
  1471. if (LatestOperator && (Current || Precedence > 0)) {
  1472. // LatestOperator->LastOperator = true;
  1473. if (Precedence == PrecedenceArrowAndPeriod) {
  1474. // Call expressions don't have a binary operator precedence.
  1475. addFakeParenthesis(Start, prec::Unknown);
  1476. } else {
  1477. addFakeParenthesis(Start, prec::Level(Precedence));
  1478. }
  1479. }
  1480. }
  1481. private:
  1482. /// \brief Gets the precedence (+1) of the given token for binary operators
  1483. /// and other tokens that we treat like binary operators.
  1484. int getCurrentPrecedence() {
  1485. if (Current) {
  1486. const FormatToken *NextNonComment = Current->getNextNonComment();
  1487. if (Current->is(TT_ConditionalExpr))
  1488. return prec::Conditional;
  1489. if (NextNonComment && Current->is(TT_SelectorName) &&
  1490. (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
  1491. ((Style.Language == FormatStyle::LK_Proto ||
  1492. Style.Language == FormatStyle::LK_TextProto) &&
  1493. NextNonComment->is(tok::less))))
  1494. return prec::Assignment;
  1495. if (Current->is(TT_JsComputedPropertyName))
  1496. return prec::Assignment;
  1497. if (Current->is(TT_LambdaArrow))
  1498. return prec::Comma;
  1499. if (Current->is(TT_JsFatArrow))
  1500. return prec::Assignment;
  1501. if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
  1502. (Current->is(tok::comment) && NextNonComment &&
  1503. NextNonComment->is(TT_SelectorName)))
  1504. return 0;
  1505. if (Current->is(TT_RangeBasedForLoopColon))
  1506. return prec::Comma;
  1507. if ((Style.Language == FormatStyle::LK_Java ||
  1508. Style.Language == FormatStyle::LK_JavaScript) &&
  1509. Current->is(Keywords.kw_instanceof))
  1510. return prec::Relational;
  1511. if (Style.Language == FormatStyle::LK_JavaScript &&
  1512. Current->isOneOf(Keywords.kw_in, Keywords.kw_as))
  1513. return prec::Relational;
  1514. if (Current->is(TT_BinaryOperator) || Current->is(tok::comma))
  1515. return Current->getPrecedence();
  1516. if (Current->isOneOf(tok::period, tok::arrow))
  1517. return PrecedenceArrowAndPeriod;
  1518. if ((Style.Language == FormatStyle::LK_Java ||
  1519. Style.Language == FormatStyle::LK_JavaScript) &&
  1520. Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements,
  1521. Keywords.kw_throws))
  1522. return 0;
  1523. }
  1524. return -1;
  1525. }
  1526. void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) {
  1527. Start->FakeLParens.push_back(Precedence);
  1528. if (Precedence > prec::Unknown)
  1529. Start->StartsBinaryExpression = true;
  1530. if (Current) {
  1531. FormatToken *Previous = Current->Previous;
  1532. while (Previous->is(tok::comment) && Previous->Previous)
  1533. Previous = Previous->Previous;
  1534. ++Previous->FakeRParens;
  1535. if (Precedence > prec::Unknown)
  1536. Previous->EndsBinaryExpression = true;
  1537. }
  1538. }
  1539. /// \brief Parse unary operator expressions and surround them with fake
  1540. /// parentheses if appropriate.
  1541. void parseUnaryOperator() {
  1542. if (!Current || Current->isNot(TT_UnaryOperator)) {
  1543. parse(PrecedenceArrowAndPeriod);
  1544. return;
  1545. }
  1546. FormatToken *Start = Current;
  1547. next();
  1548. parseUnaryOperator();
  1549. // The actual precedence doesn't matter.
  1550. addFakeParenthesis(Start, prec::Unknown);
  1551. }
  1552. void parseConditionalExpr() {
  1553. while (Current && Current->isTrailingComment()) {
  1554. next();
  1555. }
  1556. FormatToken *Start = Current;
  1557. parse(prec::LogicalOr);
  1558. if (!Current || !Current->is(tok::question))
  1559. return;
  1560. next();
  1561. parse(prec::Assignment);
  1562. if (!Current || Current->isNot(TT_ConditionalExpr))
  1563. return;
  1564. next();
  1565. parse(prec::Assignment);
  1566. addFakeParenthesis(Start, prec::Conditional);
  1567. }
  1568. void next(bool SkipPastLeadingComments = true) {
  1569. if (Current)
  1570. Current = Current->Next;
  1571. while (Current &&
  1572. (Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
  1573. Current->isTrailingComment())
  1574. Current = Current->Next;
  1575. }
  1576. const FormatStyle &Style;
  1577. const AdditionalKeywords &Keywords;
  1578. FormatToken *Current;
  1579. };
  1580. } // end anonymous namespace
  1581. void TokenAnnotator::setCommentLineLevels(
  1582. SmallVectorImpl<AnnotatedLine *> &Lines) {
  1583. const AnnotatedLine *NextNonCommentLine = nullptr;
  1584. for (SmallVectorImpl<AnnotatedLine *>::reverse_iterator I = Lines.rbegin(),
  1585. E = Lines.rend();
  1586. I != E; ++I) {
  1587. bool CommentLine = true;
  1588. for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) {
  1589. if (!Tok->is(tok::comment)) {
  1590. CommentLine = false;
  1591. break;
  1592. }
  1593. }
  1594. if (NextNonCommentLine && CommentLine) {
  1595. // If the comment is currently aligned with the line immediately following
  1596. // it, that's probably intentional and we should keep it.
  1597. bool AlignedWithNextLine =
  1598. NextNonCommentLine->First->NewlinesBefore <= 1 &&
  1599. NextNonCommentLine->First->OriginalColumn ==
  1600. (*I)->First->OriginalColumn;
  1601. if (AlignedWithNextLine)
  1602. (*I)->Level = NextNonCommentLine->Level;
  1603. } else {
  1604. NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr;
  1605. }
  1606. setCommentLineLevels((*I)->Children);
  1607. }
  1608. }
  1609. static unsigned maxNestingDepth(const AnnotatedLine &Line) {
  1610. unsigned Result = 0;
  1611. for (const auto* Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
  1612. Result = std::max(Result, Tok->NestingLevel);
  1613. return Result;
  1614. }
  1615. void TokenAnnotator::annotate(AnnotatedLine &Line) {
  1616. for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
  1617. E = Line.Children.end();
  1618. I != E; ++I) {
  1619. annotate(**I);
  1620. }
  1621. AnnotatingParser Parser(Style, Line, Keywords);
  1622. Line.Type = Parser.parseLine();
  1623. // With very deep nesting, ExpressionParser uses lots of stack and the
  1624. // formatting algorithm is very slow. We're not going to do a good job here
  1625. // anyway - it's probably generated code being formatted by mistake.
  1626. // Just skip the whole line.
  1627. if (maxNestingDepth(Line) > 50)
  1628. Line.Type = LT_Invalid;
  1629. if (Line.Type == LT_Invalid)
  1630. return;
  1631. ExpressionParser ExprParser(Style, Keywords, Line);
  1632. ExprParser.parse();
  1633. if (Line.startsWith(TT_ObjCMethodSpecifier))
  1634. Line.Type = LT_ObjCMethodDecl;
  1635. else if (Line.startsWith(TT_ObjCDecl))
  1636. Line.Type = LT_ObjCDecl;
  1637. else if (Line.startsWith(TT_ObjCProperty))
  1638. Line.Type = LT_ObjCProperty;
  1639. Line.First->SpacesRequiredBefore = 1;
  1640. Line.First->CanBreakBefore = Line.First->MustBreakBefore;
  1641. }
  1642. // This function heuristically determines whether 'Current' starts the name of a
  1643. // function declaration.
  1644. static bool isFunctionDeclarationName(const FormatToken &Current,
  1645. const AnnotatedLine &Line) {
  1646. auto skipOperatorName = [](const FormatToken* Next) -> const FormatToken* {
  1647. for (; Next; Next = Next->Next) {
  1648. if (Next->is(TT_OverloadedOperatorLParen))
  1649. return Next;
  1650. if (Next->is(TT_OverloadedOperator))
  1651. continue;
  1652. if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
  1653. // For 'new[]' and 'delete[]'.
  1654. if (Next->Next && Next->Next->is(tok::l_square) &&
  1655. Next->Next->Next && Next->Next->Next->is(tok::r_square))
  1656. Next = Next->Next->Next;
  1657. continue;
  1658. }
  1659. break;
  1660. }
  1661. return nullptr;
  1662. };
  1663. // Find parentheses of parameter list.
  1664. const FormatToken *Next = Current.Next;
  1665. if (Current.is(tok::kw_operator)) {
  1666. if (Current.Previous && Current.Previous->is(tok::coloncolon))
  1667. return false;
  1668. Next = skipOperatorName(Next);
  1669. } else {
  1670. if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
  1671. return false;
  1672. for (; Next; Next = Next->Next) {
  1673. if (Next->is(TT_TemplateOpener)) {
  1674. Next = Next->MatchingParen;
  1675. } else if (Next->is(tok::coloncolon)) {
  1676. Next = Next->Next;
  1677. if (!Next)
  1678. return false;
  1679. if (Next->is(tok::kw_operator)) {
  1680. Next = skipOperatorName(Next->Next);
  1681. break;
  1682. }
  1683. if (!Next->is(tok::identifier))
  1684. return false;
  1685. } else if (Next->is(tok::l_paren)) {
  1686. break;
  1687. } else {
  1688. return false;
  1689. }
  1690. }
  1691. }
  1692. // Check whether parameter list can belong to a function declaration.
  1693. if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
  1694. return false;
  1695. // If the lines ends with "{", this is likely an function definition.
  1696. if (Line.Last->is(tok::l_brace))
  1697. return true;
  1698. if (Next->Next == Next->MatchingParen)
  1699. return true; // Empty parentheses.
  1700. // If there is an &/&& after the r_paren, this is likely a function.
  1701. if (Next->MatchingParen->Next &&
  1702. Next->MatchingParen->Next->is(TT_PointerOrReference))
  1703. return true;
  1704. for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
  1705. Tok = Tok->Next) {
  1706. if (Tok->is(tok::l_paren) && Tok->MatchingParen) {
  1707. Tok = Tok->MatchingParen;
  1708. continue;
  1709. }
  1710. if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
  1711. Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis))
  1712. return true;
  1713. if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
  1714. Tok->Tok.isLiteral())
  1715. return false;
  1716. }
  1717. return false;
  1718. }
  1719. bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
  1720. assert(Line.MightBeFunctionDecl);
  1721. if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
  1722. Style.AlwaysBreakAfterReturnType ==
  1723. FormatStyle::RTBS_TopLevelDefinitions) &&
  1724. Line.Level > 0)
  1725. return false;
  1726. switch (Style.AlwaysBreakAfterReturnType) {
  1727. case FormatStyle::RTBS_None:
  1728. return false;
  1729. case FormatStyle::RTBS_All:
  1730. case FormatStyle::RTBS_TopLevel:
  1731. return true;
  1732. case FormatStyle::RTBS_AllDefinitions:
  1733. case FormatStyle::RTBS_TopLevelDefinitions:
  1734. return Line.mightBeFunctionDefinition();
  1735. }
  1736. return false;
  1737. }
  1738. void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
  1739. for (SmallVectorImpl<AnnotatedLine *>::iterator I = Line.Children.begin(),
  1740. E = Line.Children.end();
  1741. I != E; ++I) {
  1742. calculateFormattingInformation(**I);
  1743. }
  1744. Line.First->TotalLength =
  1745. Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth;
  1746. FormatToken *Current = Line.First->Next;
  1747. bool InFunctionDecl = Line.MightBeFunctionDecl;
  1748. while (Current) {
  1749. if (isFunctionDeclarationName(*Current, Line))
  1750. Current->Type = TT_FunctionDeclarationName;
  1751. if (Current->is(TT_LineComment)) {
  1752. if (Current->Previous->BlockKind == BK_BracedInit &&
  1753. Current->Previous->opensScope())
  1754. Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1;
  1755. else
  1756. Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
  1757. // If we find a trailing comment, iterate backwards to determine whether
  1758. // it seems to relate to a specific parameter. If so, break before that
  1759. // parameter to avoid changing the comment's meaning. E.g. don't move 'b'
  1760. // to the previous line in:
  1761. // SomeFunction(a,
  1762. // b, // comment
  1763. // c);
  1764. if (!Current->HasUnescapedNewline) {
  1765. for (FormatToken *Parameter = Current->Previous; Parameter;
  1766. Parameter = Parameter->Previous) {
  1767. if (Parameter->isOneOf(tok::comment, tok::r_brace))
  1768. break;
  1769. if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
  1770. if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
  1771. Parameter->HasUnescapedNewline)
  1772. Parameter->MustBreakBefore = true;
  1773. break;
  1774. }
  1775. }
  1776. }
  1777. } else if (Current->SpacesRequiredBefore == 0 &&
  1778. spaceRequiredBefore(Line, *Current)) {
  1779. Current->SpacesRequiredBefore = 1;
  1780. }
  1781. Current->MustBreakBefore =
  1782. Current->MustBreakBefore || mustBreakBefore(Line, *Current);
  1783. if (!Current->MustBreakBefore && InFunctionDecl &&
  1784. Current->is(TT_FunctionDeclarationName))
  1785. Current->MustBreakBefore = mustBreakForReturnType(Line);
  1786. Current->CanBreakBefore =
  1787. Current->MustBreakBefore || canBreakBefore(Line, *Current);
  1788. unsigned ChildSize = 0;
  1789. if (Current->Previous->Children.size() == 1) {
  1790. FormatToken &LastOfChild = *Current->Previous->Children[0]->Last;
  1791. ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
  1792. : LastOfChild.TotalLength + 1;
  1793. }
  1794. const FormatToken *Prev = Current->Previous;
  1795. if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
  1796. (Prev->Children.size() == 1 &&
  1797. Prev->Children[0]->First->MustBreakBefore) ||
  1798. Current->IsMultiline)
  1799. Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
  1800. else
  1801. Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
  1802. ChildSize + Current->SpacesRequiredBefore;
  1803. if (Current->is(TT_CtorInitializerColon))
  1804. InFunctionDecl = false;
  1805. // FIXME: Only calculate this if CanBreakBefore is true once static
  1806. // initializers etc. are sorted out.
  1807. // FIXME: Move magic numbers to a better place.
  1808. Current->SplitPenalty = 20 * Current->BindingStrength +
  1809. splitPenalty(Line, *Current, InFunctionDecl);
  1810. Current = Current->Next;
  1811. }
  1812. calculateUnbreakableTailLengths(Line);
  1813. unsigned IndentLevel = Line.Level;
  1814. for (Current = Line.First; Current != nullptr; Current = Current->Next) {
  1815. if (Current->Role)
  1816. Current->Role->precomputeFormattingInfos(Current);
  1817. if (Current->MatchingParen &&
  1818. Current->MatchingParen->opensBlockOrBlockTypeList(Style)) {
  1819. assert(IndentLevel > 0);
  1820. --IndentLevel;
  1821. }
  1822. Current->IndentLevel = IndentLevel;
  1823. if (Current->opensBlockOrBlockTypeList(Style))
  1824. ++IndentLevel;
  1825. }
  1826. DEBUG({ printDebugInfo(Line); });
  1827. }
  1828. void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) {
  1829. unsigned UnbreakableTailLength = 0;
  1830. FormatToken *Current = Line.Last;
  1831. while (Current) {
  1832. Current->UnbreakableTailLength = UnbreakableTailLength;
  1833. if (Current->CanBreakBefore ||
  1834. Current->isOneOf(tok::comment, tok::string_literal)) {
  1835. UnbreakableTailLength = 0;
  1836. } else {
  1837. UnbreakableTailLength +=
  1838. Current->ColumnWidth + Current->SpacesRequiredBefore;
  1839. }
  1840. Current = Current->Previous;
  1841. }
  1842. }
  1843. unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
  1844. const FormatToken &Tok,
  1845. bool InFunctionDecl) {
  1846. const FormatToken &Left = *Tok.Previous;
  1847. const FormatToken &Right = Tok;
  1848. if (Left.is(tok::semi))
  1849. return 0;
  1850. if (Style.Language == FormatStyle::LK_Java) {
  1851. if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
  1852. return 1;
  1853. if (Right.is(Keywords.kw_implements))
  1854. return 2;
  1855. if (Left.is(tok::comma) && Left.NestingLevel == 0)
  1856. return 3;
  1857. } else if (Style.Language == FormatStyle::LK_JavaScript) {
  1858. if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
  1859. return 100;
  1860. if (Left.is(TT_JsTypeColon))
  1861. return 35;
  1862. if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
  1863. (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
  1864. return 100;
  1865. // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()".
  1866. if (Left.opensScope() && Right.closesScope())
  1867. return 200;
  1868. }
  1869. if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
  1870. return 1;
  1871. if (Right.is(tok::l_square)) {
  1872. if (Style.Language == FormatStyle::LK_Proto)
  1873. return 1;
  1874. if (Left.is(tok::r_square))
  1875. return 200;
  1876. // Slightly prefer formatting local lambda definitions like functions.
  1877. if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
  1878. return 35;
  1879. if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
  1880. TT_ArrayInitializerLSquare,
  1881. TT_DesignatedInitializerLSquare))
  1882. return 500;
  1883. }
  1884. if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
  1885. Right.is(tok::kw_operator)) {
  1886. if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
  1887. return 3;
  1888. if (Left.is(TT_StartOfName))
  1889. return 110;
  1890. if (InFunctionDecl && Right.NestingLevel == 0)
  1891. return Style.PenaltyReturnTypeOnItsOwnLine;
  1892. return 200;
  1893. }
  1894. if (Right.is(TT_PointerOrReference))
  1895. return 190;
  1896. if (Right.is(TT_LambdaArrow))
  1897. return 110;
  1898. if (Left.is(tok::equal) && Right.is(tok::l_brace))
  1899. return 160;
  1900. if (Left.is(TT_CastRParen))
  1901. return 100;
  1902. if (Left.is(tok::coloncolon) ||
  1903. (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
  1904. return 500;
  1905. if (Left.isOneOf(tok::kw_class, tok::kw_struct))
  1906. return 5000;
  1907. if (Left.is(tok::comment))
  1908. return 1000;
  1909. if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon, TT_CtorInitializerColon))
  1910. return 2;
  1911. if (Right.isMemberAccess()) {
  1912. // Breaking before the "./->" of a chained call/member access is reasonably
  1913. // cheap, as formatting those with one call per line is generally
  1914. // desirable. In particular, it should be cheaper to break before the call
  1915. // than it is to break inside a call's parameters, which could lead to weird
  1916. // "hanging" indents. The exception is the very last "./->" to support this
  1917. // frequent pattern:
  1918. //
  1919. // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc(
  1920. // dddddddd);
  1921. //
  1922. // which might otherwise be blown up onto many lines. Here, clang-format
  1923. // won't produce "hanging" indents anyway as there is no other trailing
  1924. // call.
  1925. //
  1926. // Also apply higher penalty is not a call as that might lead to a wrapping
  1927. // like:
  1928. //
  1929. // aaaaaaa
  1930. // .aaaaaaaaa.bbbbbbbb(cccccccc);
  1931. return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
  1932. ? 150
  1933. : 35;
  1934. }
  1935. if (Right.is(TT_TrailingAnnotation) &&
  1936. (!Right.Next || Right.Next->isNot(tok::l_paren))) {
  1937. // Moving trailing annotations to the next line is fine for ObjC method
  1938. // declarations.
  1939. if (Line.startsWith(TT_ObjCMethodSpecifier))
  1940. return 10;
  1941. // Generally, breaking before a trailing annotation is bad unless it is
  1942. // function-like. It seems to be especially preferable to keep standard
  1943. // annotations (i.e. "const", "final" and "override") on the same line.
  1944. // Use a slightly higher penalty after ")" so that annotations like
  1945. // "const override" are kept together.
  1946. bool is_short_annotation = Right.TokenText.size() < 10;
  1947. return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
  1948. }
  1949. // In for-loops, prefer breaking at ',' and ';'.
  1950. if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
  1951. return 4;
  1952. // In Objective-C method expressions, prefer breaking before "param:" over
  1953. // breaking after it.
  1954. if (Right.is(TT_SelectorName))
  1955. return 0;
  1956. if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
  1957. return Line.MightBeFunctionDecl ? 50 : 500;
  1958. if (Left.is(tok::l_paren) && InFunctionDecl &&
  1959. Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
  1960. return 100;
  1961. if (Left.is(tok::l_paren) && Left.Previous &&
  1962. (Left.Previous->isOneOf(tok::kw_if, tok::kw_for)
  1963. || Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if)))
  1964. return 1000;
  1965. if (Left.is(tok::equal) && InFunctionDecl)
  1966. return 110;
  1967. if (Right.is(tok::r_brace))
  1968. return 1;
  1969. if (Left.is(TT_TemplateOpener))
  1970. return 100;
  1971. if (Left.opensScope()) {
  1972. if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign)
  1973. return 0;
  1974. return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
  1975. : 19;
  1976. }
  1977. if (Left.is(TT_JavaAnnotation))
  1978. return 50;
  1979. if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
  1980. Left.Previous->isLabelString() &&
  1981. (Left.NextOperator || Left.OperatorIndex != 0))
  1982. return 45;
  1983. if (Right.is(tok::plus) && Left.isLabelString() &&
  1984. (Right.NextOperator || Right.OperatorIndex != 0))
  1985. return 25;
  1986. if (Left.is(tok::comma))
  1987. return 1;
  1988. if (Right.is(tok::lessless) && Left.isLabelString() &&
  1989. (Right.NextOperator || Right.OperatorIndex != 1))
  1990. return 25;
  1991. if (Right.is(tok::lessless)) {
  1992. // Breaking at a << is really cheap.
  1993. if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0)
  1994. // Slightly prefer to break before the first one in log-like statements.
  1995. return 2;
  1996. return 1;
  1997. }
  1998. if (Left.is(TT_ConditionalExpr))
  1999. return prec::Conditional;
  2000. prec::Level Level = Left.getPrecedence();
  2001. if (Level == prec::Unknown)
  2002. Level = Right.getPrecedence();
  2003. if (Level == prec::Assignment)
  2004. return Style.PenaltyBreakAssignment;
  2005. if (Level != prec::Unknown)
  2006. return Level;
  2007. return 3;
  2008. }
  2009. bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
  2010. const FormatToken &Left,
  2011. const FormatToken &Right) {
  2012. if (Left.is(tok::kw_return) && Right.isNot(tok::semi))
  2013. return true;
  2014. if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty &&
  2015. Left.Tok.getObjCKeywordID() == tok::objc_property)
  2016. return true;
  2017. if (Right.is(tok::hashhash))
  2018. return Left.is(tok::hash);
  2019. if (Left.isOneOf(tok::hashhash, tok::hash))
  2020. return Right.is(tok::hash);
  2021. if (Left.is(tok::l_paren) && Right.is(tok::r_paren))
  2022. return Style.SpaceInEmptyParentheses;
  2023. if (Left.is(tok::l_paren) || Right.is(tok::r_paren))
  2024. return (Right.is(TT_CastRParen) ||
  2025. (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen)))
  2026. ? Style.SpacesInCStyleCastParentheses
  2027. : Style.SpacesInParentheses;
  2028. if (Right.isOneOf(tok::semi, tok::comma))
  2029. return false;
  2030. if (Right.is(tok::less) &&
  2031. Line.Type == LT_ObjCDecl && Style.ObjCSpaceBeforeProtocolList)
  2032. return true;
  2033. if (Right.is(tok::less) && Left.is(tok::kw_template))
  2034. return Style.SpaceAfterTemplateKeyword;
  2035. if (Left.isOneOf(tok::exclaim, tok::tilde))
  2036. return false;
  2037. if (Left.is(tok::at) &&
  2038. Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant,
  2039. tok::numeric_constant, tok::l_paren, tok::l_brace,
  2040. tok::kw_true, tok::kw_false))
  2041. return false;
  2042. if (Left.is(tok::colon))
  2043. return !Left.is(TT_ObjCMethodExpr);
  2044. if (Left.is(tok::coloncolon))
  2045. return false;
  2046. if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less))
  2047. return false;
  2048. if (Right.is(tok::ellipsis))
  2049. return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous &&
  2050. Left.Previous->is(tok::kw_case));
  2051. if (Left.is(tok::l_square) && Right.is(tok::amp))
  2052. return false;
  2053. if (Right.is(TT_PointerOrReference)) {
  2054. if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
  2055. if (!Left.MatchingParen)
  2056. return true;
  2057. FormatToken *TokenBeforeMatchingParen =
  2058. Left.MatchingParen->getPreviousNonComment();
  2059. if (!TokenBeforeMatchingParen ||
  2060. !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype))
  2061. return true;
  2062. }
  2063. return (Left.Tok.isLiteral() ||
  2064. (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
  2065. (Style.PointerAlignment != FormatStyle::PAS_Left ||
  2066. (Line.IsMultiVariableDeclStmt &&
  2067. (Left.NestingLevel == 0 ||
  2068. (Left.NestingLevel == 1 && Line.First->is(tok::kw_for)))))));
  2069. }
  2070. if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
  2071. (!Left.is(TT_PointerOrReference) ||
  2072. (Style.PointerAlignment != FormatStyle::PAS_Right &&
  2073. !Line.IsMultiVariableDeclStmt)))
  2074. return true;
  2075. if (Left.is(TT_PointerOrReference))
  2076. return Right.Tok.isLiteral() || Right.is(TT_BlockComment) ||
  2077. (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
  2078. !Right.is(TT_StartOfName)) ||
  2079. (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) ||
  2080. (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
  2081. tok::l_paren) &&
  2082. (Style.PointerAlignment != FormatStyle::PAS_Right &&
  2083. !Line.IsMultiVariableDeclStmt) &&
  2084. Left.Previous &&
  2085. !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon));
  2086. if (Right.is(tok::star) && Left.is(tok::l_paren))
  2087. return false;
  2088. if (Left.is(tok::l_square))
  2089. return (Left.is(TT_ArrayInitializerLSquare) &&
  2090. Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
  2091. (Left.isOneOf(TT_ArraySubscriptLSquare,
  2092. TT_StructuredBindingLSquare) &&
  2093. Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
  2094. if (Right.is(tok::r_square))
  2095. return Right.MatchingParen &&
  2096. ((Style.SpacesInContainerLiterals &&
  2097. Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
  2098. (Style.SpacesInSquareBrackets &&
  2099. Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
  2100. TT_StructuredBindingLSquare)));
  2101. if (Right.is(tok::l_square) &&
  2102. !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
  2103. TT_DesignatedInitializerLSquare,
  2104. TT_StructuredBindingLSquare) &&
  2105. !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
  2106. return false;
  2107. if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
  2108. return !Left.Children.empty(); // No spaces in "{}".
  2109. if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) ||
  2110. (Right.is(tok::r_brace) && Right.MatchingParen &&
  2111. Right.MatchingParen->BlockKind != BK_Block))
  2112. return !Style.Cpp11BracedListStyle;
  2113. if (Left.is(TT_BlockComment))
  2114. return !Left.TokenText.endswith("=*/");
  2115. if (Right.is(tok::l_paren)) {
  2116. if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen))
  2117. return true;
  2118. return Line.Type == LT_ObjCDecl || Left.is(tok::semi) ||
  2119. (Style.SpaceBeforeParens != FormatStyle::SBPO_Never &&
  2120. (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while,
  2121. tok::kw_switch, tok::kw_case, TT_ForEachMacro,
  2122. TT_ObjCForIn) ||
  2123. Left.endsSequence(tok::kw_constexpr, tok::kw_if) ||
  2124. (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch,
  2125. tok::kw_new, tok::kw_delete) &&
  2126. (!Left.Previous || Left.Previous->isNot(tok::period))))) ||
  2127. (Style.SpaceBeforeParens == FormatStyle::SBPO_Always &&
  2128. (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
  2129. Left.is(tok::r_paren)) &&
  2130. Line.Type != LT_PreprocessorDirective);
  2131. }
  2132. if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword)
  2133. return false;
  2134. if (Right.is(TT_UnaryOperator))
  2135. return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) &&
  2136. (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr));
  2137. if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square,
  2138. tok::r_paren) ||
  2139. Left.isSimpleTypeSpecifier()) &&
  2140. Right.is(tok::l_brace) && Right.getNextNonComment() &&
  2141. Right.BlockKind != BK_Block)
  2142. return false;
  2143. if (Left.is(tok::period) || Right.is(tok::period))
  2144. return false;
  2145. if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
  2146. return false;
  2147. if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
  2148. Left.MatchingParen->Previous &&
  2149. Left.MatchingParen->Previous->is(tok::period))
  2150. // A.<B>DoSomething();
  2151. return false;
  2152. if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
  2153. return false;
  2154. return true;
  2155. }
  2156. bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
  2157. const FormatToken &Right) {
  2158. const FormatToken &Left = *Right.Previous;
  2159. if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo())
  2160. return true; // Never ever merge two identifiers.
  2161. if (Style.isCpp()) {
  2162. if (Left.is(tok::kw_operator))
  2163. return Right.is(tok::coloncolon);
  2164. } else if (Style.Language == FormatStyle::LK_Proto ||
  2165. Style.Language == FormatStyle::LK_TextProto) {
  2166. if (Right.is(tok::period) &&
  2167. Left.isOneOf(Keywords.kw_optional, Keywords.kw_required,
  2168. Keywords.kw_repeated, Keywords.kw_extend))
  2169. return true;
  2170. if (Right.is(tok::l_paren) &&
  2171. Left.isOneOf(Keywords.kw_returns, Keywords.kw_option))
  2172. return true;
  2173. if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
  2174. return true;
  2175. } else if (Style.Language == FormatStyle::LK_JavaScript) {
  2176. if (Left.is(TT_JsFatArrow))
  2177. return true;
  2178. // for await ( ...
  2179. if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) &&
  2180. Left.Previous && Left.Previous->is(tok::kw_for))
  2181. return true;
  2182. if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) &&
  2183. Right.MatchingParen) {
  2184. const FormatToken *Next = Right.MatchingParen->getNextNonComment();
  2185. // An async arrow function, for example: `x = async () => foo();`,
  2186. // as opposed to calling a function called async: `x = async();`
  2187. if (Next && Next->is(TT_JsFatArrow))
  2188. return true;
  2189. }
  2190. if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
  2191. (Right.is(TT_TemplateString) && Right.TokenText.startswith("}")))
  2192. return false;
  2193. // In tagged template literals ("html`bar baz`"), there is no space between
  2194. // the tag identifier and the template string. getIdentifierInfo makes sure
  2195. // that the identifier is not a pseudo keyword like `yield`, either.
  2196. if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) &&
  2197. Right.is(TT_TemplateString))
  2198. return false;
  2199. if (Right.is(tok::star) &&
  2200. Left.isOneOf(Keywords.kw_function, Keywords.kw_yield))
  2201. return false;
  2202. if (Right.isOneOf(tok::l_brace, tok::l_square) &&
  2203. Left.isOneOf(Keywords.kw_function, Keywords.kw_yield,
  2204. Keywords.kw_extends, Keywords.kw_implements))
  2205. return true;
  2206. if (Right.is(tok::l_paren)) {
  2207. // JS methods can use some keywords as names (e.g. `delete()`).
  2208. if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
  2209. return false;
  2210. // Valid JS method names can include keywords, e.g. `foo.delete()` or
  2211. // `bar.instanceof()`. Recognize call positions by preceding period.
  2212. if (Left.Previous && Left.Previous->is(tok::period) &&
  2213. Left.Tok.getIdentifierInfo())
  2214. return false;
  2215. // Additional unary JavaScript operators that need a space after.
  2216. if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
  2217. tok::kw_void))
  2218. return true;
  2219. }
  2220. if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
  2221. tok::kw_const) ||
  2222. // "of" is only a keyword if it appears after another identifier
  2223. // (e.g. as "const x of y" in a for loop).
  2224. (Left.is(Keywords.kw_of) && Left.Previous &&
  2225. Left.Previous->Tok.getIdentifierInfo())) &&
  2226. (!Left.Previous || !Left.Previous->is(tok::period)))
  2227. return true;
  2228. if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
  2229. Left.Previous->is(tok::period) && Right.is(tok::l_paren))
  2230. return false;
  2231. if (Left.is(Keywords.kw_as) &&
  2232. Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren))
  2233. return true;
  2234. if (Left.is(tok::kw_default) && Left.Previous &&
  2235. Left.Previous->is(tok::kw_export))
  2236. return true;
  2237. if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace))
  2238. return true;
  2239. if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion))
  2240. return false;
  2241. if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator))
  2242. return false;
  2243. if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) &&
  2244. Line.First->isOneOf(Keywords.kw_import, tok::kw_export))
  2245. return false;
  2246. if (Left.is(tok::ellipsis))
  2247. return false;
  2248. if (Left.is(TT_TemplateCloser) &&
  2249. !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square,
  2250. Keywords.kw_implements, Keywords.kw_extends))
  2251. // Type assertions ('<type>expr') are not followed by whitespace. Other
  2252. // locations that should have whitespace following are identified by the
  2253. // above set of follower tokens.
  2254. return false;
  2255. if (Right.is(TT_JsNonNullAssertion))
  2256. return false;
  2257. if (Left.is(TT_JsNonNullAssertion) && Right.is(Keywords.kw_as))
  2258. return true; // "x! as string"
  2259. } else if (Style.Language == FormatStyle::LK_Java) {
  2260. if (Left.is(tok::r_square) && Right.is(tok::l_brace))
  2261. return true;
  2262. if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren))
  2263. return Style.SpaceBeforeParens != FormatStyle::SBPO_Never;
  2264. if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private,
  2265. tok::kw_protected) ||
  2266. Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract,
  2267. Keywords.kw_native)) &&
  2268. Right.is(TT_TemplateOpener))
  2269. return true;
  2270. }
  2271. if (Left.is(TT_ImplicitStringLiteral))
  2272. return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
  2273. if (Line.Type == LT_ObjCMethodDecl) {
  2274. if (Left.is(TT_ObjCMethodSpecifier))
  2275. return true;
  2276. if (Left.is(tok::r_paren) && Right.is(tok::identifier))
  2277. // Don't space between ')' and <id>
  2278. return false;
  2279. }
  2280. if (Line.Type == LT_ObjCProperty &&
  2281. (Right.is(tok::equal) || Left.is(tok::equal)))
  2282. return false;
  2283. if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) ||
  2284. Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow))
  2285. return true;
  2286. if (Right.is(TT_OverloadedOperatorLParen))
  2287. return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
  2288. if (Left.is(tok::comma))
  2289. return true;
  2290. if (Right.is(tok::comma))
  2291. return false;
  2292. if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen))
  2293. return true;
  2294. if (Right.is(tok::colon)) {
  2295. if (Line.First->isOneOf(tok::kw_case, tok::kw_default) ||
  2296. !Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
  2297. return false;
  2298. if (Right.is(TT_ObjCMethodExpr))
  2299. return false;
  2300. if (Left.is(tok::question))
  2301. return false;
  2302. if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
  2303. return false;
  2304. if (Right.is(TT_DictLiteral))
  2305. return Style.SpacesInContainerLiterals;
  2306. return true;
  2307. }
  2308. if (Left.is(TT_UnaryOperator))
  2309. return Right.is(TT_BinaryOperator);
  2310. // If the next token is a binary operator or a selector name, we have
  2311. // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly.
  2312. if (Left.is(TT_CastRParen))
  2313. return Style.SpaceAfterCStyleCast ||
  2314. Right.isOneOf(TT_BinaryOperator, TT_SelectorName);
  2315. if (Left.is(tok::greater) && Right.is(tok::greater))
  2316. return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) &&
  2317. (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles);
  2318. if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) ||
  2319. Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) ||
  2320. (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod)))
  2321. return false;
  2322. if (!Style.SpaceBeforeAssignmentOperators &&
  2323. Right.getPrecedence() == prec::Assignment)
  2324. return false;
  2325. if (Right.is(tok::coloncolon) && Left.is(tok::identifier))
  2326. // Generally don't remove existing spaces between an identifier and "::".
  2327. // The identifier might actually be a macro name such as ALWAYS_INLINE. If
  2328. // this turns out to be too lenient, add analysis of the identifier itself.
  2329. return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd();
  2330. if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment))
  2331. return (Left.is(TT_TemplateOpener) &&
  2332. Style.Standard == FormatStyle::LS_Cpp03) ||
  2333. !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
  2334. tok::kw___super, TT_TemplateCloser, TT_TemplateOpener));
  2335. if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser)))
  2336. return Style.SpacesInAngles;
  2337. if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) ||
  2338. (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) &&
  2339. !Right.is(tok::r_paren)))
  2340. return true;
  2341. if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) &&
  2342. Right.isNot(TT_FunctionTypeLParen))
  2343. return Style.SpaceBeforeParens == FormatStyle::SBPO_Always;
  2344. if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
  2345. Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen))
  2346. return false;
  2347. if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
  2348. Line.startsWith(tok::hash))
  2349. return true;
  2350. if (Right.is(TT_TrailingUnaryOperator))
  2351. return false;
  2352. if (Left.is(TT_RegexLiteral))
  2353. return false;
  2354. return spaceRequiredBetween(Line, Left, Right);
  2355. }
  2356. // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style.
  2357. static bool isAllmanBrace(const FormatToken &Tok) {
  2358. return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block &&
  2359. !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
  2360. }
  2361. bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
  2362. const FormatToken &Right) {
  2363. const FormatToken &Left = *Right.Previous;
  2364. if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
  2365. return true;
  2366. if (Style.Language == FormatStyle::LK_JavaScript) {
  2367. // FIXME: This might apply to other languages and token kinds.
  2368. if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
  2369. Left.Previous->is(tok::string_literal))
  2370. return true;
  2371. if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 &&
  2372. Left.Previous && Left.Previous->is(tok::equal) &&
  2373. Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export,
  2374. tok::kw_const) &&
  2375. // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match
  2376. // above.
  2377. !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let))
  2378. // Object literals on the top level of a file are treated as "enum-style".
  2379. // Each key/value pair is put on a separate line, instead of bin-packing.
  2380. return true;
  2381. if (Left.is(tok::l_brace) && Line.Level == 0 &&
  2382. (Line.startsWith(tok::kw_enum) ||
  2383. Line.startsWith(tok::kw_const, tok::kw_enum) ||
  2384. Line.startsWith(tok::kw_export, tok::kw_enum) ||
  2385. Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum)))
  2386. // JavaScript top-level enum key/value pairs are put on separate lines
  2387. // instead of bin-packing.
  2388. return true;
  2389. if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
  2390. !Left.Children.empty())
  2391. // Support AllowShortFunctionsOnASingleLine for JavaScript.
  2392. return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None ||
  2393. Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty ||
  2394. (Left.NestingLevel == 0 && Line.Level == 0 &&
  2395. Style.AllowShortFunctionsOnASingleLine &
  2396. FormatStyle::SFS_InlineOnly);
  2397. } else if (Style.Language == FormatStyle::LK_Java) {
  2398. if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
  2399. Right.Next->is(tok::string_literal))
  2400. return true;
  2401. } else if (Style.Language == FormatStyle::LK_Cpp ||
  2402. Style.Language == FormatStyle::LK_ObjC ||
  2403. Style.Language == FormatStyle::LK_Proto) {
  2404. if (Left.isStringLiteral() && Right.isStringLiteral())
  2405. return true;
  2406. }
  2407. // If the last token before a '}', ']', or ')' is a comma or a trailing
  2408. // comment, the intention is to insert a line break after it in order to make
  2409. // shuffling around entries easier. Import statements, especially in
  2410. // JavaScript, can be an exception to this rule.
  2411. if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
  2412. const FormatToken *BeforeClosingBrace = nullptr;
  2413. if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) ||
  2414. (Style.Language == FormatStyle::LK_JavaScript &&
  2415. Left.is(tok::l_paren))) &&
  2416. Left.BlockKind != BK_Block && Left.MatchingParen)
  2417. BeforeClosingBrace = Left.MatchingParen->Previous;
  2418. else if (Right.MatchingParen &&
  2419. (Right.MatchingParen->isOneOf(tok::l_brace,
  2420. TT_ArrayInitializerLSquare) ||
  2421. (Style.Language == FormatStyle::LK_JavaScript &&
  2422. Right.MatchingParen->is(tok::l_paren))))
  2423. BeforeClosingBrace = &Left;
  2424. if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) ||
  2425. BeforeClosingBrace->isTrailingComment()))
  2426. return true;
  2427. }
  2428. if (Right.is(tok::comment))
  2429. return Left.BlockKind != BK_BracedInit &&
  2430. Left.isNot(TT_CtorInitializerColon) &&
  2431. (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline);
  2432. if (Left.isTrailingComment())
  2433. return true;
  2434. if (Right.Previous->IsUnterminatedLiteral)
  2435. return true;
  2436. if (Right.is(tok::lessless) && Right.Next &&
  2437. Right.Previous->is(tok::string_literal) &&
  2438. Right.Next->is(tok::string_literal))
  2439. return true;
  2440. if (Right.Previous->ClosesTemplateDeclaration &&
  2441. Right.Previous->MatchingParen &&
  2442. Right.Previous->MatchingParen->NestingLevel == 0 &&
  2443. Style.AlwaysBreakTemplateDeclarations)
  2444. return true;
  2445. if (Right.is(TT_CtorInitializerComma) &&
  2446. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
  2447. !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
  2448. return true;
  2449. if (Right.is(TT_CtorInitializerColon) &&
  2450. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma &&
  2451. !Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
  2452. return true;
  2453. // Break only if we have multiple inheritance.
  2454. if (Style.BreakBeforeInheritanceComma &&
  2455. Right.is(TT_InheritanceComma))
  2456. return true;
  2457. if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\""))
  2458. // Raw string literals are special wrt. line breaks. The author has made a
  2459. // deliberate choice and might have aligned the contents of the string
  2460. // literal accordingly. Thus, we try keep existing line breaks.
  2461. return Right.NewlinesBefore > 0;
  2462. if ((Right.Previous->is(tok::l_brace) ||
  2463. (Right.Previous->is(tok::less) &&
  2464. Right.Previous->Previous &&
  2465. Right.Previous->Previous->is(tok::equal))
  2466. ) &&
  2467. Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) {
  2468. // Don't put enums or option definitions onto single lines in protocol
  2469. // buffers.
  2470. return true;
  2471. }
  2472. if (Right.is(TT_InlineASMBrace))
  2473. return Right.HasUnescapedNewline;
  2474. if (isAllmanBrace(Left) || isAllmanBrace(Right))
  2475. return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
  2476. (Line.startsWith(tok::kw_typedef, tok::kw_enum) && Style.BraceWrapping.AfterEnum) ||
  2477. (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) ||
  2478. (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct);
  2479. if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine)
  2480. return true;
  2481. if ((Style.Language == FormatStyle::LK_Java ||
  2482. Style.Language == FormatStyle::LK_JavaScript) &&
  2483. Left.is(TT_LeadingJavaAnnotation) &&
  2484. Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) &&
  2485. (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations))
  2486. return true;
  2487. return false;
  2488. }
  2489. bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
  2490. const FormatToken &Right) {
  2491. const FormatToken &Left = *Right.Previous;
  2492. // Language-specific stuff.
  2493. if (Style.Language == FormatStyle::LK_Java) {
  2494. if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
  2495. Keywords.kw_implements))
  2496. return false;
  2497. if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
  2498. Keywords.kw_implements))
  2499. return true;
  2500. } else if (Style.Language == FormatStyle::LK_JavaScript) {
  2501. const FormatToken *NonComment = Right.getPreviousNonComment();
  2502. if (NonComment &&
  2503. NonComment->isOneOf(tok::kw_return, tok::kw_continue, tok::kw_break,
  2504. tok::kw_throw, Keywords.kw_interface,
  2505. Keywords.kw_type, tok::kw_static, tok::kw_public,
  2506. tok::kw_private, tok::kw_protected,
  2507. Keywords.kw_readonly, Keywords.kw_abstract,
  2508. Keywords.kw_get, Keywords.kw_set))
  2509. return false; // Otherwise automatic semicolon insertion would trigger.
  2510. if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace))
  2511. return false;
  2512. if (Left.is(TT_JsTypeColon))
  2513. return true;
  2514. if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is))
  2515. return false;
  2516. if (Left.is(Keywords.kw_in))
  2517. return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
  2518. if (Right.is(Keywords.kw_in))
  2519. return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
  2520. if (Right.is(Keywords.kw_as))
  2521. return false; // must not break before as in 'x as type' casts
  2522. if (Left.is(Keywords.kw_as))
  2523. return true;
  2524. if (Left.is(TT_JsNonNullAssertion))
  2525. return true;
  2526. if (Left.is(Keywords.kw_declare) &&
  2527. Right.isOneOf(Keywords.kw_module, tok::kw_namespace,
  2528. Keywords.kw_function, tok::kw_class, tok::kw_enum,
  2529. Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var,
  2530. Keywords.kw_let, tok::kw_const))
  2531. // See grammar for 'declare' statements at:
  2532. // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10
  2533. return false;
  2534. if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
  2535. Right.isOneOf(tok::identifier, tok::string_literal))
  2536. return false; // must not break in "module foo { ...}"
  2537. if (Right.is(TT_TemplateString) && Right.closesScope())
  2538. return false;
  2539. if (Left.is(TT_TemplateString) && Left.opensScope())
  2540. return true;
  2541. }
  2542. if (Left.is(tok::at))
  2543. return false;
  2544. if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
  2545. return false;
  2546. if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
  2547. return !Right.is(tok::l_paren);
  2548. if (Right.is(TT_PointerOrReference))
  2549. return Line.IsMultiVariableDeclStmt ||
  2550. (Style.PointerAlignment == FormatStyle::PAS_Right &&
  2551. (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName)));
  2552. if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
  2553. Right.is(tok::kw_operator))
  2554. return true;
  2555. if (Left.is(TT_PointerOrReference))
  2556. return false;
  2557. if (Right.isTrailingComment())
  2558. // We rely on MustBreakBefore being set correctly here as we should not
  2559. // change the "binding" behavior of a comment.
  2560. // The first comment in a braced lists is always interpreted as belonging to
  2561. // the first list element. Otherwise, it should be placed outside of the
  2562. // list.
  2563. return Left.BlockKind == BK_BracedInit ||
  2564. (Left.is(TT_CtorInitializerColon) &&
  2565. Style.BreakConstructorInitializers ==
  2566. FormatStyle::BCIS_AfterColon);
  2567. if (Left.is(tok::question) && Right.is(tok::colon))
  2568. return false;
  2569. if (Right.is(TT_ConditionalExpr) || Right.is(tok::question))
  2570. return Style.BreakBeforeTernaryOperators;
  2571. if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
  2572. return !Style.BreakBeforeTernaryOperators;
  2573. if (Right.is(TT_InheritanceColon))
  2574. return true;
  2575. if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) &&
  2576. Left.isNot(TT_SelectorName))
  2577. return true;
  2578. if (Right.is(tok::colon) &&
  2579. !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
  2580. return false;
  2581. if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr))
  2582. return true;
  2583. if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
  2584. Right.Next->is(TT_ObjCMethodExpr)))
  2585. return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls.
  2586. if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
  2587. return true;
  2588. if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
  2589. return true;
  2590. if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
  2591. TT_OverloadedOperator))
  2592. return false;
  2593. if (Left.is(TT_RangeBasedForLoopColon))
  2594. return true;
  2595. if (Right.is(TT_RangeBasedForLoopColon))
  2596. return false;
  2597. if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener))
  2598. return true;
  2599. if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
  2600. Left.is(tok::kw_operator))
  2601. return false;
  2602. if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) &&
  2603. Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0)
  2604. return false;
  2605. if (Left.is(tok::l_paren) && Left.is(TT_AttributeParen))
  2606. return false;
  2607. if (Left.is(tok::l_paren) && Left.Previous &&
  2608. (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen)))
  2609. return false;
  2610. if (Right.is(TT_ImplicitStringLiteral))
  2611. return false;
  2612. if (Right.is(tok::r_paren) || Right.is(TT_TemplateCloser))
  2613. return false;
  2614. if (Right.is(tok::r_square) && Right.MatchingParen &&
  2615. Right.MatchingParen->is(TT_LambdaLSquare))
  2616. return false;
  2617. // We only break before r_brace if there was a corresponding break before
  2618. // the l_brace, which is tracked by BreakBeforeClosingBrace.
  2619. if (Right.is(tok::r_brace))
  2620. return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block;
  2621. // Allow breaking after a trailing annotation, e.g. after a method
  2622. // declaration.
  2623. if (Left.is(TT_TrailingAnnotation))
  2624. return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren,
  2625. tok::less, tok::coloncolon);
  2626. if (Right.is(tok::kw___attribute))
  2627. return true;
  2628. if (Left.is(tok::identifier) && Right.is(tok::string_literal))
  2629. return true;
  2630. if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
  2631. return true;
  2632. if (Left.is(TT_CtorInitializerColon))
  2633. return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon;
  2634. if (Right.is(TT_CtorInitializerColon))
  2635. return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
  2636. if (Left.is(TT_CtorInitializerComma) &&
  2637. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
  2638. return false;
  2639. if (Right.is(TT_CtorInitializerComma) &&
  2640. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma)
  2641. return true;
  2642. if (Left.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
  2643. return false;
  2644. if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma)
  2645. return true;
  2646. if ((Left.is(tok::greater) && Right.is(tok::greater)) ||
  2647. (Left.is(tok::less) && Right.is(tok::less)))
  2648. return false;
  2649. if (Right.is(TT_BinaryOperator) &&
  2650. Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
  2651. (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
  2652. Right.getPrecedence() != prec::Assignment))
  2653. return true;
  2654. if (Left.is(TT_ArrayInitializerLSquare))
  2655. return true;
  2656. if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const))
  2657. return true;
  2658. if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
  2659. !Left.isOneOf(tok::arrowstar, tok::lessless) &&
  2660. Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
  2661. (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
  2662. Left.getPrecedence() == prec::Assignment))
  2663. return true;
  2664. return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
  2665. tok::kw_class, tok::kw_struct, tok::comment) ||
  2666. Right.isMemberAccess() ||
  2667. Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
  2668. tok::colon, tok::l_square, tok::at) ||
  2669. (Left.is(tok::r_paren) &&
  2670. Right.isOneOf(tok::identifier, tok::kw_const)) ||
  2671. (Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
  2672. (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
  2673. }
  2674. void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
  2675. llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
  2676. const FormatToken *Tok = Line.First;
  2677. while (Tok) {
  2678. llvm::errs() << " M=" << Tok->MustBreakBefore
  2679. << " C=" << Tok->CanBreakBefore
  2680. << " T=" << getTokenTypeName(Tok->Type)
  2681. << " S=" << Tok->SpacesRequiredBefore
  2682. << " B=" << Tok->BlockParameterCount
  2683. << " BK=" << Tok->BlockKind
  2684. << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName()
  2685. << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind
  2686. << " FakeLParens=";
  2687. for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
  2688. llvm::errs() << Tok->FakeLParens[i] << "/";
  2689. llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
  2690. llvm::errs() << " Text='" << Tok->TokenText << "'\n";
  2691. if (!Tok->Next)
  2692. assert(Tok == Line.Last);
  2693. Tok = Tok->Next;
  2694. }
  2695. llvm::errs() << "----\n";
  2696. }
  2697. } // namespace format
  2698. } // namespace clang