TokenAnnotator.cpp 143 KB

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