Format.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870
  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 LLVM_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 = "@(export|requirecss|return|see|visibility) ";
  575. GoogleStyle.MaxEmptyLinesToKeep = 3;
  576. GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
  577. GoogleStyle.SpacesInContainerLiterals = false;
  578. GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
  579. GoogleStyle.JavaScriptWrapImports = false;
  580. } else if (Language == FormatStyle::LK_Proto) {
  581. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
  582. GoogleStyle.SpacesInContainerLiterals = false;
  583. }
  584. return GoogleStyle;
  585. }
  586. FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
  587. FormatStyle ChromiumStyle = getGoogleStyle(Language);
  588. if (Language == FormatStyle::LK_Java) {
  589. ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
  590. ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
  591. ChromiumStyle.ContinuationIndentWidth = 8;
  592. ChromiumStyle.IndentWidth = 4;
  593. } else {
  594. ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  595. ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  596. ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
  597. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  598. ChromiumStyle.BinPackParameters = false;
  599. ChromiumStyle.DerivePointerAlignment = false;
  600. }
  601. ChromiumStyle.SortIncludes = false;
  602. return ChromiumStyle;
  603. }
  604. FormatStyle getMozillaStyle() {
  605. FormatStyle MozillaStyle = getLLVMStyle();
  606. MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  607. MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  608. MozillaStyle.AlwaysBreakAfterReturnType =
  609. FormatStyle::RTBS_TopLevelDefinitions;
  610. MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
  611. FormatStyle::DRTBS_TopLevel;
  612. MozillaStyle.AlwaysBreakTemplateDeclarations = true;
  613. MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
  614. MozillaStyle.BreakConstructorInitializersBeforeComma = true;
  615. MozillaStyle.ConstructorInitializerIndentWidth = 2;
  616. MozillaStyle.ContinuationIndentWidth = 2;
  617. MozillaStyle.Cpp11BracedListStyle = false;
  618. MozillaStyle.IndentCaseLabels = true;
  619. MozillaStyle.ObjCSpaceAfterProperty = true;
  620. MozillaStyle.ObjCSpaceBeforeProtocolList = false;
  621. MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  622. MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
  623. MozillaStyle.SpaceAfterTemplateKeyword = false;
  624. return MozillaStyle;
  625. }
  626. FormatStyle getWebKitStyle() {
  627. FormatStyle Style = getLLVMStyle();
  628. Style.AccessModifierOffset = -4;
  629. Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  630. Style.AlignOperands = false;
  631. Style.AlignTrailingComments = false;
  632. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  633. Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
  634. Style.BreakConstructorInitializersBeforeComma = true;
  635. Style.Cpp11BracedListStyle = false;
  636. Style.ColumnLimit = 0;
  637. Style.IndentWidth = 4;
  638. Style.NamespaceIndentation = FormatStyle::NI_Inner;
  639. Style.ObjCBlockIndentWidth = 4;
  640. Style.ObjCSpaceAfterProperty = true;
  641. Style.PointerAlignment = FormatStyle::PAS_Left;
  642. return Style;
  643. }
  644. FormatStyle getGNUStyle() {
  645. FormatStyle Style = getLLVMStyle();
  646. Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
  647. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  648. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  649. Style.BreakBeforeBraces = FormatStyle::BS_GNU;
  650. Style.BreakBeforeTernaryOperators = true;
  651. Style.Cpp11BracedListStyle = false;
  652. Style.ColumnLimit = 79;
  653. Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
  654. Style.Standard = FormatStyle::LS_Cpp03;
  655. return Style;
  656. }
  657. FormatStyle getNoStyle() {
  658. FormatStyle NoStyle = getLLVMStyle();
  659. NoStyle.DisableFormat = true;
  660. NoStyle.SortIncludes = false;
  661. return NoStyle;
  662. }
  663. bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
  664. FormatStyle *Style) {
  665. if (Name.equals_lower("llvm")) {
  666. *Style = getLLVMStyle();
  667. } else if (Name.equals_lower("chromium")) {
  668. *Style = getChromiumStyle(Language);
  669. } else if (Name.equals_lower("mozilla")) {
  670. *Style = getMozillaStyle();
  671. } else if (Name.equals_lower("google")) {
  672. *Style = getGoogleStyle(Language);
  673. } else if (Name.equals_lower("webkit")) {
  674. *Style = getWebKitStyle();
  675. } else if (Name.equals_lower("gnu")) {
  676. *Style = getGNUStyle();
  677. } else if (Name.equals_lower("none")) {
  678. *Style = getNoStyle();
  679. } else {
  680. return false;
  681. }
  682. Style->Language = Language;
  683. return true;
  684. }
  685. std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
  686. assert(Style);
  687. FormatStyle::LanguageKind Language = Style->Language;
  688. assert(Language != FormatStyle::LK_None);
  689. if (Text.trim().empty())
  690. return make_error_code(ParseError::Error);
  691. std::vector<FormatStyle> Styles;
  692. llvm::yaml::Input Input(Text);
  693. // DocumentListTraits<vector<FormatStyle>> uses the context to get default
  694. // values for the fields, keys for which are missing from the configuration.
  695. // Mapping also uses the context to get the language to find the correct
  696. // base style.
  697. Input.setContext(Style);
  698. Input >> Styles;
  699. if (Input.error())
  700. return Input.error();
  701. for (unsigned i = 0; i < Styles.size(); ++i) {
  702. // Ensures that only the first configuration can skip the Language option.
  703. if (Styles[i].Language == FormatStyle::LK_None && i != 0)
  704. return make_error_code(ParseError::Error);
  705. // Ensure that each language is configured at most once.
  706. for (unsigned j = 0; j < i; ++j) {
  707. if (Styles[i].Language == Styles[j].Language) {
  708. DEBUG(llvm::dbgs()
  709. << "Duplicate languages in the config file on positions " << j
  710. << " and " << i << "\n");
  711. return make_error_code(ParseError::Error);
  712. }
  713. }
  714. }
  715. // Look for a suitable configuration starting from the end, so we can
  716. // find the configuration for the specific language first, and the default
  717. // configuration (which can only be at slot 0) after it.
  718. for (int i = Styles.size() - 1; i >= 0; --i) {
  719. if (Styles[i].Language == Language ||
  720. Styles[i].Language == FormatStyle::LK_None) {
  721. *Style = Styles[i];
  722. Style->Language = Language;
  723. return make_error_code(ParseError::Success);
  724. }
  725. }
  726. return make_error_code(ParseError::Unsuitable);
  727. }
  728. std::string configurationAsText(const FormatStyle &Style) {
  729. std::string Text;
  730. llvm::raw_string_ostream Stream(Text);
  731. llvm::yaml::Output Output(Stream);
  732. // We use the same mapping method for input and output, so we need a non-const
  733. // reference here.
  734. FormatStyle NonConstStyle = expandPresets(Style);
  735. Output << NonConstStyle;
  736. return Stream.str();
  737. }
  738. namespace {
  739. class JavaScriptRequoter : public TokenAnalyzer {
  740. public:
  741. JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
  742. : TokenAnalyzer(Env, Style) {}
  743. tooling::Replacements
  744. analyze(TokenAnnotator &Annotator,
  745. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  746. FormatTokenLexer &Tokens) override {
  747. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  748. AnnotatedLines.end());
  749. tooling::Replacements Result;
  750. requoteJSStringLiteral(AnnotatedLines, Result);
  751. return Result;
  752. }
  753. private:
  754. // Replaces double/single-quoted string literal as appropriate, re-escaping
  755. // the contents in the process.
  756. void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
  757. tooling::Replacements &Result) {
  758. for (AnnotatedLine *Line : Lines) {
  759. requoteJSStringLiteral(Line->Children, Result);
  760. if (!Line->Affected)
  761. continue;
  762. for (FormatToken *FormatTok = Line->First; FormatTok;
  763. FormatTok = FormatTok->Next) {
  764. StringRef Input = FormatTok->TokenText;
  765. if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
  766. // NB: testing for not starting with a double quote to avoid
  767. // breaking `template strings`.
  768. (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
  769. !Input.startswith("\"")) ||
  770. (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
  771. !Input.startswith("\'")))
  772. continue;
  773. // Change start and end quote.
  774. bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
  775. SourceLocation Start = FormatTok->Tok.getLocation();
  776. auto Replace = [&](SourceLocation Start, unsigned Length,
  777. StringRef ReplacementText) {
  778. auto Err = Result.add(tooling::Replacement(
  779. Env.getSourceManager(), Start, Length, ReplacementText));
  780. // FIXME: handle error. For now, print error message and skip the
  781. // replacement for release version.
  782. if (Err)
  783. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  784. assert(!Err);
  785. };
  786. Replace(Start, 1, IsSingle ? "'" : "\"");
  787. Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
  788. IsSingle ? "'" : "\"");
  789. // Escape internal quotes.
  790. bool Escaped = false;
  791. for (size_t i = 1; i < Input.size() - 1; i++) {
  792. switch (Input[i]) {
  793. case '\\':
  794. if (!Escaped && i + 1 < Input.size() &&
  795. ((IsSingle && Input[i + 1] == '"') ||
  796. (!IsSingle && Input[i + 1] == '\''))) {
  797. // Remove this \, it's escaping a " or ' that no longer needs
  798. // escaping
  799. Replace(Start.getLocWithOffset(i), 1, "");
  800. continue;
  801. }
  802. Escaped = !Escaped;
  803. break;
  804. case '\"':
  805. case '\'':
  806. if (!Escaped && IsSingle == (Input[i] == '\'')) {
  807. // Escape the quote.
  808. Replace(Start.getLocWithOffset(i), 0, "\\");
  809. }
  810. Escaped = false;
  811. break;
  812. default:
  813. Escaped = false;
  814. break;
  815. }
  816. }
  817. }
  818. }
  819. }
  820. };
  821. class Formatter : public TokenAnalyzer {
  822. public:
  823. Formatter(const Environment &Env, const FormatStyle &Style,
  824. bool *IncompleteFormat)
  825. : TokenAnalyzer(Env, Style), IncompleteFormat(IncompleteFormat) {}
  826. tooling::Replacements
  827. analyze(TokenAnnotator &Annotator,
  828. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  829. FormatTokenLexer &Tokens) override {
  830. tooling::Replacements Result;
  831. deriveLocalStyle(AnnotatedLines);
  832. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  833. AnnotatedLines.end());
  834. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  835. Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
  836. }
  837. Annotator.setCommentLineLevels(AnnotatedLines);
  838. WhitespaceManager Whitespaces(
  839. Env.getSourceManager(), Style,
  840. inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
  841. ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
  842. Env.getSourceManager(), Whitespaces, Encoding,
  843. BinPackInconclusiveFunctions);
  844. UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
  845. IncompleteFormat)
  846. .format(AnnotatedLines);
  847. for (const auto &R : Whitespaces.generateReplacements())
  848. if (Result.add(R))
  849. return Result;
  850. return Result;
  851. }
  852. private:
  853. static bool inputUsesCRLF(StringRef Text) {
  854. return Text.count('\r') * 2 > Text.count('\n');
  855. }
  856. bool
  857. hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  858. for (const AnnotatedLine *Line : Lines) {
  859. if (hasCpp03IncompatibleFormat(Line->Children))
  860. return true;
  861. for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
  862. if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
  863. if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
  864. return true;
  865. if (Tok->is(TT_TemplateCloser) &&
  866. Tok->Previous->is(TT_TemplateCloser))
  867. return true;
  868. }
  869. }
  870. }
  871. return false;
  872. }
  873. int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  874. int AlignmentDiff = 0;
  875. for (const AnnotatedLine *Line : Lines) {
  876. AlignmentDiff += countVariableAlignments(Line->Children);
  877. for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
  878. if (!Tok->is(TT_PointerOrReference))
  879. continue;
  880. bool SpaceBefore =
  881. Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
  882. bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
  883. Tok->Next->WhitespaceRange.getEnd();
  884. if (SpaceBefore && !SpaceAfter)
  885. ++AlignmentDiff;
  886. if (!SpaceBefore && SpaceAfter)
  887. --AlignmentDiff;
  888. }
  889. }
  890. return AlignmentDiff;
  891. }
  892. void
  893. deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  894. bool HasBinPackedFunction = false;
  895. bool HasOnePerLineFunction = false;
  896. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  897. if (!AnnotatedLines[i]->First->Next)
  898. continue;
  899. FormatToken *Tok = AnnotatedLines[i]->First->Next;
  900. while (Tok->Next) {
  901. if (Tok->PackingKind == PPK_BinPacked)
  902. HasBinPackedFunction = true;
  903. if (Tok->PackingKind == PPK_OnePerLine)
  904. HasOnePerLineFunction = true;
  905. Tok = Tok->Next;
  906. }
  907. }
  908. if (Style.DerivePointerAlignment)
  909. Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
  910. ? FormatStyle::PAS_Left
  911. : FormatStyle::PAS_Right;
  912. if (Style.Standard == FormatStyle::LS_Auto)
  913. Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
  914. ? FormatStyle::LS_Cpp11
  915. : FormatStyle::LS_Cpp03;
  916. BinPackInconclusiveFunctions =
  917. HasBinPackedFunction || !HasOnePerLineFunction;
  918. }
  919. bool BinPackInconclusiveFunctions;
  920. bool *IncompleteFormat;
  921. };
  922. // This class clean up the erroneous/redundant code around the given ranges in
  923. // file.
  924. class Cleaner : public TokenAnalyzer {
  925. public:
  926. Cleaner(const Environment &Env, const FormatStyle &Style)
  927. : TokenAnalyzer(Env, Style),
  928. DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
  929. // FIXME: eliminate unused parameters.
  930. tooling::Replacements
  931. analyze(TokenAnnotator &Annotator,
  932. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  933. FormatTokenLexer &Tokens) override {
  934. // FIXME: in the current implementation the granularity of affected range
  935. // is an annotated line. However, this is not sufficient. Furthermore,
  936. // redundant code introduced by replacements does not necessarily
  937. // intercept with ranges of replacements that result in the redundancy.
  938. // To determine if some redundant code is actually introduced by
  939. // replacements(e.g. deletions), we need to come up with a more
  940. // sophisticated way of computing affected ranges.
  941. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  942. AnnotatedLines.end());
  943. checkEmptyNamespace(AnnotatedLines);
  944. for (auto &Line : AnnotatedLines) {
  945. if (Line->Affected) {
  946. cleanupRight(Line->First, tok::comma, tok::comma);
  947. cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
  948. cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
  949. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
  950. }
  951. }
  952. return generateFixes();
  953. }
  954. private:
  955. bool containsOnlyComments(const AnnotatedLine &Line) {
  956. for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
  957. if (Tok->isNot(tok::comment))
  958. return false;
  959. }
  960. return true;
  961. }
  962. // Iterate through all lines and remove any empty (nested) namespaces.
  963. void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  964. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  965. auto &Line = *AnnotatedLines[i];
  966. if (Line.startsWith(tok::kw_namespace) ||
  967. Line.startsWith(tok::kw_inline, tok::kw_namespace)) {
  968. checkEmptyNamespace(AnnotatedLines, i, i);
  969. }
  970. }
  971. for (auto Line : DeletedLines) {
  972. FormatToken *Tok = AnnotatedLines[Line]->First;
  973. while (Tok) {
  974. deleteToken(Tok);
  975. Tok = Tok->Next;
  976. }
  977. }
  978. }
  979. // The function checks if the namespace, which starts from \p CurrentLine, and
  980. // its nested namespaces are empty and delete them if they are empty. It also
  981. // sets \p NewLine to the last line checked.
  982. // Returns true if the current namespace is empty.
  983. bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  984. unsigned CurrentLine, unsigned &NewLine) {
  985. unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
  986. if (Style.BraceWrapping.AfterNamespace) {
  987. // If the left brace is in a new line, we should consume it first so that
  988. // it does not make the namespace non-empty.
  989. // FIXME: error handling if there is no left brace.
  990. if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
  991. NewLine = CurrentLine;
  992. return false;
  993. }
  994. } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
  995. return false;
  996. }
  997. while (++CurrentLine < End) {
  998. if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
  999. break;
  1000. if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) ||
  1001. AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline,
  1002. tok::kw_namespace)) {
  1003. if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine))
  1004. return false;
  1005. CurrentLine = NewLine;
  1006. continue;
  1007. }
  1008. if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
  1009. continue;
  1010. // If there is anything other than comments or nested namespaces in the
  1011. // current namespace, the namespace cannot be empty.
  1012. NewLine = CurrentLine;
  1013. return false;
  1014. }
  1015. NewLine = CurrentLine;
  1016. if (CurrentLine >= End)
  1017. return false;
  1018. // Check if the empty namespace is actually affected by changed ranges.
  1019. if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
  1020. AnnotatedLines[InitLine]->First->Tok.getLocation(),
  1021. AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
  1022. return false;
  1023. for (unsigned i = InitLine; i <= CurrentLine; ++i) {
  1024. DeletedLines.insert(i);
  1025. }
  1026. return true;
  1027. }
  1028. // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
  1029. // of the token in the pair if the left token has \p LK token kind and the
  1030. // right token has \p RK token kind. If \p DeleteLeft is true, the left token
  1031. // is deleted on match; otherwise, the right token is deleted.
  1032. template <typename LeftKind, typename RightKind>
  1033. void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
  1034. bool DeleteLeft) {
  1035. auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
  1036. for (auto *Res = Tok.Next; Res; Res = Res->Next)
  1037. if (!Res->is(tok::comment) &&
  1038. DeletedTokens.find(Res) == DeletedTokens.end())
  1039. return Res;
  1040. return nullptr;
  1041. };
  1042. for (auto *Left = Start; Left;) {
  1043. auto *Right = NextNotDeleted(*Left);
  1044. if (!Right)
  1045. break;
  1046. if (Left->is(LK) && Right->is(RK)) {
  1047. deleteToken(DeleteLeft ? Left : Right);
  1048. for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
  1049. deleteToken(Tok);
  1050. // If the right token is deleted, we should keep the left token
  1051. // unchanged and pair it with the new right token.
  1052. if (!DeleteLeft)
  1053. continue;
  1054. }
  1055. Left = Right;
  1056. }
  1057. }
  1058. template <typename LeftKind, typename RightKind>
  1059. void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
  1060. cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
  1061. }
  1062. template <typename LeftKind, typename RightKind>
  1063. void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
  1064. cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
  1065. }
  1066. // Delete the given token.
  1067. inline void deleteToken(FormatToken *Tok) {
  1068. if (Tok)
  1069. DeletedTokens.insert(Tok);
  1070. }
  1071. tooling::Replacements generateFixes() {
  1072. tooling::Replacements Fixes;
  1073. std::vector<FormatToken *> Tokens;
  1074. std::copy(DeletedTokens.begin(), DeletedTokens.end(),
  1075. std::back_inserter(Tokens));
  1076. // Merge multiple continuous token deletions into one big deletion so that
  1077. // the number of replacements can be reduced. This makes computing affected
  1078. // ranges more efficient when we run reformat on the changed code.
  1079. unsigned Idx = 0;
  1080. while (Idx < Tokens.size()) {
  1081. unsigned St = Idx, End = Idx;
  1082. while ((End + 1) < Tokens.size() &&
  1083. Tokens[End]->Next == Tokens[End + 1]) {
  1084. End++;
  1085. }
  1086. auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
  1087. Tokens[End]->Tok.getEndLoc());
  1088. auto Err =
  1089. Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
  1090. // FIXME: better error handling. for now just print error message and skip
  1091. // for the release version.
  1092. if (Err)
  1093. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1094. assert(!Err && "Fixes must not conflict!");
  1095. Idx = End + 1;
  1096. }
  1097. return Fixes;
  1098. }
  1099. // Class for less-than inequality comparason for the set `RedundantTokens`.
  1100. // We store tokens in the order they appear in the translation unit so that
  1101. // we do not need to sort them in `generateFixes()`.
  1102. struct FormatTokenLess {
  1103. FormatTokenLess(const SourceManager &SM) : SM(SM) {}
  1104. bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
  1105. return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
  1106. RHS->Tok.getLocation());
  1107. }
  1108. const SourceManager &SM;
  1109. };
  1110. // Tokens to be deleted.
  1111. std::set<FormatToken *, FormatTokenLess> DeletedTokens;
  1112. // The line numbers of lines to be deleted.
  1113. std::set<unsigned> DeletedLines;
  1114. };
  1115. struct IncludeDirective {
  1116. StringRef Filename;
  1117. StringRef Text;
  1118. unsigned Offset;
  1119. int Category;
  1120. };
  1121. } // end anonymous namespace
  1122. // Determines whether 'Ranges' intersects with ('Start', 'End').
  1123. static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
  1124. unsigned End) {
  1125. for (auto Range : Ranges) {
  1126. if (Range.getOffset() < End &&
  1127. Range.getOffset() + Range.getLength() > Start)
  1128. return true;
  1129. }
  1130. return false;
  1131. }
  1132. // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
  1133. // before sorting/deduplicating. Index is the index of the include under the
  1134. // cursor in the original set of includes. If this include has duplicates, it is
  1135. // the index of the first of the duplicates as the others are going to be
  1136. // removed. OffsetToEOL describes the cursor's position relative to the end of
  1137. // its current line.
  1138. // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
  1139. static std::pair<unsigned, unsigned>
  1140. FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
  1141. const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
  1142. unsigned CursorIndex = UINT_MAX;
  1143. unsigned OffsetToEOL = 0;
  1144. for (int i = 0, e = Includes.size(); i != e; ++i) {
  1145. unsigned Start = Includes[Indices[i]].Offset;
  1146. unsigned End = Start + Includes[Indices[i]].Text.size();
  1147. if (!(Cursor >= Start && Cursor < End))
  1148. continue;
  1149. CursorIndex = Indices[i];
  1150. OffsetToEOL = End - Cursor;
  1151. // Put the cursor on the only remaining #include among the duplicate
  1152. // #includes.
  1153. while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
  1154. CursorIndex = i;
  1155. break;
  1156. }
  1157. return std::make_pair(CursorIndex, OffsetToEOL);
  1158. }
  1159. // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
  1160. // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
  1161. // source order.
  1162. // #include directives with the same text will be deduplicated, and only the
  1163. // first #include in the duplicate #includes remains. If the `Cursor` is
  1164. // provided and put on a deleted #include, it will be moved to the remaining
  1165. // #include in the duplicate #includes.
  1166. static void sortCppIncludes(const FormatStyle &Style,
  1167. const SmallVectorImpl<IncludeDirective> &Includes,
  1168. ArrayRef<tooling::Range> Ranges, StringRef FileName,
  1169. tooling::Replacements &Replaces, unsigned *Cursor) {
  1170. unsigned IncludesBeginOffset = Includes.front().Offset;
  1171. unsigned IncludesEndOffset =
  1172. Includes.back().Offset + Includes.back().Text.size();
  1173. unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
  1174. if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
  1175. return;
  1176. SmallVector<unsigned, 16> Indices;
  1177. for (unsigned i = 0, e = Includes.size(); i != e; ++i)
  1178. Indices.push_back(i);
  1179. std::stable_sort(
  1180. Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
  1181. return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
  1182. std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
  1183. });
  1184. // The index of the include on which the cursor will be put after
  1185. // sorting/deduplicating.
  1186. unsigned CursorIndex;
  1187. // The offset from cursor to the end of line.
  1188. unsigned CursorToEOLOffset;
  1189. if (Cursor)
  1190. std::tie(CursorIndex, CursorToEOLOffset) =
  1191. FindCursorIndex(Includes, Indices, *Cursor);
  1192. // Deduplicate #includes.
  1193. Indices.erase(std::unique(Indices.begin(), Indices.end(),
  1194. [&](unsigned LHSI, unsigned RHSI) {
  1195. return Includes[LHSI].Text == Includes[RHSI].Text;
  1196. }),
  1197. Indices.end());
  1198. // If the #includes are out of order, we generate a single replacement fixing
  1199. // the entire block. Otherwise, no replacement is generated.
  1200. if (Indices.size() == Includes.size() &&
  1201. std::is_sorted(Indices.begin(), Indices.end()))
  1202. return;
  1203. std::string result;
  1204. for (unsigned Index : Indices) {
  1205. if (!result.empty())
  1206. result += "\n";
  1207. result += Includes[Index].Text;
  1208. if (Cursor && CursorIndex == Index)
  1209. *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
  1210. }
  1211. auto Err = Replaces.add(tooling::Replacement(
  1212. FileName, Includes.front().Offset, IncludesBlockSize, result));
  1213. // FIXME: better error handling. For now, just skip the replacement for the
  1214. // release version.
  1215. if (Err)
  1216. llvm::errs() << llvm::toString(std::move(Err)) << "\n";
  1217. assert(!Err);
  1218. }
  1219. namespace {
  1220. // This class manages priorities of #include categories and calculates
  1221. // priorities for headers.
  1222. class IncludeCategoryManager {
  1223. public:
  1224. IncludeCategoryManager(const FormatStyle &Style, StringRef FileName)
  1225. : Style(Style), FileName(FileName) {
  1226. FileStem = llvm::sys::path::stem(FileName);
  1227. for (const auto &Category : Style.IncludeCategories)
  1228. CategoryRegexs.emplace_back(Category.Regex);
  1229. IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
  1230. FileName.endswith(".cpp") || FileName.endswith(".c++") ||
  1231. FileName.endswith(".cxx") || FileName.endswith(".m") ||
  1232. FileName.endswith(".mm");
  1233. }
  1234. // Returns the priority of the category which \p IncludeName belongs to.
  1235. // If \p CheckMainHeader is true and \p IncludeName is a main header, returns
  1236. // 0. Otherwise, returns the priority of the matching category or INT_MAX.
  1237. int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) {
  1238. int Ret = INT_MAX;
  1239. for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
  1240. if (CategoryRegexs[i].match(IncludeName)) {
  1241. Ret = Style.IncludeCategories[i].Priority;
  1242. break;
  1243. }
  1244. if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
  1245. Ret = 0;
  1246. return Ret;
  1247. }
  1248. private:
  1249. bool isMainHeader(StringRef IncludeName) const {
  1250. if (!IncludeName.startswith("\""))
  1251. return false;
  1252. StringRef HeaderStem =
  1253. llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
  1254. if (FileStem.startswith(HeaderStem)) {
  1255. llvm::Regex MainIncludeRegex(
  1256. (HeaderStem + Style.IncludeIsMainRegex).str());
  1257. if (MainIncludeRegex.match(FileStem))
  1258. return true;
  1259. }
  1260. return false;
  1261. }
  1262. const FormatStyle &Style;
  1263. bool IsMainFile;
  1264. StringRef FileName;
  1265. StringRef FileStem;
  1266. SmallVector<llvm::Regex, 4> CategoryRegexs;
  1267. };
  1268. const char IncludeRegexPattern[] =
  1269. R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
  1270. } // anonymous namespace
  1271. tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
  1272. ArrayRef<tooling::Range> Ranges,
  1273. StringRef FileName,
  1274. tooling::Replacements &Replaces,
  1275. unsigned *Cursor) {
  1276. unsigned Prev = 0;
  1277. unsigned SearchFrom = 0;
  1278. llvm::Regex IncludeRegex(IncludeRegexPattern);
  1279. SmallVector<StringRef, 4> Matches;
  1280. SmallVector<IncludeDirective, 16> IncludesInBlock;
  1281. // In compiled files, consider the first #include to be the main #include of
  1282. // the file if it is not a system #include. This ensures that the header
  1283. // doesn't have hidden dependencies
  1284. // (http://llvm.org/docs/CodingStandards.html#include-style).
  1285. //
  1286. // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
  1287. // cases where the first #include is unlikely to be the main header.
  1288. IncludeCategoryManager Categories(Style, FileName);
  1289. bool FirstIncludeBlock = true;
  1290. bool MainIncludeFound = false;
  1291. bool FormattingOff = false;
  1292. for (;;) {
  1293. auto Pos = Code.find('\n', SearchFrom);
  1294. StringRef Line =
  1295. Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
  1296. StringRef Trimmed = Line.trim();
  1297. if (Trimmed == "// clang-format off")
  1298. FormattingOff = true;
  1299. else if (Trimmed == "// clang-format on")
  1300. FormattingOff = false;
  1301. if (!FormattingOff && !Line.endswith("\\")) {
  1302. if (IncludeRegex.match(Line, &Matches)) {
  1303. StringRef IncludeName = Matches[2];
  1304. int Category = Categories.getIncludePriority(
  1305. IncludeName,
  1306. /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
  1307. if (Category == 0)
  1308. MainIncludeFound = true;
  1309. IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
  1310. } else if (!IncludesInBlock.empty()) {
  1311. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
  1312. Cursor);
  1313. IncludesInBlock.clear();
  1314. FirstIncludeBlock = false;
  1315. }
  1316. Prev = Pos + 1;
  1317. }
  1318. if (Pos == StringRef::npos || Pos + 1 == Code.size())
  1319. break;
  1320. SearchFrom = Pos + 1;
  1321. }
  1322. if (!IncludesInBlock.empty())
  1323. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
  1324. return Replaces;
  1325. }
  1326. tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
  1327. ArrayRef<tooling::Range> Ranges,
  1328. StringRef FileName, unsigned *Cursor) {
  1329. tooling::Replacements Replaces;
  1330. if (!Style.SortIncludes)
  1331. return Replaces;
  1332. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
  1333. return sortJavaScriptImports(Style, Code, Ranges, FileName);
  1334. sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
  1335. return Replaces;
  1336. }
  1337. template <typename T>
  1338. static llvm::Expected<tooling::Replacements>
  1339. processReplacements(T ProcessFunc, StringRef Code,
  1340. const tooling::Replacements &Replaces,
  1341. const FormatStyle &Style) {
  1342. if (Replaces.empty())
  1343. return tooling::Replacements();
  1344. auto NewCode = applyAllReplacements(Code, Replaces);
  1345. if (!NewCode)
  1346. return NewCode.takeError();
  1347. std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
  1348. StringRef FileName = Replaces.begin()->getFilePath();
  1349. tooling::Replacements FormatReplaces =
  1350. ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
  1351. return Replaces.merge(FormatReplaces);
  1352. }
  1353. llvm::Expected<tooling::Replacements>
  1354. formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
  1355. const FormatStyle &Style) {
  1356. // We need to use lambda function here since there are two versions of
  1357. // `sortIncludes`.
  1358. auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
  1359. std::vector<tooling::Range> Ranges,
  1360. StringRef FileName) -> tooling::Replacements {
  1361. return sortIncludes(Style, Code, Ranges, FileName);
  1362. };
  1363. auto SortedReplaces =
  1364. processReplacements(SortIncludes, Code, Replaces, Style);
  1365. if (!SortedReplaces)
  1366. return SortedReplaces.takeError();
  1367. // We need to use lambda function here since there are two versions of
  1368. // `reformat`.
  1369. auto Reformat = [](const FormatStyle &Style, StringRef Code,
  1370. std::vector<tooling::Range> Ranges,
  1371. StringRef FileName) -> tooling::Replacements {
  1372. return reformat(Style, Code, Ranges, FileName);
  1373. };
  1374. return processReplacements(Reformat, Code, *SortedReplaces, Style);
  1375. }
  1376. namespace {
  1377. inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
  1378. return Replace.getOffset() == UINT_MAX &&
  1379. llvm::Regex(IncludeRegexPattern).match(Replace.getReplacementText());
  1380. }
  1381. void skipComments(Lexer &Lex, Token &Tok) {
  1382. while (Tok.is(tok::comment))
  1383. if (Lex.LexFromRawLexer(Tok))
  1384. return;
  1385. }
  1386. // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
  1387. // \p Tok will be the token after this directive; otherwise, it can be any token
  1388. // after the given \p Tok (including \p Tok).
  1389. bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) {
  1390. bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
  1391. Tok.is(tok::raw_identifier) &&
  1392. Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
  1393. Tok.is(tok::raw_identifier);
  1394. if (Matched)
  1395. Lex.LexFromRawLexer(Tok);
  1396. return Matched;
  1397. }
  1398. unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
  1399. StringRef Code,
  1400. const FormatStyle &Style) {
  1401. std::unique_ptr<Environment> Env =
  1402. Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
  1403. const SourceManager &SourceMgr = Env->getSourceManager();
  1404. Lexer Lex(Env->getFileID(), SourceMgr.getBuffer(Env->getFileID()), SourceMgr,
  1405. getFormattingLangOpts(Style));
  1406. Token Tok;
  1407. // Get the first token.
  1408. Lex.LexFromRawLexer(Tok);
  1409. skipComments(Lex, Tok);
  1410. unsigned AfterComments = SourceMgr.getFileOffset(Tok.getLocation());
  1411. if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
  1412. skipComments(Lex, Tok);
  1413. if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
  1414. return SourceMgr.getFileOffset(Tok.getLocation());
  1415. }
  1416. return AfterComments;
  1417. }
  1418. // FIXME: we also need to insert a '\n' at the end of the code if we have an
  1419. // insertion with offset Code.size(), and there is no '\n' at the end of the
  1420. // code.
  1421. // FIXME: do not insert headers into conditional #include blocks, e.g. #includes
  1422. // surrounded by compile condition "#if...".
  1423. // FIXME: insert empty lines between newly created blocks.
  1424. tooling::Replacements
  1425. fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
  1426. const FormatStyle &Style) {
  1427. if (Style.Language != FormatStyle::LanguageKind::LK_Cpp)
  1428. return Replaces;
  1429. tooling::Replacements HeaderInsertions;
  1430. tooling::Replacements Result;
  1431. for (const auto &R : Replaces) {
  1432. if (isHeaderInsertion(R)) {
  1433. // Replacements from \p Replaces must be conflict-free already, so we can
  1434. // simply consume the error.
  1435. llvm::consumeError(HeaderInsertions.add(R));
  1436. } else if (R.getOffset() == UINT_MAX) {
  1437. llvm::errs() << "Insertions other than header #include insertion are "
  1438. "not supported! "
  1439. << R.getReplacementText() << "\n";
  1440. } else {
  1441. llvm::consumeError(Result.add(R));
  1442. }
  1443. }
  1444. if (HeaderInsertions.empty())
  1445. return Replaces;
  1446. llvm::Regex IncludeRegex(IncludeRegexPattern);
  1447. llvm::Regex DefineRegex(R"(^[\t\ ]*#[\t\ ]*define[\t\ ]*[^\\]*$)");
  1448. SmallVector<StringRef, 4> Matches;
  1449. StringRef FileName = Replaces.begin()->getFilePath();
  1450. IncludeCategoryManager Categories(Style, FileName);
  1451. // Record the offset of the end of the last include in each category.
  1452. std::map<int, int> CategoryEndOffsets;
  1453. // All possible priorities.
  1454. // Add 0 for main header and INT_MAX for headers that are not in any category.
  1455. std::set<int> Priorities = {0, INT_MAX};
  1456. for (const auto &Category : Style.IncludeCategories)
  1457. Priorities.insert(Category.Priority);
  1458. int FirstIncludeOffset = -1;
  1459. // All new headers should be inserted after this offset.
  1460. unsigned MinInsertOffset =
  1461. getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style);
  1462. StringRef TrimmedCode = Code.drop_front(MinInsertOffset);
  1463. SmallVector<StringRef, 32> Lines;
  1464. TrimmedCode.split(Lines, '\n');
  1465. unsigned Offset = MinInsertOffset;
  1466. unsigned NextLineOffset;
  1467. std::set<StringRef> ExistingIncludes;
  1468. for (auto Line : Lines) {
  1469. NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
  1470. if (IncludeRegex.match(Line, &Matches)) {
  1471. StringRef IncludeName = Matches[2];
  1472. ExistingIncludes.insert(IncludeName);
  1473. int Category = Categories.getIncludePriority(
  1474. IncludeName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
  1475. CategoryEndOffsets[Category] = NextLineOffset;
  1476. if (FirstIncludeOffset < 0)
  1477. FirstIncludeOffset = Offset;
  1478. }
  1479. Offset = NextLineOffset;
  1480. }
  1481. // Populate CategoryEndOfssets:
  1482. // - Ensure that CategoryEndOffset[Highest] is always populated.
  1483. // - If CategoryEndOffset[Priority] isn't set, use the next higher value that
  1484. // is set, up to CategoryEndOffset[Highest].
  1485. auto Highest = Priorities.begin();
  1486. if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
  1487. if (FirstIncludeOffset >= 0)
  1488. CategoryEndOffsets[*Highest] = FirstIncludeOffset;
  1489. else
  1490. CategoryEndOffsets[*Highest] = MinInsertOffset;
  1491. }
  1492. // By this point, CategoryEndOffset[Highest] is always set appropriately:
  1493. // - to an appropriate location before/after existing #includes, or
  1494. // - to right after the header guard, or
  1495. // - to the beginning of the file.
  1496. for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
  1497. if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
  1498. CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
  1499. for (const auto &R : HeaderInsertions) {
  1500. auto IncludeDirective = R.getReplacementText();
  1501. bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
  1502. assert(Matched && "Header insertion replacement must have replacement text "
  1503. "'#include ...'");
  1504. (void)Matched;
  1505. auto IncludeName = Matches[2];
  1506. if (ExistingIncludes.find(IncludeName) != ExistingIncludes.end()) {
  1507. DEBUG(llvm::dbgs() << "Skip adding existing include : " << IncludeName
  1508. << "\n");
  1509. continue;
  1510. }
  1511. int Category =
  1512. Categories.getIncludePriority(IncludeName, /*CheckMainHeader=*/true);
  1513. Offset = CategoryEndOffsets[Category];
  1514. std::string NewInclude = !IncludeDirective.endswith("\n")
  1515. ? (IncludeDirective + "\n").str()
  1516. : IncludeDirective.str();
  1517. auto NewReplace = tooling::Replacement(FileName, Offset, 0, NewInclude);
  1518. auto Err = Result.add(NewReplace);
  1519. if (Err) {
  1520. llvm::consumeError(std::move(Err));
  1521. Result = Result.merge(tooling::Replacements(NewReplace));
  1522. }
  1523. }
  1524. return Result;
  1525. }
  1526. } // anonymous namespace
  1527. llvm::Expected<tooling::Replacements>
  1528. cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
  1529. const FormatStyle &Style) {
  1530. // We need to use lambda function here since there are two versions of
  1531. // `cleanup`.
  1532. auto Cleanup = [](const FormatStyle &Style, StringRef Code,
  1533. std::vector<tooling::Range> Ranges,
  1534. StringRef FileName) -> tooling::Replacements {
  1535. return cleanup(Style, Code, Ranges, FileName);
  1536. };
  1537. // Make header insertion replacements insert new headers into correct blocks.
  1538. tooling::Replacements NewReplaces =
  1539. fixCppIncludeInsertions(Code, Replaces, Style);
  1540. return processReplacements(Cleanup, Code, NewReplaces, Style);
  1541. }
  1542. tooling::Replacements reformat(const FormatStyle &Style, SourceManager &SM,
  1543. FileID ID, ArrayRef<CharSourceRange> Ranges,
  1544. bool *IncompleteFormat) {
  1545. FormatStyle Expanded = expandPresets(Style);
  1546. if (Expanded.DisableFormat)
  1547. return tooling::Replacements();
  1548. Environment Env(SM, ID, Ranges);
  1549. Formatter Format(Env, Expanded, IncompleteFormat);
  1550. return Format.process();
  1551. }
  1552. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  1553. ArrayRef<tooling::Range> Ranges,
  1554. StringRef FileName, bool *IncompleteFormat) {
  1555. FormatStyle Expanded = expandPresets(Style);
  1556. if (Expanded.DisableFormat)
  1557. return tooling::Replacements();
  1558. auto Env = Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  1559. if (Style.Language == FormatStyle::LK_JavaScript &&
  1560. Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) {
  1561. JavaScriptRequoter Requoter(*Env, Expanded);
  1562. tooling::Replacements Requotes = Requoter.process();
  1563. if (!Requotes.empty()) {
  1564. auto NewCode = applyAllReplacements(Code, Requotes);
  1565. if (NewCode) {
  1566. auto NewEnv = Environment::CreateVirtualEnvironment(
  1567. *NewCode, FileName,
  1568. tooling::calculateRangesAfterReplacements(Requotes, Ranges));
  1569. Formatter Format(*NewEnv, Expanded, IncompleteFormat);
  1570. return Requotes.merge(Format.process());
  1571. }
  1572. }
  1573. }
  1574. Formatter Format(*Env, Expanded, IncompleteFormat);
  1575. return Format.process();
  1576. }
  1577. tooling::Replacements cleanup(const FormatStyle &Style, SourceManager &SM,
  1578. FileID ID, ArrayRef<CharSourceRange> Ranges) {
  1579. Environment Env(SM, ID, Ranges);
  1580. Cleaner Clean(Env, Style);
  1581. return Clean.process();
  1582. }
  1583. tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
  1584. ArrayRef<tooling::Range> Ranges,
  1585. StringRef FileName) {
  1586. std::unique_ptr<Environment> Env =
  1587. Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  1588. Cleaner Clean(*Env, Style);
  1589. return Clean.process();
  1590. }
  1591. LangOptions getFormattingLangOpts(const FormatStyle &Style) {
  1592. LangOptions LangOpts;
  1593. LangOpts.CPlusPlus = 1;
  1594. LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  1595. LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  1596. LangOpts.LineComment = 1;
  1597. bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
  1598. LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
  1599. LangOpts.Bool = 1;
  1600. LangOpts.ObjC1 = 1;
  1601. LangOpts.ObjC2 = 1;
  1602. LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
  1603. LangOpts.DeclSpecKeyword = 1; // To get __declspec.
  1604. return LangOpts;
  1605. }
  1606. const char *StyleOptionHelpDescription =
  1607. "Coding style, currently supports:\n"
  1608. " LLVM, Google, Chromium, Mozilla, WebKit.\n"
  1609. "Use -style=file to load style configuration from\n"
  1610. ".clang-format file located in one of the parent\n"
  1611. "directories of the source file (or current\n"
  1612. "directory for stdin).\n"
  1613. "Use -style=\"{key: value, ...}\" to set specific\n"
  1614. "parameters, e.g.:\n"
  1615. " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
  1616. static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
  1617. if (FileName.endswith(".java"))
  1618. return FormatStyle::LK_Java;
  1619. if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
  1620. return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
  1621. if (FileName.endswith_lower(".proto") ||
  1622. FileName.endswith_lower(".protodevel"))
  1623. return FormatStyle::LK_Proto;
  1624. if (FileName.endswith_lower(".td"))
  1625. return FormatStyle::LK_TableGen;
  1626. return FormatStyle::LK_Cpp;
  1627. }
  1628. FormatStyle getStyle(StringRef StyleName, StringRef FileName,
  1629. StringRef FallbackStyle, vfs::FileSystem *FS) {
  1630. if (!FS) {
  1631. FS = vfs::getRealFileSystem().get();
  1632. }
  1633. FormatStyle Style = getLLVMStyle();
  1634. Style.Language = getLanguageByFileName(FileName);
  1635. if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
  1636. llvm::errs() << "Invalid fallback style \"" << FallbackStyle
  1637. << "\" using LLVM style\n";
  1638. return Style;
  1639. }
  1640. if (StyleName.startswith("{")) {
  1641. // Parse YAML/JSON style from the command line.
  1642. if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
  1643. llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
  1644. << FallbackStyle << " style\n";
  1645. }
  1646. return Style;
  1647. }
  1648. if (!StyleName.equals_lower("file")) {
  1649. if (!getPredefinedStyle(StyleName, Style.Language, &Style))
  1650. llvm::errs() << "Invalid value for -style, using " << FallbackStyle
  1651. << " style\n";
  1652. return Style;
  1653. }
  1654. // Look for .clang-format/_clang-format file in the file's parent directories.
  1655. SmallString<128> UnsuitableConfigFiles;
  1656. SmallString<128> Path(FileName);
  1657. llvm::sys::fs::make_absolute(Path);
  1658. for (StringRef Directory = Path; !Directory.empty();
  1659. Directory = llvm::sys::path::parent_path(Directory)) {
  1660. auto Status = FS->status(Directory);
  1661. if (!Status ||
  1662. Status->getType() != llvm::sys::fs::file_type::directory_file) {
  1663. continue;
  1664. }
  1665. SmallString<128> ConfigFile(Directory);
  1666. llvm::sys::path::append(ConfigFile, ".clang-format");
  1667. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1668. Status = FS->status(ConfigFile.str());
  1669. bool IsFile =
  1670. Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
  1671. if (!IsFile) {
  1672. // Try _clang-format too, since dotfiles are not commonly used on Windows.
  1673. ConfigFile = Directory;
  1674. llvm::sys::path::append(ConfigFile, "_clang-format");
  1675. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1676. Status = FS->status(ConfigFile.str());
  1677. IsFile = Status &&
  1678. (Status->getType() == llvm::sys::fs::file_type::regular_file);
  1679. }
  1680. if (IsFile) {
  1681. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  1682. FS->getBufferForFile(ConfigFile.str());
  1683. if (std::error_code EC = Text.getError()) {
  1684. llvm::errs() << EC.message() << "\n";
  1685. break;
  1686. }
  1687. if (std::error_code ec =
  1688. parseConfiguration(Text.get()->getBuffer(), &Style)) {
  1689. if (ec == ParseError::Unsuitable) {
  1690. if (!UnsuitableConfigFiles.empty())
  1691. UnsuitableConfigFiles.append(", ");
  1692. UnsuitableConfigFiles.append(ConfigFile);
  1693. continue;
  1694. }
  1695. llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
  1696. << "\n";
  1697. break;
  1698. }
  1699. DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
  1700. return Style;
  1701. }
  1702. }
  1703. if (!UnsuitableConfigFiles.empty()) {
  1704. llvm::errs() << "Configuration file(s) do(es) not support "
  1705. << getLanguageName(Style.Language) << ": "
  1706. << UnsuitableConfigFiles << "\n";
  1707. }
  1708. return Style;
  1709. }
  1710. } // namespace format
  1711. } // namespace clang