Format.cpp 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  1. //===--- Format.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 functions declared in Format.h. This will be
  12. /// split into separate files as we go.
  13. ///
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/Format/Format.h"
  16. #include "AffectedRangeManager.h"
  17. #include "ContinuationIndenter.h"
  18. #include "FormatInternal.h"
  19. #include "FormatTokenLexer.h"
  20. #include "NamespaceEndCommentsFixer.h"
  21. #include "SortJavaScriptImports.h"
  22. #include "TokenAnalyzer.h"
  23. #include "TokenAnnotator.h"
  24. #include "UnwrappedLineFormatter.h"
  25. #include "UnwrappedLineParser.h"
  26. #include "UsingDeclarationsSorter.h"
  27. #include "WhitespaceManager.h"
  28. #include "clang/Basic/Diagnostic.h"
  29. #include "clang/Basic/DiagnosticOptions.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "clang/Basic/VirtualFileSystem.h"
  32. #include "clang/Lex/Lexer.h"
  33. #include "llvm/ADT/STLExtras.h"
  34. #include "llvm/ADT/StringRef.h"
  35. #include "llvm/Support/Allocator.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/Path.h"
  38. #include "llvm/Support/Regex.h"
  39. #include "llvm/Support/YAMLTraits.h"
  40. #include <algorithm>
  41. #include <memory>
  42. #include <string>
  43. #define DEBUG_TYPE "format-formatter"
  44. using clang::format::FormatStyle;
  45. LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
  46. LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
  47. namespace llvm {
  48. namespace yaml {
  49. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
  50. static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
  51. IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
  52. IO.enumCase(Value, "Java", FormatStyle::LK_Java);
  53. IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
  54. IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
  55. IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
  56. IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
  57. IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
  58. }
  59. };
  60. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
  61. static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
  62. IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
  63. IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
  64. IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
  65. IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
  66. IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
  67. }
  68. };
  69. template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
  70. static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
  71. IO.enumCase(Value, "Never", FormatStyle::UT_Never);
  72. IO.enumCase(Value, "false", FormatStyle::UT_Never);
  73. IO.enumCase(Value, "Always", FormatStyle::UT_Always);
  74. IO.enumCase(Value, "true", FormatStyle::UT_Always);
  75. IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
  76. IO.enumCase(Value, "ForContinuationAndIndentation",
  77. FormatStyle::UT_ForContinuationAndIndentation);
  78. }
  79. };
  80. template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
  81. static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
  82. IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
  83. IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
  84. IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
  85. }
  86. };
  87. template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
  88. static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
  89. IO.enumCase(Value, "None", FormatStyle::SFS_None);
  90. IO.enumCase(Value, "false", FormatStyle::SFS_None);
  91. IO.enumCase(Value, "All", FormatStyle::SFS_All);
  92. IO.enumCase(Value, "true", FormatStyle::SFS_All);
  93. IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
  94. IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
  95. IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
  96. }
  97. };
  98. template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
  99. static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
  100. IO.enumCase(Value, "All", FormatStyle::BOS_All);
  101. IO.enumCase(Value, "true", FormatStyle::BOS_All);
  102. IO.enumCase(Value, "None", FormatStyle::BOS_None);
  103. IO.enumCase(Value, "false", FormatStyle::BOS_None);
  104. IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
  105. }
  106. };
  107. template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
  108. static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
  109. IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
  110. IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
  111. IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
  112. IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
  113. IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
  114. IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
  115. IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
  116. IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
  117. }
  118. };
  119. template <>
  120. struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
  121. static void
  122. enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
  123. IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
  124. IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
  125. IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
  126. }
  127. };
  128. template <>
  129. struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
  130. static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
  131. IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
  132. IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
  133. }
  134. };
  135. template <>
  136. struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
  137. static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
  138. IO.enumCase(Value, "None", FormatStyle::RTBS_None);
  139. IO.enumCase(Value, "All", FormatStyle::RTBS_All);
  140. IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
  141. IO.enumCase(Value, "TopLevelDefinitions",
  142. FormatStyle::RTBS_TopLevelDefinitions);
  143. IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
  144. }
  145. };
  146. template <>
  147. struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
  148. static void
  149. enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
  150. IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
  151. IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
  152. IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
  153. // For backward compatibility.
  154. IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
  155. IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
  156. }
  157. };
  158. template <>
  159. struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
  160. static void enumeration(IO &IO,
  161. FormatStyle::NamespaceIndentationKind &Value) {
  162. IO.enumCase(Value, "None", FormatStyle::NI_None);
  163. IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
  164. IO.enumCase(Value, "All", FormatStyle::NI_All);
  165. }
  166. };
  167. template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
  168. static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
  169. IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
  170. IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
  171. IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
  172. // For backward compatibility.
  173. IO.enumCase(Value, "true", FormatStyle::BAS_Align);
  174. IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
  175. }
  176. };
  177. template <>
  178. struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
  179. static void enumeration(IO &IO,
  180. FormatStyle::EscapedNewlineAlignmentStyle &Value) {
  181. IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
  182. IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
  183. IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
  184. // For backward compatibility.
  185. IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
  186. IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
  187. }
  188. };
  189. template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
  190. static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
  191. IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
  192. IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
  193. IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
  194. // For backward compatibility.
  195. IO.enumCase(Value, "true", FormatStyle::PAS_Left);
  196. IO.enumCase(Value, "false", FormatStyle::PAS_Right);
  197. }
  198. };
  199. template <>
  200. struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
  201. static void enumeration(IO &IO,
  202. FormatStyle::SpaceBeforeParensOptions &Value) {
  203. IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
  204. IO.enumCase(Value, "ControlStatements",
  205. FormatStyle::SBPO_ControlStatements);
  206. IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
  207. // For backward compatibility.
  208. IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
  209. IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
  210. }
  211. };
  212. template <> struct MappingTraits<FormatStyle> {
  213. static void mapping(IO &IO, FormatStyle &Style) {
  214. // When reading, read the language first, we need it for getPredefinedStyle.
  215. IO.mapOptional("Language", Style.Language);
  216. if (IO.outputting()) {
  217. StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
  218. "Mozilla", "WebKit", "GNU"};
  219. ArrayRef<StringRef> Styles(StylesArray);
  220. for (size_t i = 0, e = Styles.size(); i < e; ++i) {
  221. StringRef StyleName(Styles[i]);
  222. FormatStyle PredefinedStyle;
  223. if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
  224. Style == PredefinedStyle) {
  225. IO.mapOptional("# BasedOnStyle", StyleName);
  226. break;
  227. }
  228. }
  229. } else {
  230. StringRef BasedOnStyle;
  231. IO.mapOptional("BasedOnStyle", BasedOnStyle);
  232. if (!BasedOnStyle.empty()) {
  233. FormatStyle::LanguageKind OldLanguage = Style.Language;
  234. FormatStyle::LanguageKind Language =
  235. ((FormatStyle *)IO.getContext())->Language;
  236. if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
  237. IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
  238. return;
  239. }
  240. Style.Language = OldLanguage;
  241. }
  242. }
  243. // For backward compatibility.
  244. if (!IO.outputting()) {
  245. IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
  246. IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
  247. IO.mapOptional("IndentFunctionDeclarationAfterType",
  248. Style.IndentWrappedFunctionNames);
  249. IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
  250. IO.mapOptional("SpaceAfterControlStatementKeyword",
  251. Style.SpaceBeforeParens);
  252. }
  253. IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
  254. IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
  255. IO.mapOptional("AlignConsecutiveAssignments",
  256. Style.AlignConsecutiveAssignments);
  257. IO.mapOptional("AlignConsecutiveDeclarations",
  258. Style.AlignConsecutiveDeclarations);
  259. IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
  260. IO.mapOptional("AlignOperands", Style.AlignOperands);
  261. IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
  262. IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
  263. Style.AllowAllParametersOfDeclarationOnNextLine);
  264. IO.mapOptional("AllowShortBlocksOnASingleLine",
  265. Style.AllowShortBlocksOnASingleLine);
  266. IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
  267. Style.AllowShortCaseLabelsOnASingleLine);
  268. IO.mapOptional("AllowShortFunctionsOnASingleLine",
  269. Style.AllowShortFunctionsOnASingleLine);
  270. IO.mapOptional("AllowShortIfStatementsOnASingleLine",
  271. Style.AllowShortIfStatementsOnASingleLine);
  272. IO.mapOptional("AllowShortLoopsOnASingleLine",
  273. Style.AllowShortLoopsOnASingleLine);
  274. IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
  275. Style.AlwaysBreakAfterDefinitionReturnType);
  276. IO.mapOptional("AlwaysBreakAfterReturnType",
  277. Style.AlwaysBreakAfterReturnType);
  278. // If AlwaysBreakAfterDefinitionReturnType was specified but
  279. // AlwaysBreakAfterReturnType was not, initialize the latter from the
  280. // former for backwards compatibility.
  281. if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
  282. Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
  283. if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
  284. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  285. else if (Style.AlwaysBreakAfterDefinitionReturnType ==
  286. FormatStyle::DRTBS_TopLevel)
  287. Style.AlwaysBreakAfterReturnType =
  288. FormatStyle::RTBS_TopLevelDefinitions;
  289. }
  290. IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
  291. Style.AlwaysBreakBeforeMultilineStrings);
  292. IO.mapOptional("AlwaysBreakTemplateDeclarations",
  293. Style.AlwaysBreakTemplateDeclarations);
  294. IO.mapOptional("BinPackArguments", Style.BinPackArguments);
  295. IO.mapOptional("BinPackParameters", Style.BinPackParameters);
  296. IO.mapOptional("BraceWrapping", Style.BraceWrapping);
  297. IO.mapOptional("BreakBeforeBinaryOperators",
  298. Style.BreakBeforeBinaryOperators);
  299. IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
  300. IO.mapOptional("BreakBeforeInheritanceComma",
  301. Style.BreakBeforeInheritanceComma);
  302. IO.mapOptional("BreakBeforeTernaryOperators",
  303. Style.BreakBeforeTernaryOperators);
  304. bool BreakConstructorInitializersBeforeComma = false;
  305. IO.mapOptional("BreakConstructorInitializersBeforeComma",
  306. BreakConstructorInitializersBeforeComma);
  307. IO.mapOptional("BreakConstructorInitializers",
  308. Style.BreakConstructorInitializers);
  309. // If BreakConstructorInitializersBeforeComma was specified but
  310. // BreakConstructorInitializers was not, initialize the latter from the
  311. // former for backwards compatibility.
  312. if (BreakConstructorInitializersBeforeComma &&
  313. Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
  314. Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  315. IO.mapOptional("BreakAfterJavaFieldAnnotations",
  316. Style.BreakAfterJavaFieldAnnotations);
  317. IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
  318. IO.mapOptional("ColumnLimit", Style.ColumnLimit);
  319. IO.mapOptional("CommentPragmas", Style.CommentPragmas);
  320. IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
  321. IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
  322. Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
  323. IO.mapOptional("ConstructorInitializerIndentWidth",
  324. Style.ConstructorInitializerIndentWidth);
  325. IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
  326. IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
  327. IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
  328. IO.mapOptional("DisableFormat", Style.DisableFormat);
  329. IO.mapOptional("ExperimentalAutoDetectBinPacking",
  330. Style.ExperimentalAutoDetectBinPacking);
  331. IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
  332. IO.mapOptional("ForEachMacros", Style.ForEachMacros);
  333. IO.mapOptional("IncludeBlocks", Style.IncludeBlocks);
  334. IO.mapOptional("IncludeCategories", Style.IncludeCategories);
  335. IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex);
  336. IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
  337. IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
  338. IO.mapOptional("IndentWidth", Style.IndentWidth);
  339. IO.mapOptional("IndentWrappedFunctionNames",
  340. Style.IndentWrappedFunctionNames);
  341. IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
  342. IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
  343. IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
  344. Style.KeepEmptyLinesAtTheStartOfBlocks);
  345. IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
  346. IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
  347. IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
  348. IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
  349. IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
  350. IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
  351. IO.mapOptional("ObjCSpaceBeforeProtocolList",
  352. Style.ObjCSpaceBeforeProtocolList);
  353. IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
  354. IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
  355. Style.PenaltyBreakBeforeFirstCallParameter);
  356. IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
  357. IO.mapOptional("PenaltyBreakFirstLessLess",
  358. Style.PenaltyBreakFirstLessLess);
  359. IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
  360. IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
  361. IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
  362. Style.PenaltyReturnTypeOnItsOwnLine);
  363. IO.mapOptional("PointerAlignment", Style.PointerAlignment);
  364. IO.mapOptional("RawStringFormats", Style.RawStringFormats);
  365. IO.mapOptional("ReflowComments", Style.ReflowComments);
  366. IO.mapOptional("SortIncludes", Style.SortIncludes);
  367. IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
  368. IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
  369. IO.mapOptional("SpaceAfterTemplateKeyword",
  370. Style.SpaceAfterTemplateKeyword);
  371. IO.mapOptional("SpaceBeforeAssignmentOperators",
  372. Style.SpaceBeforeAssignmentOperators);
  373. IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
  374. IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
  375. IO.mapOptional("SpacesBeforeTrailingComments",
  376. Style.SpacesBeforeTrailingComments);
  377. IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
  378. IO.mapOptional("SpacesInContainerLiterals",
  379. Style.SpacesInContainerLiterals);
  380. IO.mapOptional("SpacesInCStyleCastParentheses",
  381. Style.SpacesInCStyleCastParentheses);
  382. IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
  383. IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
  384. IO.mapOptional("Standard", Style.Standard);
  385. IO.mapOptional("TabWidth", Style.TabWidth);
  386. IO.mapOptional("UseTab", Style.UseTab);
  387. }
  388. };
  389. template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
  390. static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
  391. IO.mapOptional("AfterClass", Wrapping.AfterClass);
  392. IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
  393. IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
  394. IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
  395. IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
  396. IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
  397. IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
  398. IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
  399. IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
  400. IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
  401. IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
  402. IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
  403. IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
  404. IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
  405. IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
  406. }
  407. };
  408. template <> struct MappingTraits<FormatStyle::IncludeCategory> {
  409. static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
  410. IO.mapOptional("Regex", Category.Regex);
  411. IO.mapOptional("Priority", Category.Priority);
  412. }
  413. };
  414. template <> struct ScalarEnumerationTraits<FormatStyle::IncludeBlocksStyle> {
  415. static void enumeration(IO &IO, FormatStyle::IncludeBlocksStyle &Value) {
  416. IO.enumCase(Value, "Preserve", FormatStyle::IBS_Preserve);
  417. IO.enumCase(Value, "Merge", FormatStyle::IBS_Merge);
  418. IO.enumCase(Value, "Regroup", FormatStyle::IBS_Regroup);
  419. }
  420. };
  421. template <> struct MappingTraits<FormatStyle::RawStringFormat> {
  422. static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
  423. IO.mapOptional("Language", Format.Language);
  424. IO.mapOptional("Delimiters", Format.Delimiters);
  425. IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
  426. IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
  427. IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
  428. }
  429. };
  430. // Allows to read vector<FormatStyle> while keeping default values.
  431. // IO.getContext() should contain a pointer to the FormatStyle structure, that
  432. // will be used to get default values for missing keys.
  433. // If the first element has no Language specified, it will be treated as the
  434. // default one for the following elements.
  435. template <> struct DocumentListTraits<std::vector<FormatStyle>> {
  436. static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
  437. return Seq.size();
  438. }
  439. static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
  440. size_t Index) {
  441. if (Index >= Seq.size()) {
  442. assert(Index == Seq.size());
  443. FormatStyle Template;
  444. if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
  445. Template = Seq[0];
  446. } else {
  447. Template = *((const FormatStyle *)IO.getContext());
  448. Template.Language = FormatStyle::LK_None;
  449. }
  450. Seq.resize(Index + 1, Template);
  451. }
  452. return Seq[Index];
  453. }
  454. };
  455. } // namespace yaml
  456. } // namespace llvm
  457. namespace clang {
  458. namespace format {
  459. const std::error_category &getParseCategory() {
  460. static ParseErrorCategory C;
  461. return C;
  462. }
  463. std::error_code make_error_code(ParseError e) {
  464. return std::error_code(static_cast<int>(e), getParseCategory());
  465. }
  466. inline llvm::Error make_string_error(const llvm::Twine &Message) {
  467. return llvm::make_error<llvm::StringError>(Message,
  468. llvm::inconvertibleErrorCode());
  469. }
  470. const char *ParseErrorCategory::name() const noexcept {
  471. return "clang-format.parse_error";
  472. }
  473. std::string ParseErrorCategory::message(int EV) const {
  474. switch (static_cast<ParseError>(EV)) {
  475. case ParseError::Success:
  476. return "Success";
  477. case ParseError::Error:
  478. return "Invalid argument";
  479. case ParseError::Unsuitable:
  480. return "Unsuitable";
  481. }
  482. llvm_unreachable("unexpected parse error");
  483. }
  484. static FormatStyle expandPresets(const FormatStyle &Style) {
  485. if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
  486. return Style;
  487. FormatStyle Expanded = Style;
  488. Expanded.BraceWrapping = {false, false, false, false, false,
  489. false, false, false, false, false,
  490. false, false, true, true, true};
  491. switch (Style.BreakBeforeBraces) {
  492. case FormatStyle::BS_Linux:
  493. Expanded.BraceWrapping.AfterClass = true;
  494. Expanded.BraceWrapping.AfterFunction = true;
  495. Expanded.BraceWrapping.AfterNamespace = true;
  496. break;
  497. case FormatStyle::BS_Mozilla:
  498. Expanded.BraceWrapping.AfterClass = true;
  499. Expanded.BraceWrapping.AfterEnum = true;
  500. Expanded.BraceWrapping.AfterFunction = true;
  501. Expanded.BraceWrapping.AfterStruct = true;
  502. Expanded.BraceWrapping.AfterUnion = true;
  503. Expanded.BraceWrapping.AfterExternBlock = true;
  504. Expanded.BraceWrapping.SplitEmptyFunction = true;
  505. Expanded.BraceWrapping.SplitEmptyRecord = false;
  506. break;
  507. case FormatStyle::BS_Stroustrup:
  508. Expanded.BraceWrapping.AfterFunction = true;
  509. Expanded.BraceWrapping.BeforeCatch = true;
  510. Expanded.BraceWrapping.BeforeElse = true;
  511. break;
  512. case FormatStyle::BS_Allman:
  513. Expanded.BraceWrapping.AfterClass = true;
  514. Expanded.BraceWrapping.AfterControlStatement = true;
  515. Expanded.BraceWrapping.AfterEnum = true;
  516. Expanded.BraceWrapping.AfterFunction = true;
  517. Expanded.BraceWrapping.AfterNamespace = true;
  518. Expanded.BraceWrapping.AfterObjCDeclaration = true;
  519. Expanded.BraceWrapping.AfterStruct = true;
  520. Expanded.BraceWrapping.AfterExternBlock = true;
  521. Expanded.BraceWrapping.BeforeCatch = true;
  522. Expanded.BraceWrapping.BeforeElse = true;
  523. break;
  524. case FormatStyle::BS_GNU:
  525. Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
  526. true, true, true, true, true, true, true};
  527. break;
  528. case FormatStyle::BS_WebKit:
  529. Expanded.BraceWrapping.AfterFunction = true;
  530. break;
  531. default:
  532. break;
  533. }
  534. return Expanded;
  535. }
  536. FormatStyle getLLVMStyle() {
  537. FormatStyle LLVMStyle;
  538. LLVMStyle.Language = FormatStyle::LK_Cpp;
  539. LLVMStyle.AccessModifierOffset = -2;
  540. LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
  541. LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
  542. LLVMStyle.AlignOperands = true;
  543. LLVMStyle.AlignTrailingComments = true;
  544. LLVMStyle.AlignConsecutiveAssignments = false;
  545. LLVMStyle.AlignConsecutiveDeclarations = false;
  546. LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
  547. LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
  548. LLVMStyle.AllowShortBlocksOnASingleLine = false;
  549. LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
  550. LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
  551. LLVMStyle.AllowShortLoopsOnASingleLine = false;
  552. LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
  553. LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
  554. LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
  555. LLVMStyle.AlwaysBreakTemplateDeclarations = false;
  556. LLVMStyle.BinPackArguments = true;
  557. LLVMStyle.BinPackParameters = true;
  558. LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
  559. LLVMStyle.BreakBeforeTernaryOperators = true;
  560. LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
  561. LLVMStyle.BraceWrapping = {false, false, false, false, false,
  562. false, false, false, false, false,
  563. false, false, true, true, true};
  564. LLVMStyle.BreakAfterJavaFieldAnnotations = false;
  565. LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
  566. LLVMStyle.BreakBeforeInheritanceComma = false;
  567. LLVMStyle.BreakStringLiterals = true;
  568. LLVMStyle.ColumnLimit = 80;
  569. LLVMStyle.CommentPragmas = "^ IWYU pragma:";
  570. LLVMStyle.CompactNamespaces = false;
  571. LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
  572. LLVMStyle.ConstructorInitializerIndentWidth = 4;
  573. LLVMStyle.ContinuationIndentWidth = 4;
  574. LLVMStyle.Cpp11BracedListStyle = true;
  575. LLVMStyle.DerivePointerAlignment = false;
  576. LLVMStyle.ExperimentalAutoDetectBinPacking = false;
  577. LLVMStyle.FixNamespaceComments = true;
  578. LLVMStyle.ForEachMacros.push_back("foreach");
  579. LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
  580. LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
  581. LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
  582. {"^(<|\"(gtest|gmock|isl|json)/)", 3},
  583. {".*", 1}};
  584. LLVMStyle.IncludeIsMainRegex = "(Test)?$";
  585. LLVMStyle.IncludeBlocks = FormatStyle::IBS_Preserve;
  586. LLVMStyle.IndentCaseLabels = false;
  587. LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
  588. LLVMStyle.IndentWrappedFunctionNames = false;
  589. LLVMStyle.IndentWidth = 2;
  590. LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
  591. LLVMStyle.JavaScriptWrapImports = true;
  592. LLVMStyle.TabWidth = 8;
  593. LLVMStyle.MaxEmptyLinesToKeep = 1;
  594. LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
  595. LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
  596. LLVMStyle.ObjCBlockIndentWidth = 2;
  597. LLVMStyle.ObjCSpaceAfterProperty = false;
  598. LLVMStyle.ObjCSpaceBeforeProtocolList = true;
  599. LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
  600. LLVMStyle.SpacesBeforeTrailingComments = 1;
  601. LLVMStyle.Standard = FormatStyle::LS_Cpp11;
  602. LLVMStyle.UseTab = FormatStyle::UT_Never;
  603. LLVMStyle.ReflowComments = true;
  604. LLVMStyle.SpacesInParentheses = false;
  605. LLVMStyle.SpacesInSquareBrackets = false;
  606. LLVMStyle.SpaceInEmptyParentheses = false;
  607. LLVMStyle.SpacesInContainerLiterals = true;
  608. LLVMStyle.SpacesInCStyleCastParentheses = false;
  609. LLVMStyle.SpaceAfterCStyleCast = false;
  610. LLVMStyle.SpaceAfterTemplateKeyword = true;
  611. LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
  612. LLVMStyle.SpaceBeforeAssignmentOperators = true;
  613. LLVMStyle.SpacesInAngles = false;
  614. LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
  615. LLVMStyle.PenaltyBreakComment = 300;
  616. LLVMStyle.PenaltyBreakFirstLessLess = 120;
  617. LLVMStyle.PenaltyBreakString = 1000;
  618. LLVMStyle.PenaltyExcessCharacter = 1000000;
  619. LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
  620. LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
  621. LLVMStyle.DisableFormat = false;
  622. LLVMStyle.SortIncludes = true;
  623. LLVMStyle.SortUsingDeclarations = true;
  624. return LLVMStyle;
  625. }
  626. FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
  627. if (Language == FormatStyle::LK_TextProto) {
  628. FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
  629. GoogleStyle.Language = FormatStyle::LK_TextProto;
  630. return GoogleStyle;
  631. }
  632. FormatStyle GoogleStyle = getLLVMStyle();
  633. GoogleStyle.Language = Language;
  634. GoogleStyle.AccessModifierOffset = -1;
  635. GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
  636. GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
  637. GoogleStyle.AllowShortLoopsOnASingleLine = true;
  638. GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
  639. GoogleStyle.AlwaysBreakTemplateDeclarations = true;
  640. GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
  641. GoogleStyle.DerivePointerAlignment = true;
  642. GoogleStyle.IncludeCategories = {
  643. {"^<ext/.*\\.h>", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
  644. GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
  645. GoogleStyle.IndentCaseLabels = true;
  646. GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
  647. GoogleStyle.ObjCSpaceAfterProperty = false;
  648. GoogleStyle.ObjCSpaceBeforeProtocolList = true;
  649. GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
  650. GoogleStyle.RawStringFormats = {{
  651. FormatStyle::LK_TextProto,
  652. /*Delimiters=*/
  653. {
  654. "pb",
  655. "PB",
  656. "proto",
  657. "PROTO",
  658. "textproto",
  659. "TEXTPROTO",
  660. },
  661. /*EnclosingFunctionNames=*/
  662. {
  663. "EqualsProto",
  664. "PARSE_TEXT_PROTO",
  665. "ParseTextProto",
  666. },
  667. /*CanonicalDelimiter=*/"",
  668. /*BasedOnStyle=*/"google",
  669. }};
  670. GoogleStyle.SpacesBeforeTrailingComments = 2;
  671. GoogleStyle.Standard = FormatStyle::LS_Auto;
  672. GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  673. GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
  674. if (Language == FormatStyle::LK_Java) {
  675. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  676. GoogleStyle.AlignOperands = false;
  677. GoogleStyle.AlignTrailingComments = false;
  678. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  679. GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
  680. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  681. GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
  682. GoogleStyle.ColumnLimit = 100;
  683. GoogleStyle.SpaceAfterCStyleCast = true;
  684. GoogleStyle.SpacesBeforeTrailingComments = 1;
  685. } else if (Language == FormatStyle::LK_JavaScript) {
  686. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
  687. GoogleStyle.AlignOperands = false;
  688. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  689. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  690. GoogleStyle.BreakBeforeTernaryOperators = false;
  691. // taze:, triple slash directives (`/// <...`), @tag followed by { for a lot
  692. // of JSDoc tags, and @see, which is commonly followed by overlong URLs.
  693. GoogleStyle.CommentPragmas =
  694. "(taze:|^/[ \t]*<|(@[A-Za-z_0-9-]+[ \\t]*{)|@see)";
  695. GoogleStyle.MaxEmptyLinesToKeep = 3;
  696. GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
  697. GoogleStyle.SpacesInContainerLiterals = false;
  698. GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
  699. GoogleStyle.JavaScriptWrapImports = false;
  700. } else if (Language == FormatStyle::LK_Proto) {
  701. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
  702. GoogleStyle.SpacesInContainerLiterals = false;
  703. } else if (Language == FormatStyle::LK_ObjC) {
  704. GoogleStyle.ColumnLimit = 100;
  705. }
  706. return GoogleStyle;
  707. }
  708. FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
  709. FormatStyle ChromiumStyle = getGoogleStyle(Language);
  710. if (Language == FormatStyle::LK_Java) {
  711. ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
  712. ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
  713. ChromiumStyle.ContinuationIndentWidth = 8;
  714. ChromiumStyle.IndentWidth = 4;
  715. } else if (Language == FormatStyle::LK_JavaScript) {
  716. ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
  717. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  718. } else {
  719. ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  720. ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  721. ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
  722. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  723. ChromiumStyle.BinPackParameters = false;
  724. ChromiumStyle.DerivePointerAlignment = false;
  725. if (Language == FormatStyle::LK_ObjC)
  726. ChromiumStyle.ColumnLimit = 80;
  727. }
  728. return ChromiumStyle;
  729. }
  730. FormatStyle getMozillaStyle() {
  731. FormatStyle MozillaStyle = getLLVMStyle();
  732. MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  733. MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  734. MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
  735. MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
  736. FormatStyle::DRTBS_TopLevel;
  737. MozillaStyle.AlwaysBreakTemplateDeclarations = true;
  738. MozillaStyle.BinPackParameters = false;
  739. MozillaStyle.BinPackArguments = false;
  740. MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
  741. MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  742. MozillaStyle.BreakBeforeInheritanceComma = true;
  743. MozillaStyle.ConstructorInitializerIndentWidth = 2;
  744. MozillaStyle.ContinuationIndentWidth = 2;
  745. MozillaStyle.Cpp11BracedListStyle = false;
  746. MozillaStyle.FixNamespaceComments = false;
  747. MozillaStyle.IndentCaseLabels = true;
  748. MozillaStyle.ObjCSpaceAfterProperty = true;
  749. MozillaStyle.ObjCSpaceBeforeProtocolList = false;
  750. MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  751. MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
  752. MozillaStyle.SpaceAfterTemplateKeyword = false;
  753. return MozillaStyle;
  754. }
  755. FormatStyle getWebKitStyle() {
  756. FormatStyle Style = getLLVMStyle();
  757. Style.AccessModifierOffset = -4;
  758. Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  759. Style.AlignOperands = false;
  760. Style.AlignTrailingComments = false;
  761. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  762. Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
  763. Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
  764. Style.Cpp11BracedListStyle = false;
  765. Style.ColumnLimit = 0;
  766. Style.FixNamespaceComments = false;
  767. Style.IndentWidth = 4;
  768. Style.NamespaceIndentation = FormatStyle::NI_Inner;
  769. Style.ObjCBlockIndentWidth = 4;
  770. Style.ObjCSpaceAfterProperty = true;
  771. Style.PointerAlignment = FormatStyle::PAS_Left;
  772. return Style;
  773. }
  774. FormatStyle getGNUStyle() {
  775. FormatStyle Style = getLLVMStyle();
  776. Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
  777. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  778. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  779. Style.BreakBeforeBraces = FormatStyle::BS_GNU;
  780. Style.BreakBeforeTernaryOperators = true;
  781. Style.Cpp11BracedListStyle = false;
  782. Style.ColumnLimit = 79;
  783. Style.FixNamespaceComments = false;
  784. Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
  785. Style.Standard = FormatStyle::LS_Cpp03;
  786. return Style;
  787. }
  788. FormatStyle getNoStyle() {
  789. FormatStyle NoStyle = getLLVMStyle();
  790. NoStyle.DisableFormat = true;
  791. NoStyle.SortIncludes = false;
  792. NoStyle.SortUsingDeclarations = false;
  793. return NoStyle;
  794. }
  795. bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
  796. FormatStyle *Style) {
  797. if (Name.equals_lower("llvm")) {
  798. *Style = getLLVMStyle();
  799. } else if (Name.equals_lower("chromium")) {
  800. *Style = getChromiumStyle(Language);
  801. } else if (Name.equals_lower("mozilla")) {
  802. *Style = getMozillaStyle();
  803. } else if (Name.equals_lower("google")) {
  804. *Style = getGoogleStyle(Language);
  805. } else if (Name.equals_lower("webkit")) {
  806. *Style = getWebKitStyle();
  807. } else if (Name.equals_lower("gnu")) {
  808. *Style = getGNUStyle();
  809. } else if (Name.equals_lower("none")) {
  810. *Style = getNoStyle();
  811. } else {
  812. return false;
  813. }
  814. Style->Language = Language;
  815. return true;
  816. }
  817. std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
  818. assert(Style);
  819. FormatStyle::LanguageKind Language = Style->Language;
  820. assert(Language != FormatStyle::LK_None);
  821. if (Text.trim().empty())
  822. return make_error_code(ParseError::Error);
  823. Style->StyleSet.Clear();
  824. std::vector<FormatStyle> Styles;
  825. llvm::yaml::Input Input(Text);
  826. // DocumentListTraits<vector<FormatStyle>> uses the context to get default
  827. // values for the fields, keys for which are missing from the configuration.
  828. // Mapping also uses the context to get the language to find the correct
  829. // base style.
  830. Input.setContext(Style);
  831. Input >> Styles;
  832. if (Input.error())
  833. return Input.error();
  834. for (unsigned i = 0; i < Styles.size(); ++i) {
  835. // Ensures that only the first configuration can skip the Language option.
  836. if (Styles[i].Language == FormatStyle::LK_None && i != 0)
  837. return make_error_code(ParseError::Error);
  838. // Ensure that each language is configured at most once.
  839. for (unsigned j = 0; j < i; ++j) {
  840. if (Styles[i].Language == Styles[j].Language) {
  841. DEBUG(llvm::dbgs()
  842. << "Duplicate languages in the config file on positions " << j
  843. << " and " << i << "\n");
  844. return make_error_code(ParseError::Error);
  845. }
  846. }
  847. }
  848. // Look for a suitable configuration starting from the end, so we can
  849. // find the configuration for the specific language first, and the default
  850. // configuration (which can only be at slot 0) after it.
  851. FormatStyle::FormatStyleSet StyleSet;
  852. bool LanguageFound = false;
  853. for (int i = Styles.size() - 1; i >= 0; --i) {
  854. if (Styles[i].Language != FormatStyle::LK_None)
  855. StyleSet.Add(Styles[i]);
  856. if (Styles[i].Language == Language)
  857. LanguageFound = true;
  858. }
  859. if (!LanguageFound) {
  860. if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
  861. return make_error_code(ParseError::Unsuitable);
  862. FormatStyle DefaultStyle = Styles[0];
  863. DefaultStyle.Language = Language;
  864. StyleSet.Add(std::move(DefaultStyle));
  865. }
  866. *Style = *StyleSet.Get(Language);
  867. return make_error_code(ParseError::Success);
  868. }
  869. std::string configurationAsText(const FormatStyle &Style) {
  870. std::string Text;
  871. llvm::raw_string_ostream Stream(Text);
  872. llvm::yaml::Output Output(Stream);
  873. // We use the same mapping method for input and output, so we need a non-const
  874. // reference here.
  875. FormatStyle NonConstStyle = expandPresets(Style);
  876. Output << NonConstStyle;
  877. return Stream.str();
  878. }
  879. llvm::Optional<FormatStyle>
  880. FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
  881. if (!Styles)
  882. return None;
  883. auto It = Styles->find(Language);
  884. if (It == Styles->end())
  885. return None;
  886. FormatStyle Style = It->second;
  887. Style.StyleSet = *this;
  888. return Style;
  889. }
  890. void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
  891. assert(Style.Language != LK_None &&
  892. "Cannot add a style for LK_None to a StyleSet");
  893. assert(
  894. !Style.StyleSet.Styles &&
  895. "Cannot add a style associated with an existing StyleSet to a StyleSet");
  896. if (!Styles)
  897. Styles = std::make_shared<MapType>();
  898. (*Styles)[Style.Language] = std::move(Style);
  899. }
  900. void FormatStyle::FormatStyleSet::Clear() {
  901. Styles.reset();
  902. }
  903. llvm::Optional<FormatStyle>
  904. FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
  905. return StyleSet.Get(Language);
  906. }
  907. namespace {
  908. class JavaScriptRequoter : public TokenAnalyzer {
  909. public:
  910. JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
  911. : TokenAnalyzer(Env, Style) {}
  912. std::pair<tooling::Replacements, unsigned>
  913. analyze(TokenAnnotator &Annotator,
  914. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  915. FormatTokenLexer &Tokens) override {
  916. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  917. AnnotatedLines.end());
  918. tooling::Replacements Result;
  919. requoteJSStringLiteral(AnnotatedLines, Result);
  920. return {Result, 0};
  921. }
  922. private:
  923. // Replaces double/single-quoted string literal as appropriate, re-escaping
  924. // the contents in the process.
  925. void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
  926. tooling::Replacements &Result) {
  927. for (AnnotatedLine *Line : Lines) {
  928. requoteJSStringLiteral(Line->Children, Result);
  929. if (!Line->Affected)
  930. continue;
  931. for (FormatToken *FormatTok = Line->First; FormatTok;
  932. FormatTok = FormatTok->Next) {
  933. StringRef Input = FormatTok->TokenText;
  934. if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
  935. // NB: testing for not starting with a double quote to avoid
  936. // breaking `template strings`.
  937. (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
  938. !Input.startswith("\"")) ||
  939. (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
  940. !Input.startswith("\'")))
  941. continue;
  942. // Change start and end quote.
  943. bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
  944. SourceLocation Start = FormatTok->Tok.getLocation();
  945. auto Replace = [&](SourceLocation Start, unsigned Length,
  946. StringRef ReplacementText) {
  947. auto Err = Result.add(tooling::Replacement(
  948. Env.getSourceManager(), Start, Length, ReplacementText));
  949. // FIXME: handle error. For now, print error message and skip the
  950. // replacement for release version.
  951. if (Err) {
  952. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  953. assert(false);
  954. }
  955. };
  956. Replace(Start, 1, IsSingle ? "'" : "\"");
  957. Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
  958. IsSingle ? "'" : "\"");
  959. // Escape internal quotes.
  960. bool Escaped = false;
  961. for (size_t i = 1; i < Input.size() - 1; i++) {
  962. switch (Input[i]) {
  963. case '\\':
  964. if (!Escaped && i + 1 < Input.size() &&
  965. ((IsSingle && Input[i + 1] == '"') ||
  966. (!IsSingle && Input[i + 1] == '\''))) {
  967. // Remove this \, it's escaping a " or ' that no longer needs
  968. // escaping
  969. Replace(Start.getLocWithOffset(i), 1, "");
  970. continue;
  971. }
  972. Escaped = !Escaped;
  973. break;
  974. case '\"':
  975. case '\'':
  976. if (!Escaped && IsSingle == (Input[i] == '\'')) {
  977. // Escape the quote.
  978. Replace(Start.getLocWithOffset(i), 0, "\\");
  979. }
  980. Escaped = false;
  981. break;
  982. default:
  983. Escaped = false;
  984. break;
  985. }
  986. }
  987. }
  988. }
  989. }
  990. };
  991. class Formatter : public TokenAnalyzer {
  992. public:
  993. Formatter(const Environment &Env, const FormatStyle &Style,
  994. FormattingAttemptStatus *Status)
  995. : TokenAnalyzer(Env, Style), Status(Status) {}
  996. std::pair<tooling::Replacements, unsigned>
  997. analyze(TokenAnnotator &Annotator,
  998. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  999. FormatTokenLexer &Tokens) override {
  1000. tooling::Replacements Result;
  1001. deriveLocalStyle(AnnotatedLines);
  1002. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  1003. AnnotatedLines.end());
  1004. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1005. Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
  1006. }
  1007. Annotator.setCommentLineLevels(AnnotatedLines);
  1008. WhitespaceManager Whitespaces(
  1009. Env.getSourceManager(), Style,
  1010. inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
  1011. ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
  1012. Env.getSourceManager(), Whitespaces, Encoding,
  1013. BinPackInconclusiveFunctions);
  1014. unsigned Penalty =
  1015. UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
  1016. Tokens.getKeywords(), Env.getSourceManager(),
  1017. Status)
  1018. .format(AnnotatedLines, /*DryRun=*/false,
  1019. /*AdditionalIndent=*/0,
  1020. /*FixBadIndentation=*/false,
  1021. /*FirstStartColumn=*/Env.getFirstStartColumn(),
  1022. /*NextStartColumn=*/Env.getNextStartColumn(),
  1023. /*LastStartColumn=*/Env.getLastStartColumn());
  1024. for (const auto &R : Whitespaces.generateReplacements())
  1025. if (Result.add(R))
  1026. return std::make_pair(Result, 0);
  1027. return std::make_pair(Result, Penalty);
  1028. }
  1029. private:
  1030. static bool inputUsesCRLF(StringRef Text) {
  1031. return Text.count('\r') * 2 > Text.count('\n');
  1032. }
  1033. bool
  1034. hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  1035. for (const AnnotatedLine *Line : Lines) {
  1036. if (hasCpp03IncompatibleFormat(Line->Children))
  1037. return true;
  1038. for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
  1039. if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
  1040. if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
  1041. return true;
  1042. if (Tok->is(TT_TemplateCloser) &&
  1043. Tok->Previous->is(TT_TemplateCloser))
  1044. return true;
  1045. }
  1046. }
  1047. }
  1048. return false;
  1049. }
  1050. int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  1051. int AlignmentDiff = 0;
  1052. for (const AnnotatedLine *Line : Lines) {
  1053. AlignmentDiff += countVariableAlignments(Line->Children);
  1054. for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
  1055. if (!Tok->is(TT_PointerOrReference))
  1056. continue;
  1057. bool SpaceBefore =
  1058. Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
  1059. bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
  1060. Tok->Next->WhitespaceRange.getEnd();
  1061. if (SpaceBefore && !SpaceAfter)
  1062. ++AlignmentDiff;
  1063. if (!SpaceBefore && SpaceAfter)
  1064. --AlignmentDiff;
  1065. }
  1066. }
  1067. return AlignmentDiff;
  1068. }
  1069. void
  1070. deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  1071. bool HasBinPackedFunction = false;
  1072. bool HasOnePerLineFunction = false;
  1073. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1074. if (!AnnotatedLines[i]->First->Next)
  1075. continue;
  1076. FormatToken *Tok = AnnotatedLines[i]->First->Next;
  1077. while (Tok->Next) {
  1078. if (Tok->PackingKind == PPK_BinPacked)
  1079. HasBinPackedFunction = true;
  1080. if (Tok->PackingKind == PPK_OnePerLine)
  1081. HasOnePerLineFunction = true;
  1082. Tok = Tok->Next;
  1083. }
  1084. }
  1085. if (Style.DerivePointerAlignment)
  1086. Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
  1087. ? FormatStyle::PAS_Left
  1088. : FormatStyle::PAS_Right;
  1089. if (Style.Standard == FormatStyle::LS_Auto)
  1090. Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
  1091. ? FormatStyle::LS_Cpp11
  1092. : FormatStyle::LS_Cpp03;
  1093. BinPackInconclusiveFunctions =
  1094. HasBinPackedFunction || !HasOnePerLineFunction;
  1095. }
  1096. bool BinPackInconclusiveFunctions;
  1097. FormattingAttemptStatus *Status;
  1098. };
  1099. // This class clean up the erroneous/redundant code around the given ranges in
  1100. // file.
  1101. class Cleaner : public TokenAnalyzer {
  1102. public:
  1103. Cleaner(const Environment &Env, const FormatStyle &Style)
  1104. : TokenAnalyzer(Env, Style),
  1105. DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
  1106. // FIXME: eliminate unused parameters.
  1107. std::pair<tooling::Replacements, unsigned>
  1108. analyze(TokenAnnotator &Annotator,
  1109. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1110. FormatTokenLexer &Tokens) override {
  1111. // FIXME: in the current implementation the granularity of affected range
  1112. // is an annotated line. However, this is not sufficient. Furthermore,
  1113. // redundant code introduced by replacements does not necessarily
  1114. // intercept with ranges of replacements that result in the redundancy.
  1115. // To determine if some redundant code is actually introduced by
  1116. // replacements(e.g. deletions), we need to come up with a more
  1117. // sophisticated way of computing affected ranges.
  1118. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  1119. AnnotatedLines.end());
  1120. checkEmptyNamespace(AnnotatedLines);
  1121. for (auto &Line : AnnotatedLines) {
  1122. if (Line->Affected) {
  1123. cleanupRight(Line->First, tok::comma, tok::comma);
  1124. cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
  1125. cleanupRight(Line->First, tok::l_paren, tok::comma);
  1126. cleanupLeft(Line->First, tok::comma, tok::r_paren);
  1127. cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
  1128. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
  1129. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
  1130. }
  1131. }
  1132. return {generateFixes(), 0};
  1133. }
  1134. private:
  1135. bool containsOnlyComments(const AnnotatedLine &Line) {
  1136. for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
  1137. if (Tok->isNot(tok::comment))
  1138. return false;
  1139. }
  1140. return true;
  1141. }
  1142. // Iterate through all lines and remove any empty (nested) namespaces.
  1143. void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  1144. std::set<unsigned> DeletedLines;
  1145. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1146. auto &Line = *AnnotatedLines[i];
  1147. if (Line.startsWith(tok::kw_namespace) ||
  1148. Line.startsWith(tok::kw_inline, tok::kw_namespace)) {
  1149. checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
  1150. }
  1151. }
  1152. for (auto Line : DeletedLines) {
  1153. FormatToken *Tok = AnnotatedLines[Line]->First;
  1154. while (Tok) {
  1155. deleteToken(Tok);
  1156. Tok = Tok->Next;
  1157. }
  1158. }
  1159. }
  1160. // The function checks if the namespace, which starts from \p CurrentLine, and
  1161. // its nested namespaces are empty and delete them if they are empty. It also
  1162. // sets \p NewLine to the last line checked.
  1163. // Returns true if the current namespace is empty.
  1164. bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1165. unsigned CurrentLine, unsigned &NewLine,
  1166. std::set<unsigned> &DeletedLines) {
  1167. unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
  1168. if (Style.BraceWrapping.AfterNamespace) {
  1169. // If the left brace is in a new line, we should consume it first so that
  1170. // it does not make the namespace non-empty.
  1171. // FIXME: error handling if there is no left brace.
  1172. if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
  1173. NewLine = CurrentLine;
  1174. return false;
  1175. }
  1176. } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
  1177. return false;
  1178. }
  1179. while (++CurrentLine < End) {
  1180. if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
  1181. break;
  1182. if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) ||
  1183. AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline,
  1184. tok::kw_namespace)) {
  1185. if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
  1186. DeletedLines))
  1187. return false;
  1188. CurrentLine = NewLine;
  1189. continue;
  1190. }
  1191. if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
  1192. continue;
  1193. // If there is anything other than comments or nested namespaces in the
  1194. // current namespace, the namespace cannot be empty.
  1195. NewLine = CurrentLine;
  1196. return false;
  1197. }
  1198. NewLine = CurrentLine;
  1199. if (CurrentLine >= End)
  1200. return false;
  1201. // Check if the empty namespace is actually affected by changed ranges.
  1202. if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
  1203. AnnotatedLines[InitLine]->First->Tok.getLocation(),
  1204. AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
  1205. return false;
  1206. for (unsigned i = InitLine; i <= CurrentLine; ++i) {
  1207. DeletedLines.insert(i);
  1208. }
  1209. return true;
  1210. }
  1211. // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
  1212. // of the token in the pair if the left token has \p LK token kind and the
  1213. // right token has \p RK token kind. If \p DeleteLeft is true, the left token
  1214. // is deleted on match; otherwise, the right token is deleted.
  1215. template <typename LeftKind, typename RightKind>
  1216. void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
  1217. bool DeleteLeft) {
  1218. auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
  1219. for (auto *Res = Tok.Next; Res; Res = Res->Next)
  1220. if (!Res->is(tok::comment) &&
  1221. DeletedTokens.find(Res) == DeletedTokens.end())
  1222. return Res;
  1223. return nullptr;
  1224. };
  1225. for (auto *Left = Start; Left;) {
  1226. auto *Right = NextNotDeleted(*Left);
  1227. if (!Right)
  1228. break;
  1229. if (Left->is(LK) && Right->is(RK)) {
  1230. deleteToken(DeleteLeft ? Left : Right);
  1231. for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
  1232. deleteToken(Tok);
  1233. // If the right token is deleted, we should keep the left token
  1234. // unchanged and pair it with the new right token.
  1235. if (!DeleteLeft)
  1236. continue;
  1237. }
  1238. Left = Right;
  1239. }
  1240. }
  1241. template <typename LeftKind, typename RightKind>
  1242. void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
  1243. cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
  1244. }
  1245. template <typename LeftKind, typename RightKind>
  1246. void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
  1247. cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
  1248. }
  1249. // Delete the given token.
  1250. inline void deleteToken(FormatToken *Tok) {
  1251. if (Tok)
  1252. DeletedTokens.insert(Tok);
  1253. }
  1254. tooling::Replacements generateFixes() {
  1255. tooling::Replacements Fixes;
  1256. std::vector<FormatToken *> Tokens;
  1257. std::copy(DeletedTokens.begin(), DeletedTokens.end(),
  1258. std::back_inserter(Tokens));
  1259. // Merge multiple continuous token deletions into one big deletion so that
  1260. // the number of replacements can be reduced. This makes computing affected
  1261. // ranges more efficient when we run reformat on the changed code.
  1262. unsigned Idx = 0;
  1263. while (Idx < Tokens.size()) {
  1264. unsigned St = Idx, End = Idx;
  1265. while ((End + 1) < Tokens.size() &&
  1266. Tokens[End]->Next == Tokens[End + 1]) {
  1267. End++;
  1268. }
  1269. auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
  1270. Tokens[End]->Tok.getEndLoc());
  1271. auto Err =
  1272. Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
  1273. // FIXME: better error handling. for now just print error message and skip
  1274. // for the release version.
  1275. if (Err) {
  1276. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1277. assert(false && "Fixes must not conflict!");
  1278. }
  1279. Idx = End + 1;
  1280. }
  1281. return Fixes;
  1282. }
  1283. // Class for less-than inequality comparason for the set `RedundantTokens`.
  1284. // We store tokens in the order they appear in the translation unit so that
  1285. // we do not need to sort them in `generateFixes()`.
  1286. struct FormatTokenLess {
  1287. FormatTokenLess(const SourceManager &SM) : SM(SM) {}
  1288. bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
  1289. return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
  1290. RHS->Tok.getLocation());
  1291. }
  1292. const SourceManager &SM;
  1293. };
  1294. // Tokens to be deleted.
  1295. std::set<FormatToken *, FormatTokenLess> DeletedTokens;
  1296. };
  1297. class ObjCHeaderStyleGuesser : public TokenAnalyzer {
  1298. public:
  1299. ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
  1300. : TokenAnalyzer(Env, Style), IsObjC(false) {}
  1301. std::pair<tooling::Replacements, unsigned>
  1302. analyze(TokenAnnotator &Annotator,
  1303. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1304. FormatTokenLexer &Tokens) override {
  1305. assert(Style.Language == FormatStyle::LK_Cpp);
  1306. IsObjC = guessIsObjC(AnnotatedLines, Tokens.getKeywords());
  1307. tooling::Replacements Result;
  1308. return {Result, 0};
  1309. }
  1310. bool isObjC() { return IsObjC; }
  1311. private:
  1312. static bool guessIsObjC(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1313. const AdditionalKeywords &Keywords) {
  1314. // Keep this array sorted, since we are binary searching over it.
  1315. static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
  1316. "CGFloat",
  1317. "NSAffineTransform",
  1318. "NSArray",
  1319. "NSAttributedString",
  1320. "NSCache",
  1321. "NSCharacterSet",
  1322. "NSCountedSet",
  1323. "NSData",
  1324. "NSDataDetector",
  1325. "NSDecimal",
  1326. "NSDecimalNumber",
  1327. "NSDictionary",
  1328. "NSEdgeInsets",
  1329. "NSHashTable",
  1330. "NSIndexPath",
  1331. "NSIndexSet",
  1332. "NSInteger",
  1333. "NSLocale",
  1334. "NSMapTable",
  1335. "NSMutableArray",
  1336. "NSMutableAttributedString",
  1337. "NSMutableCharacterSet",
  1338. "NSMutableData",
  1339. "NSMutableDictionary",
  1340. "NSMutableIndexSet",
  1341. "NSMutableOrderedSet",
  1342. "NSMutableSet",
  1343. "NSMutableString",
  1344. "NSNumber",
  1345. "NSNumberFormatter",
  1346. "NSOrderedSet",
  1347. "NSPoint",
  1348. "NSPointerArray",
  1349. "NSRange",
  1350. "NSRect",
  1351. "NSRegularExpression",
  1352. "NSSet",
  1353. "NSSize",
  1354. "NSString",
  1355. "NSUInteger",
  1356. "NSURL",
  1357. "NSURLComponents",
  1358. "NSURLQueryItem",
  1359. "NSUUID",
  1360. };
  1361. for (auto &Line : AnnotatedLines) {
  1362. for (FormatToken *FormatTok = Line->First->Next; FormatTok;
  1363. FormatTok = FormatTok->Next) {
  1364. if ((FormatTok->Previous->is(tok::at) &&
  1365. (FormatTok->isObjCAtKeyword(tok::objc_interface) ||
  1366. FormatTok->isObjCAtKeyword(tok::objc_implementation) ||
  1367. FormatTok->isObjCAtKeyword(tok::objc_protocol) ||
  1368. FormatTok->isObjCAtKeyword(tok::objc_end) ||
  1369. FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
  1370. tok::l_brace))) ||
  1371. (FormatTok->Tok.isAnyIdentifier() &&
  1372. std::binary_search(std::begin(FoundationIdentifiers),
  1373. std::end(FoundationIdentifiers),
  1374. FormatTok->TokenText)) ||
  1375. FormatTok->is(TT_ObjCStringLiteral) ||
  1376. FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
  1377. TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
  1378. TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
  1379. TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
  1380. return true;
  1381. }
  1382. }
  1383. }
  1384. return false;
  1385. }
  1386. bool IsObjC;
  1387. };
  1388. struct IncludeDirective {
  1389. StringRef Filename;
  1390. StringRef Text;
  1391. unsigned Offset;
  1392. int Category;
  1393. };
  1394. } // end anonymous namespace
  1395. // Determines whether 'Ranges' intersects with ('Start', 'End').
  1396. static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
  1397. unsigned End) {
  1398. for (auto Range : Ranges) {
  1399. if (Range.getOffset() < End &&
  1400. Range.getOffset() + Range.getLength() > Start)
  1401. return true;
  1402. }
  1403. return false;
  1404. }
  1405. // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
  1406. // before sorting/deduplicating. Index is the index of the include under the
  1407. // cursor in the original set of includes. If this include has duplicates, it is
  1408. // the index of the first of the duplicates as the others are going to be
  1409. // removed. OffsetToEOL describes the cursor's position relative to the end of
  1410. // its current line.
  1411. // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
  1412. static std::pair<unsigned, unsigned>
  1413. FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
  1414. const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
  1415. unsigned CursorIndex = UINT_MAX;
  1416. unsigned OffsetToEOL = 0;
  1417. for (int i = 0, e = Includes.size(); i != e; ++i) {
  1418. unsigned Start = Includes[Indices[i]].Offset;
  1419. unsigned End = Start + Includes[Indices[i]].Text.size();
  1420. if (!(Cursor >= Start && Cursor < End))
  1421. continue;
  1422. CursorIndex = Indices[i];
  1423. OffsetToEOL = End - Cursor;
  1424. // Put the cursor on the only remaining #include among the duplicate
  1425. // #includes.
  1426. while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
  1427. CursorIndex = i;
  1428. break;
  1429. }
  1430. return std::make_pair(CursorIndex, OffsetToEOL);
  1431. }
  1432. // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
  1433. // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
  1434. // source order.
  1435. // #include directives with the same text will be deduplicated, and only the
  1436. // first #include in the duplicate #includes remains. If the `Cursor` is
  1437. // provided and put on a deleted #include, it will be moved to the remaining
  1438. // #include in the duplicate #includes.
  1439. static void sortCppIncludes(const FormatStyle &Style,
  1440. const SmallVectorImpl<IncludeDirective> &Includes,
  1441. ArrayRef<tooling::Range> Ranges, StringRef FileName,
  1442. tooling::Replacements &Replaces, unsigned *Cursor) {
  1443. unsigned IncludesBeginOffset = Includes.front().Offset;
  1444. unsigned IncludesEndOffset =
  1445. Includes.back().Offset + Includes.back().Text.size();
  1446. unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
  1447. if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
  1448. return;
  1449. SmallVector<unsigned, 16> Indices;
  1450. for (unsigned i = 0, e = Includes.size(); i != e; ++i)
  1451. Indices.push_back(i);
  1452. std::stable_sort(
  1453. Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
  1454. return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
  1455. std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
  1456. });
  1457. // The index of the include on which the cursor will be put after
  1458. // sorting/deduplicating.
  1459. unsigned CursorIndex;
  1460. // The offset from cursor to the end of line.
  1461. unsigned CursorToEOLOffset;
  1462. if (Cursor)
  1463. std::tie(CursorIndex, CursorToEOLOffset) =
  1464. FindCursorIndex(Includes, Indices, *Cursor);
  1465. // Deduplicate #includes.
  1466. Indices.erase(std::unique(Indices.begin(), Indices.end(),
  1467. [&](unsigned LHSI, unsigned RHSI) {
  1468. return Includes[LHSI].Text == Includes[RHSI].Text;
  1469. }),
  1470. Indices.end());
  1471. int CurrentCategory = Includes.front().Category;
  1472. // If the #includes are out of order, we generate a single replacement fixing
  1473. // the entire block. Otherwise, no replacement is generated.
  1474. if (Indices.size() == Includes.size() &&
  1475. std::is_sorted(Indices.begin(), Indices.end()) &&
  1476. Style.IncludeBlocks == FormatStyle::IBS_Preserve)
  1477. return;
  1478. std::string result;
  1479. for (unsigned Index : Indices) {
  1480. if (!result.empty()) {
  1481. result += "\n";
  1482. if (Style.IncludeBlocks == FormatStyle::IBS_Regroup &&
  1483. CurrentCategory != Includes[Index].Category)
  1484. result += "\n";
  1485. }
  1486. result += Includes[Index].Text;
  1487. if (Cursor && CursorIndex == Index)
  1488. *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
  1489. CurrentCategory = Includes[Index].Category;
  1490. }
  1491. auto Err = Replaces.add(tooling::Replacement(
  1492. FileName, Includes.front().Offset, IncludesBlockSize, result));
  1493. // FIXME: better error handling. For now, just skip the replacement for the
  1494. // release version.
  1495. if (Err) {
  1496. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1497. assert(false);
  1498. }
  1499. }
  1500. namespace {
  1501. // This class manages priorities of #include categories and calculates
  1502. // priorities for headers.
  1503. class IncludeCategoryManager {
  1504. public:
  1505. IncludeCategoryManager(const FormatStyle &Style, StringRef FileName)
  1506. : Style(Style), FileName(FileName) {
  1507. FileStem = llvm::sys::path::stem(FileName);
  1508. for (const auto &Category : Style.IncludeCategories)
  1509. CategoryRegexs.emplace_back(Category.Regex, llvm::Regex::IgnoreCase);
  1510. IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
  1511. FileName.endswith(".cpp") || FileName.endswith(".c++") ||
  1512. FileName.endswith(".cxx") || FileName.endswith(".m") ||
  1513. FileName.endswith(".mm");
  1514. }
  1515. // Returns the priority of the category which \p IncludeName belongs to.
  1516. // If \p CheckMainHeader is true and \p IncludeName is a main header, returns
  1517. // 0. Otherwise, returns the priority of the matching category or INT_MAX.
  1518. int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) {
  1519. int Ret = INT_MAX;
  1520. for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
  1521. if (CategoryRegexs[i].match(IncludeName)) {
  1522. Ret = Style.IncludeCategories[i].Priority;
  1523. break;
  1524. }
  1525. if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
  1526. Ret = 0;
  1527. return Ret;
  1528. }
  1529. private:
  1530. bool isMainHeader(StringRef IncludeName) const {
  1531. if (!IncludeName.startswith("\""))
  1532. return false;
  1533. StringRef HeaderStem =
  1534. llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
  1535. if (FileStem.startswith(HeaderStem) ||
  1536. FileStem.startswith_lower(HeaderStem)) {
  1537. llvm::Regex MainIncludeRegex(
  1538. (HeaderStem + Style.IncludeIsMainRegex).str(),
  1539. llvm::Regex::IgnoreCase);
  1540. if (MainIncludeRegex.match(FileStem))
  1541. return true;
  1542. }
  1543. return false;
  1544. }
  1545. const FormatStyle &Style;
  1546. bool IsMainFile;
  1547. StringRef FileName;
  1548. StringRef FileStem;
  1549. SmallVector<llvm::Regex, 4> CategoryRegexs;
  1550. };
  1551. const char IncludeRegexPattern[] =
  1552. R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
  1553. } // anonymous namespace
  1554. tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
  1555. ArrayRef<tooling::Range> Ranges,
  1556. StringRef FileName,
  1557. tooling::Replacements &Replaces,
  1558. unsigned *Cursor) {
  1559. unsigned Prev = 0;
  1560. unsigned SearchFrom = 0;
  1561. llvm::Regex IncludeRegex(IncludeRegexPattern);
  1562. SmallVector<StringRef, 4> Matches;
  1563. SmallVector<IncludeDirective, 16> IncludesInBlock;
  1564. // In compiled files, consider the first #include to be the main #include of
  1565. // the file if it is not a system #include. This ensures that the header
  1566. // doesn't have hidden dependencies
  1567. // (http://llvm.org/docs/CodingStandards.html#include-style).
  1568. //
  1569. // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
  1570. // cases where the first #include is unlikely to be the main header.
  1571. IncludeCategoryManager Categories(Style, FileName);
  1572. bool FirstIncludeBlock = true;
  1573. bool MainIncludeFound = false;
  1574. bool FormattingOff = false;
  1575. for (;;) {
  1576. auto Pos = Code.find('\n', SearchFrom);
  1577. StringRef Line =
  1578. Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
  1579. StringRef Trimmed = Line.trim();
  1580. if (Trimmed == "// clang-format off")
  1581. FormattingOff = true;
  1582. else if (Trimmed == "// clang-format on")
  1583. FormattingOff = false;
  1584. const bool EmptyLineSkipped =
  1585. Trimmed.empty() && (Style.IncludeBlocks == FormatStyle::IBS_Merge ||
  1586. Style.IncludeBlocks == FormatStyle::IBS_Regroup);
  1587. if (!FormattingOff && !Line.endswith("\\")) {
  1588. if (IncludeRegex.match(Line, &Matches)) {
  1589. StringRef IncludeName = Matches[2];
  1590. int Category = Categories.getIncludePriority(
  1591. IncludeName,
  1592. /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
  1593. if (Category == 0)
  1594. MainIncludeFound = true;
  1595. IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
  1596. } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
  1597. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
  1598. Cursor);
  1599. IncludesInBlock.clear();
  1600. FirstIncludeBlock = false;
  1601. }
  1602. Prev = Pos + 1;
  1603. }
  1604. if (Pos == StringRef::npos || Pos + 1 == Code.size())
  1605. break;
  1606. SearchFrom = Pos + 1;
  1607. }
  1608. if (!IncludesInBlock.empty())
  1609. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
  1610. return Replaces;
  1611. }
  1612. bool isMpegTS(StringRef Code) {
  1613. // MPEG transport streams use the ".ts" file extension. clang-format should
  1614. // not attempt to format those. MPEG TS' frame format starts with 0x47 every
  1615. // 189 bytes - detect that and return.
  1616. return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
  1617. }
  1618. bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
  1619. tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
  1620. ArrayRef<tooling::Range> Ranges,
  1621. StringRef FileName, unsigned *Cursor) {
  1622. tooling::Replacements Replaces;
  1623. if (!Style.SortIncludes)
  1624. return Replaces;
  1625. if (isLikelyXml(Code))
  1626. return Replaces;
  1627. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
  1628. isMpegTS(Code))
  1629. return Replaces;
  1630. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
  1631. return sortJavaScriptImports(Style, Code, Ranges, FileName);
  1632. sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
  1633. return Replaces;
  1634. }
  1635. template <typename T>
  1636. static llvm::Expected<tooling::Replacements>
  1637. processReplacements(T ProcessFunc, StringRef Code,
  1638. const tooling::Replacements &Replaces,
  1639. const FormatStyle &Style) {
  1640. if (Replaces.empty())
  1641. return tooling::Replacements();
  1642. auto NewCode = applyAllReplacements(Code, Replaces);
  1643. if (!NewCode)
  1644. return NewCode.takeError();
  1645. std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
  1646. StringRef FileName = Replaces.begin()->getFilePath();
  1647. tooling::Replacements FormatReplaces =
  1648. ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
  1649. return Replaces.merge(FormatReplaces);
  1650. }
  1651. llvm::Expected<tooling::Replacements>
  1652. formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
  1653. const FormatStyle &Style) {
  1654. // We need to use lambda function here since there are two versions of
  1655. // `sortIncludes`.
  1656. auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
  1657. std::vector<tooling::Range> Ranges,
  1658. StringRef FileName) -> tooling::Replacements {
  1659. return sortIncludes(Style, Code, Ranges, FileName);
  1660. };
  1661. auto SortedReplaces =
  1662. processReplacements(SortIncludes, Code, Replaces, Style);
  1663. if (!SortedReplaces)
  1664. return SortedReplaces.takeError();
  1665. // We need to use lambda function here since there are two versions of
  1666. // `reformat`.
  1667. auto Reformat = [](const FormatStyle &Style, StringRef Code,
  1668. std::vector<tooling::Range> Ranges,
  1669. StringRef FileName) -> tooling::Replacements {
  1670. return reformat(Style, Code, Ranges, FileName);
  1671. };
  1672. return processReplacements(Reformat, Code, *SortedReplaces, Style);
  1673. }
  1674. namespace {
  1675. inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
  1676. return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
  1677. llvm::Regex(IncludeRegexPattern).match(Replace.getReplacementText());
  1678. }
  1679. inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
  1680. return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
  1681. }
  1682. // Returns the offset after skipping a sequence of tokens, matched by \p
  1683. // GetOffsetAfterSequence, from the start of the code.
  1684. // \p GetOffsetAfterSequence should be a function that matches a sequence of
  1685. // tokens and returns an offset after the sequence.
  1686. unsigned getOffsetAfterTokenSequence(
  1687. StringRef FileName, StringRef Code, const FormatStyle &Style,
  1688. llvm::function_ref<unsigned(const SourceManager &, Lexer &, Token &)>
  1689. GetOffsetAfterSequence) {
  1690. std::unique_ptr<Environment> Env =
  1691. Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
  1692. const SourceManager &SourceMgr = Env->getSourceManager();
  1693. Lexer Lex(Env->getFileID(), SourceMgr.getBuffer(Env->getFileID()), SourceMgr,
  1694. getFormattingLangOpts(Style));
  1695. Token Tok;
  1696. // Get the first token.
  1697. Lex.LexFromRawLexer(Tok);
  1698. return GetOffsetAfterSequence(SourceMgr, Lex, Tok);
  1699. }
  1700. // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
  1701. // \p Tok will be the token after this directive; otherwise, it can be any token
  1702. // after the given \p Tok (including \p Tok).
  1703. bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) {
  1704. bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
  1705. Tok.is(tok::raw_identifier) &&
  1706. Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
  1707. Tok.is(tok::raw_identifier);
  1708. if (Matched)
  1709. Lex.LexFromRawLexer(Tok);
  1710. return Matched;
  1711. }
  1712. void skipComments(Lexer &Lex, Token &Tok) {
  1713. while (Tok.is(tok::comment))
  1714. if (Lex.LexFromRawLexer(Tok))
  1715. return;
  1716. }
  1717. // Returns the offset after header guard directives and any comments
  1718. // before/after header guards. If no header guard presents in the code, this
  1719. // will returns the offset after skipping all comments from the start of the
  1720. // code.
  1721. unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
  1722. StringRef Code,
  1723. const FormatStyle &Style) {
  1724. return getOffsetAfterTokenSequence(
  1725. FileName, Code, Style,
  1726. [](const SourceManager &SM, Lexer &Lex, Token Tok) {
  1727. skipComments(Lex, Tok);
  1728. unsigned InitialOffset = SM.getFileOffset(Tok.getLocation());
  1729. if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
  1730. skipComments(Lex, Tok);
  1731. if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
  1732. return SM.getFileOffset(Tok.getLocation());
  1733. }
  1734. return InitialOffset;
  1735. });
  1736. }
  1737. // Check if a sequence of tokens is like
  1738. // "#include ("header.h" | <header.h>)".
  1739. // If it is, \p Tok will be the token after this directive; otherwise, it can be
  1740. // any token after the given \p Tok (including \p Tok).
  1741. bool checkAndConsumeInclusiveDirective(Lexer &Lex, Token &Tok) {
  1742. auto Matched = [&]() {
  1743. Lex.LexFromRawLexer(Tok);
  1744. return true;
  1745. };
  1746. if (Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
  1747. Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == "include") {
  1748. if (Lex.LexFromRawLexer(Tok))
  1749. return false;
  1750. if (Tok.is(tok::string_literal))
  1751. return Matched();
  1752. if (Tok.is(tok::less)) {
  1753. while (!Lex.LexFromRawLexer(Tok) && Tok.isNot(tok::greater)) {
  1754. }
  1755. if (Tok.is(tok::greater))
  1756. return Matched();
  1757. }
  1758. }
  1759. return false;
  1760. }
  1761. // Returns the offset of the last #include directive after which a new
  1762. // #include can be inserted. This ignores #include's after the #include block(s)
  1763. // in the beginning of a file to avoid inserting headers into code sections
  1764. // where new #include's should not be added by default.
  1765. // These code sections include:
  1766. // - raw string literals (containing #include).
  1767. // - #if blocks.
  1768. // - Special #include's among declarations (e.g. functions).
  1769. //
  1770. // If no #include after which a new #include can be inserted, this returns the
  1771. // offset after skipping all comments from the start of the code.
  1772. // Inserting after an #include is not allowed if it comes after code that is not
  1773. // #include (e.g. pre-processing directive that is not #include, declarations).
  1774. unsigned getMaxHeaderInsertionOffset(StringRef FileName, StringRef Code,
  1775. const FormatStyle &Style) {
  1776. return getOffsetAfterTokenSequence(
  1777. FileName, Code, Style,
  1778. [](const SourceManager &SM, Lexer &Lex, Token Tok) {
  1779. skipComments(Lex, Tok);
  1780. unsigned MaxOffset = SM.getFileOffset(Tok.getLocation());
  1781. while (checkAndConsumeInclusiveDirective(Lex, Tok))
  1782. MaxOffset = SM.getFileOffset(Tok.getLocation());
  1783. return MaxOffset;
  1784. });
  1785. }
  1786. bool isDeletedHeader(llvm::StringRef HeaderName,
  1787. const std::set<llvm::StringRef> &HeadersToDelete) {
  1788. return HeadersToDelete.count(HeaderName) ||
  1789. HeadersToDelete.count(HeaderName.trim("\"<>"));
  1790. }
  1791. // FIXME: insert empty lines between newly created blocks.
  1792. tooling::Replacements
  1793. fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
  1794. const FormatStyle &Style) {
  1795. if (!Style.isCpp())
  1796. return Replaces;
  1797. tooling::Replacements HeaderInsertions;
  1798. std::set<llvm::StringRef> HeadersToDelete;
  1799. tooling::Replacements Result;
  1800. for (const auto &R : Replaces) {
  1801. if (isHeaderInsertion(R)) {
  1802. // Replacements from \p Replaces must be conflict-free already, so we can
  1803. // simply consume the error.
  1804. llvm::consumeError(HeaderInsertions.add(R));
  1805. } else if (isHeaderDeletion(R)) {
  1806. HeadersToDelete.insert(R.getReplacementText());
  1807. } else if (R.getOffset() == UINT_MAX) {
  1808. llvm::errs() << "Insertions other than header #include insertion are "
  1809. "not supported! "
  1810. << R.getReplacementText() << "\n";
  1811. } else {
  1812. llvm::consumeError(Result.add(R));
  1813. }
  1814. }
  1815. if (HeaderInsertions.empty() && HeadersToDelete.empty())
  1816. return Replaces;
  1817. llvm::Regex IncludeRegex(IncludeRegexPattern);
  1818. llvm::Regex DefineRegex(R"(^[\t\ ]*#[\t\ ]*define[\t\ ]*[^\\]*$)");
  1819. SmallVector<StringRef, 4> Matches;
  1820. StringRef FileName = Replaces.begin()->getFilePath();
  1821. IncludeCategoryManager Categories(Style, FileName);
  1822. // Record the offset of the end of the last include in each category.
  1823. std::map<int, int> CategoryEndOffsets;
  1824. // All possible priorities.
  1825. // Add 0 for main header and INT_MAX for headers that are not in any category.
  1826. std::set<int> Priorities = {0, INT_MAX};
  1827. for (const auto &Category : Style.IncludeCategories)
  1828. Priorities.insert(Category.Priority);
  1829. int FirstIncludeOffset = -1;
  1830. // All new headers should be inserted after this offset.
  1831. unsigned MinInsertOffset =
  1832. getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style);
  1833. StringRef TrimmedCode = Code.drop_front(MinInsertOffset);
  1834. // Max insertion offset in the original code.
  1835. unsigned MaxInsertOffset =
  1836. MinInsertOffset +
  1837. getMaxHeaderInsertionOffset(FileName, TrimmedCode, Style);
  1838. SmallVector<StringRef, 32> Lines;
  1839. TrimmedCode.split(Lines, '\n');
  1840. unsigned Offset = MinInsertOffset;
  1841. unsigned NextLineOffset;
  1842. std::set<StringRef> ExistingIncludes;
  1843. for (auto Line : Lines) {
  1844. NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
  1845. if (IncludeRegex.match(Line, &Matches)) {
  1846. // The header name with quotes or angle brackets.
  1847. StringRef IncludeName = Matches[2];
  1848. ExistingIncludes.insert(IncludeName);
  1849. // Only record the offset of current #include if we can insert after it.
  1850. if (Offset <= MaxInsertOffset) {
  1851. int Category = Categories.getIncludePriority(
  1852. IncludeName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
  1853. CategoryEndOffsets[Category] = NextLineOffset;
  1854. if (FirstIncludeOffset < 0)
  1855. FirstIncludeOffset = Offset;
  1856. }
  1857. if (isDeletedHeader(IncludeName, HeadersToDelete)) {
  1858. // If this is the last line without trailing newline, we need to make
  1859. // sure we don't delete across the file boundary.
  1860. unsigned Length = std::min(Line.size() + 1, Code.size() - Offset);
  1861. llvm::Error Err =
  1862. Result.add(tooling::Replacement(FileName, Offset, Length, ""));
  1863. if (Err) {
  1864. // Ignore the deletion on conflict.
  1865. llvm::errs() << "Failed to add header deletion replacement for "
  1866. << IncludeName << ": " << llvm::toString(std::move(Err))
  1867. << "\n";
  1868. }
  1869. }
  1870. }
  1871. Offset = NextLineOffset;
  1872. }
  1873. // Populate CategoryEndOfssets:
  1874. // - Ensure that CategoryEndOffset[Highest] is always populated.
  1875. // - If CategoryEndOffset[Priority] isn't set, use the next higher value that
  1876. // is set, up to CategoryEndOffset[Highest].
  1877. auto Highest = Priorities.begin();
  1878. if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
  1879. if (FirstIncludeOffset >= 0)
  1880. CategoryEndOffsets[*Highest] = FirstIncludeOffset;
  1881. else
  1882. CategoryEndOffsets[*Highest] = MinInsertOffset;
  1883. }
  1884. // By this point, CategoryEndOffset[Highest] is always set appropriately:
  1885. // - to an appropriate location before/after existing #includes, or
  1886. // - to right after the header guard, or
  1887. // - to the beginning of the file.
  1888. for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
  1889. if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
  1890. CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
  1891. bool NeedNewLineAtEnd = !Code.empty() && Code.back() != '\n';
  1892. for (const auto &R : HeaderInsertions) {
  1893. auto IncludeDirective = R.getReplacementText();
  1894. bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
  1895. assert(Matched && "Header insertion replacement must have replacement text "
  1896. "'#include ...'");
  1897. (void)Matched;
  1898. auto IncludeName = Matches[2];
  1899. if (ExistingIncludes.find(IncludeName) != ExistingIncludes.end()) {
  1900. DEBUG(llvm::dbgs() << "Skip adding existing include : " << IncludeName
  1901. << "\n");
  1902. continue;
  1903. }
  1904. int Category =
  1905. Categories.getIncludePriority(IncludeName, /*CheckMainHeader=*/true);
  1906. Offset = CategoryEndOffsets[Category];
  1907. std::string NewInclude = !IncludeDirective.endswith("\n")
  1908. ? (IncludeDirective + "\n").str()
  1909. : IncludeDirective.str();
  1910. // When inserting headers at end of the code, also append '\n' to the code
  1911. // if it does not end with '\n'.
  1912. if (NeedNewLineAtEnd && Offset == Code.size()) {
  1913. NewInclude = "\n" + NewInclude;
  1914. NeedNewLineAtEnd = false;
  1915. }
  1916. auto NewReplace = tooling::Replacement(FileName, Offset, 0, NewInclude);
  1917. auto Err = Result.add(NewReplace);
  1918. if (Err) {
  1919. llvm::consumeError(std::move(Err));
  1920. unsigned NewOffset = Result.getShiftedCodePosition(Offset);
  1921. NewReplace = tooling::Replacement(FileName, NewOffset, 0, NewInclude);
  1922. Result = Result.merge(tooling::Replacements(NewReplace));
  1923. }
  1924. }
  1925. return Result;
  1926. }
  1927. } // anonymous namespace
  1928. llvm::Expected<tooling::Replacements>
  1929. cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
  1930. const FormatStyle &Style) {
  1931. // We need to use lambda function here since there are two versions of
  1932. // `cleanup`.
  1933. auto Cleanup = [](const FormatStyle &Style, StringRef Code,
  1934. std::vector<tooling::Range> Ranges,
  1935. StringRef FileName) -> tooling::Replacements {
  1936. return cleanup(Style, Code, Ranges, FileName);
  1937. };
  1938. // Make header insertion replacements insert new headers into correct blocks.
  1939. tooling::Replacements NewReplaces =
  1940. fixCppIncludeInsertions(Code, Replaces, Style);
  1941. return processReplacements(Cleanup, Code, NewReplaces, Style);
  1942. }
  1943. namespace internal {
  1944. std::pair<tooling::Replacements, unsigned>
  1945. reformat(const FormatStyle &Style, StringRef Code,
  1946. ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
  1947. unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
  1948. FormattingAttemptStatus *Status) {
  1949. FormatStyle Expanded = expandPresets(Style);
  1950. if (Expanded.DisableFormat)
  1951. return {tooling::Replacements(), 0};
  1952. if (isLikelyXml(Code))
  1953. return {tooling::Replacements(), 0};
  1954. if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
  1955. return {tooling::Replacements(), 0};
  1956. typedef std::function<std::pair<tooling::Replacements, unsigned>(
  1957. const Environment &)>
  1958. AnalyzerPass;
  1959. SmallVector<AnalyzerPass, 4> Passes;
  1960. if (Style.Language == FormatStyle::LK_Cpp) {
  1961. if (Style.FixNamespaceComments)
  1962. Passes.emplace_back([&](const Environment &Env) {
  1963. return NamespaceEndCommentsFixer(Env, Expanded).process();
  1964. });
  1965. if (Style.SortUsingDeclarations)
  1966. Passes.emplace_back([&](const Environment &Env) {
  1967. return UsingDeclarationsSorter(Env, Expanded).process();
  1968. });
  1969. }
  1970. if (Style.Language == FormatStyle::LK_JavaScript &&
  1971. Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
  1972. Passes.emplace_back([&](const Environment &Env) {
  1973. return JavaScriptRequoter(Env, Expanded).process();
  1974. });
  1975. Passes.emplace_back([&](const Environment &Env) {
  1976. return Formatter(Env, Expanded, Status).process();
  1977. });
  1978. std::unique_ptr<Environment> Env = Environment::CreateVirtualEnvironment(
  1979. Code, FileName, Ranges, FirstStartColumn, NextStartColumn,
  1980. LastStartColumn);
  1981. llvm::Optional<std::string> CurrentCode = None;
  1982. tooling::Replacements Fixes;
  1983. unsigned Penalty = 0;
  1984. for (size_t I = 0, E = Passes.size(); I < E; ++I) {
  1985. std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
  1986. auto NewCode = applyAllReplacements(
  1987. CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
  1988. if (NewCode) {
  1989. Fixes = Fixes.merge(PassFixes.first);
  1990. Penalty += PassFixes.second;
  1991. if (I + 1 < E) {
  1992. CurrentCode = std::move(*NewCode);
  1993. Env = Environment::CreateVirtualEnvironment(
  1994. *CurrentCode, FileName,
  1995. tooling::calculateRangesAfterReplacements(Fixes, Ranges),
  1996. FirstStartColumn, NextStartColumn, LastStartColumn);
  1997. }
  1998. }
  1999. }
  2000. return {Fixes, Penalty};
  2001. }
  2002. } // namespace internal
  2003. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  2004. ArrayRef<tooling::Range> Ranges,
  2005. StringRef FileName,
  2006. FormattingAttemptStatus *Status) {
  2007. return internal::reformat(Style, Code, Ranges,
  2008. /*FirstStartColumn=*/0,
  2009. /*NextStartColumn=*/0,
  2010. /*LastStartColumn=*/0, FileName, Status)
  2011. .first;
  2012. }
  2013. tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
  2014. ArrayRef<tooling::Range> Ranges,
  2015. StringRef FileName) {
  2016. // cleanups only apply to C++ (they mostly concern ctor commas etc.)
  2017. if (Style.Language != FormatStyle::LK_Cpp)
  2018. return tooling::Replacements();
  2019. std::unique_ptr<Environment> Env =
  2020. Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  2021. Cleaner Clean(*Env, Style);
  2022. return Clean.process().first;
  2023. }
  2024. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  2025. ArrayRef<tooling::Range> Ranges,
  2026. StringRef FileName, bool *IncompleteFormat) {
  2027. FormattingAttemptStatus Status;
  2028. auto Result = reformat(Style, Code, Ranges, FileName, &Status);
  2029. if (!Status.FormatComplete)
  2030. *IncompleteFormat = true;
  2031. return Result;
  2032. }
  2033. tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
  2034. StringRef Code,
  2035. ArrayRef<tooling::Range> Ranges,
  2036. StringRef FileName) {
  2037. std::unique_ptr<Environment> Env =
  2038. Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  2039. NamespaceEndCommentsFixer Fix(*Env, Style);
  2040. return Fix.process().first;
  2041. }
  2042. tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
  2043. StringRef Code,
  2044. ArrayRef<tooling::Range> Ranges,
  2045. StringRef FileName) {
  2046. std::unique_ptr<Environment> Env =
  2047. Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  2048. UsingDeclarationsSorter Sorter(*Env, Style);
  2049. return Sorter.process().first;
  2050. }
  2051. LangOptions getFormattingLangOpts(const FormatStyle &Style) {
  2052. LangOptions LangOpts;
  2053. LangOpts.CPlusPlus = 1;
  2054. LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  2055. LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  2056. LangOpts.CPlusPlus17 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  2057. LangOpts.CPlusPlus2a = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  2058. LangOpts.LineComment = 1;
  2059. bool AlternativeOperators = Style.isCpp();
  2060. LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
  2061. LangOpts.Bool = 1;
  2062. LangOpts.ObjC1 = 1;
  2063. LangOpts.ObjC2 = 1;
  2064. LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
  2065. LangOpts.DeclSpecKeyword = 1; // To get __declspec.
  2066. return LangOpts;
  2067. }
  2068. const char *StyleOptionHelpDescription =
  2069. "Coding style, currently supports:\n"
  2070. " LLVM, Google, Chromium, Mozilla, WebKit.\n"
  2071. "Use -style=file to load style configuration from\n"
  2072. ".clang-format file located in one of the parent\n"
  2073. "directories of the source file (or current\n"
  2074. "directory for stdin).\n"
  2075. "Use -style=\"{key: value, ...}\" to set specific\n"
  2076. "parameters, e.g.:\n"
  2077. " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
  2078. static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
  2079. if (FileName.endswith(".java"))
  2080. return FormatStyle::LK_Java;
  2081. if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
  2082. return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
  2083. if (FileName.endswith(".m") || FileName.endswith(".mm"))
  2084. return FormatStyle::LK_ObjC;
  2085. if (FileName.endswith_lower(".proto") ||
  2086. FileName.endswith_lower(".protodevel"))
  2087. return FormatStyle::LK_Proto;
  2088. if (FileName.endswith_lower(".textpb") ||
  2089. FileName.endswith_lower(".pb.txt") ||
  2090. FileName.endswith_lower(".textproto") ||
  2091. FileName.endswith_lower(".asciipb"))
  2092. return FormatStyle::LK_TextProto;
  2093. if (FileName.endswith_lower(".td"))
  2094. return FormatStyle::LK_TableGen;
  2095. return FormatStyle::LK_Cpp;
  2096. }
  2097. llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
  2098. StringRef FallbackStyleName,
  2099. StringRef Code, vfs::FileSystem *FS) {
  2100. if (!FS) {
  2101. FS = vfs::getRealFileSystem().get();
  2102. }
  2103. FormatStyle Style = getLLVMStyle();
  2104. Style.Language = getLanguageByFileName(FileName);
  2105. if (Style.Language == FormatStyle::LK_Cpp && FileName.endswith(".h")) {
  2106. std::unique_ptr<Environment> Env =
  2107. Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
  2108. ObjCHeaderStyleGuesser Guesser(*Env, Style);
  2109. Guesser.process();
  2110. if (Guesser.isObjC()) {
  2111. Style.Language = FormatStyle::LK_ObjC;
  2112. }
  2113. }
  2114. FormatStyle FallbackStyle = getNoStyle();
  2115. if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
  2116. return make_string_error("Invalid fallback style \"" + FallbackStyleName);
  2117. if (StyleName.startswith("{")) {
  2118. // Parse YAML/JSON style from the command line.
  2119. if (std::error_code ec = parseConfiguration(StyleName, &Style))
  2120. return make_string_error("Error parsing -style: " + ec.message());
  2121. return Style;
  2122. }
  2123. if (!StyleName.equals_lower("file")) {
  2124. if (!getPredefinedStyle(StyleName, Style.Language, &Style))
  2125. return make_string_error("Invalid value for -style");
  2126. return Style;
  2127. }
  2128. // Look for .clang-format/_clang-format file in the file's parent directories.
  2129. SmallString<128> UnsuitableConfigFiles;
  2130. SmallString<128> Path(FileName);
  2131. if (std::error_code EC = FS->makeAbsolute(Path))
  2132. return make_string_error(EC.message());
  2133. for (StringRef Directory = Path; !Directory.empty();
  2134. Directory = llvm::sys::path::parent_path(Directory)) {
  2135. auto Status = FS->status(Directory);
  2136. if (!Status ||
  2137. Status->getType() != llvm::sys::fs::file_type::directory_file) {
  2138. continue;
  2139. }
  2140. SmallString<128> ConfigFile(Directory);
  2141. llvm::sys::path::append(ConfigFile, ".clang-format");
  2142. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  2143. Status = FS->status(ConfigFile.str());
  2144. bool FoundConfigFile =
  2145. Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
  2146. if (!FoundConfigFile) {
  2147. // Try _clang-format too, since dotfiles are not commonly used on Windows.
  2148. ConfigFile = Directory;
  2149. llvm::sys::path::append(ConfigFile, "_clang-format");
  2150. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  2151. Status = FS->status(ConfigFile.str());
  2152. FoundConfigFile = Status && (Status->getType() ==
  2153. llvm::sys::fs::file_type::regular_file);
  2154. }
  2155. if (FoundConfigFile) {
  2156. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  2157. FS->getBufferForFile(ConfigFile.str());
  2158. if (std::error_code EC = Text.getError())
  2159. return make_string_error(EC.message());
  2160. if (std::error_code ec =
  2161. parseConfiguration(Text.get()->getBuffer(), &Style)) {
  2162. if (ec == ParseError::Unsuitable) {
  2163. if (!UnsuitableConfigFiles.empty())
  2164. UnsuitableConfigFiles.append(", ");
  2165. UnsuitableConfigFiles.append(ConfigFile);
  2166. continue;
  2167. }
  2168. return make_string_error("Error reading " + ConfigFile + ": " +
  2169. ec.message());
  2170. }
  2171. DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
  2172. return Style;
  2173. }
  2174. }
  2175. if (!UnsuitableConfigFiles.empty())
  2176. return make_string_error("Configuration file(s) do(es) not support " +
  2177. getLanguageName(Style.Language) + ": " +
  2178. UnsuitableConfigFiles);
  2179. return FallbackStyle;
  2180. }
  2181. } // namespace format
  2182. } // namespace clang