TokenAnnotator.cpp 116 KB

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