TokenAnnotator.cpp 106 KB

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