Format.cpp 76 KB

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