Format.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  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("SpaceBeforeAssignmentOperators",
  316. Style.SpaceBeforeAssignmentOperators);
  317. IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
  318. IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
  319. IO.mapOptional("SpacesBeforeTrailingComments",
  320. Style.SpacesBeforeTrailingComments);
  321. IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
  322. IO.mapOptional("SpacesInContainerLiterals",
  323. Style.SpacesInContainerLiterals);
  324. IO.mapOptional("SpacesInCStyleCastParentheses",
  325. Style.SpacesInCStyleCastParentheses);
  326. IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
  327. IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
  328. IO.mapOptional("Standard", Style.Standard);
  329. IO.mapOptional("TabWidth", Style.TabWidth);
  330. IO.mapOptional("UseTab", Style.UseTab);
  331. }
  332. };
  333. template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
  334. static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
  335. IO.mapOptional("AfterClass", Wrapping.AfterClass);
  336. IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
  337. IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
  338. IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
  339. IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
  340. IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
  341. IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
  342. IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
  343. IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
  344. IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
  345. IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
  346. }
  347. };
  348. template <> struct MappingTraits<FormatStyle::IncludeCategory> {
  349. static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
  350. IO.mapOptional("Regex", Category.Regex);
  351. IO.mapOptional("Priority", Category.Priority);
  352. }
  353. };
  354. // Allows to read vector<FormatStyle> while keeping default values.
  355. // IO.getContext() should contain a pointer to the FormatStyle structure, that
  356. // will be used to get default values for missing keys.
  357. // If the first element has no Language specified, it will be treated as the
  358. // default one for the following elements.
  359. template <> struct DocumentListTraits<std::vector<FormatStyle>> {
  360. static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
  361. return Seq.size();
  362. }
  363. static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
  364. size_t Index) {
  365. if (Index >= Seq.size()) {
  366. assert(Index == Seq.size());
  367. FormatStyle Template;
  368. if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
  369. Template = Seq[0];
  370. } else {
  371. Template = *((const FormatStyle *)IO.getContext());
  372. Template.Language = FormatStyle::LK_None;
  373. }
  374. Seq.resize(Index + 1, Template);
  375. }
  376. return Seq[Index];
  377. }
  378. };
  379. } // namespace yaml
  380. } // namespace llvm
  381. namespace clang {
  382. namespace format {
  383. const std::error_category &getParseCategory() {
  384. static ParseErrorCategory C;
  385. return C;
  386. }
  387. std::error_code make_error_code(ParseError e) {
  388. return std::error_code(static_cast<int>(e), getParseCategory());
  389. }
  390. const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
  391. return "clang-format.parse_error";
  392. }
  393. std::string ParseErrorCategory::message(int EV) const {
  394. switch (static_cast<ParseError>(EV)) {
  395. case ParseError::Success:
  396. return "Success";
  397. case ParseError::Error:
  398. return "Invalid argument";
  399. case ParseError::Unsuitable:
  400. return "Unsuitable";
  401. }
  402. llvm_unreachable("unexpected parse error");
  403. }
  404. static FormatStyle expandPresets(const FormatStyle &Style) {
  405. if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
  406. return Style;
  407. FormatStyle Expanded = Style;
  408. Expanded.BraceWrapping = {false, false, false, false, false, false,
  409. false, false, false, false, false};
  410. switch (Style.BreakBeforeBraces) {
  411. case FormatStyle::BS_Linux:
  412. Expanded.BraceWrapping.AfterClass = true;
  413. Expanded.BraceWrapping.AfterFunction = true;
  414. Expanded.BraceWrapping.AfterNamespace = true;
  415. break;
  416. case FormatStyle::BS_Mozilla:
  417. Expanded.BraceWrapping.AfterClass = true;
  418. Expanded.BraceWrapping.AfterEnum = true;
  419. Expanded.BraceWrapping.AfterFunction = true;
  420. Expanded.BraceWrapping.AfterStruct = true;
  421. Expanded.BraceWrapping.AfterUnion = true;
  422. break;
  423. case FormatStyle::BS_Stroustrup:
  424. Expanded.BraceWrapping.AfterFunction = true;
  425. Expanded.BraceWrapping.BeforeCatch = true;
  426. Expanded.BraceWrapping.BeforeElse = true;
  427. break;
  428. case FormatStyle::BS_Allman:
  429. Expanded.BraceWrapping.AfterClass = true;
  430. Expanded.BraceWrapping.AfterControlStatement = true;
  431. Expanded.BraceWrapping.AfterEnum = true;
  432. Expanded.BraceWrapping.AfterFunction = true;
  433. Expanded.BraceWrapping.AfterNamespace = true;
  434. Expanded.BraceWrapping.AfterObjCDeclaration = true;
  435. Expanded.BraceWrapping.AfterStruct = true;
  436. Expanded.BraceWrapping.BeforeCatch = true;
  437. Expanded.BraceWrapping.BeforeElse = true;
  438. break;
  439. case FormatStyle::BS_GNU:
  440. Expanded.BraceWrapping = {true, true, true, true, true, true,
  441. true, true, true, true, true};
  442. break;
  443. case FormatStyle::BS_WebKit:
  444. Expanded.BraceWrapping.AfterFunction = true;
  445. break;
  446. default:
  447. break;
  448. }
  449. return Expanded;
  450. }
  451. FormatStyle getLLVMStyle() {
  452. FormatStyle LLVMStyle;
  453. LLVMStyle.Language = FormatStyle::LK_Cpp;
  454. LLVMStyle.AccessModifierOffset = -2;
  455. LLVMStyle.AlignEscapedNewlinesLeft = false;
  456. LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
  457. LLVMStyle.AlignOperands = true;
  458. LLVMStyle.AlignTrailingComments = true;
  459. LLVMStyle.AlignConsecutiveAssignments = false;
  460. LLVMStyle.AlignConsecutiveDeclarations = false;
  461. LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
  462. LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
  463. LLVMStyle.AllowShortBlocksOnASingleLine = false;
  464. LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
  465. LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
  466. LLVMStyle.AllowShortLoopsOnASingleLine = false;
  467. LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
  468. LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
  469. LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
  470. LLVMStyle.AlwaysBreakTemplateDeclarations = false;
  471. LLVMStyle.BinPackParameters = true;
  472. LLVMStyle.BinPackArguments = true;
  473. LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
  474. LLVMStyle.BreakBeforeTernaryOperators = true;
  475. LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
  476. LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
  477. false, false, false, false, false};
  478. LLVMStyle.BreakAfterJavaFieldAnnotations = false;
  479. LLVMStyle.BreakConstructorInitializersBeforeComma = false;
  480. LLVMStyle.BreakStringLiterals = true;
  481. LLVMStyle.ColumnLimit = 80;
  482. LLVMStyle.CommentPragmas = "^ IWYU pragma:";
  483. LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
  484. LLVMStyle.ConstructorInitializerIndentWidth = 4;
  485. LLVMStyle.ContinuationIndentWidth = 4;
  486. LLVMStyle.Cpp11BracedListStyle = true;
  487. LLVMStyle.DerivePointerAlignment = false;
  488. LLVMStyle.ExperimentalAutoDetectBinPacking = false;
  489. LLVMStyle.ForEachMacros.push_back("foreach");
  490. LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
  491. LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
  492. LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
  493. {"^(<|\"(gtest|isl|json)/)", 3},
  494. {".*", 1}};
  495. LLVMStyle.IncludeIsMainRegex = "$";
  496. LLVMStyle.IndentCaseLabels = false;
  497. LLVMStyle.IndentWrappedFunctionNames = false;
  498. LLVMStyle.IndentWidth = 2;
  499. LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
  500. LLVMStyle.JavaScriptWrapImports = true;
  501. LLVMStyle.TabWidth = 8;
  502. LLVMStyle.MaxEmptyLinesToKeep = 1;
  503. LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
  504. LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
  505. LLVMStyle.ObjCBlockIndentWidth = 2;
  506. LLVMStyle.ObjCSpaceAfterProperty = false;
  507. LLVMStyle.ObjCSpaceBeforeProtocolList = true;
  508. LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
  509. LLVMStyle.SpacesBeforeTrailingComments = 1;
  510. LLVMStyle.Standard = FormatStyle::LS_Cpp11;
  511. LLVMStyle.UseTab = FormatStyle::UT_Never;
  512. LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
  513. LLVMStyle.ReflowComments = true;
  514. LLVMStyle.SpacesInParentheses = false;
  515. LLVMStyle.SpacesInSquareBrackets = false;
  516. LLVMStyle.SpaceInEmptyParentheses = false;
  517. LLVMStyle.SpacesInContainerLiterals = true;
  518. LLVMStyle.SpacesInCStyleCastParentheses = false;
  519. LLVMStyle.SpaceAfterCStyleCast = false;
  520. LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
  521. LLVMStyle.SpaceBeforeAssignmentOperators = true;
  522. LLVMStyle.SpacesInAngles = false;
  523. LLVMStyle.PenaltyBreakComment = 300;
  524. LLVMStyle.PenaltyBreakFirstLessLess = 120;
  525. LLVMStyle.PenaltyBreakString = 1000;
  526. LLVMStyle.PenaltyExcessCharacter = 1000000;
  527. LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
  528. LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
  529. LLVMStyle.DisableFormat = false;
  530. LLVMStyle.SortIncludes = true;
  531. return LLVMStyle;
  532. }
  533. FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
  534. FormatStyle GoogleStyle = getLLVMStyle();
  535. GoogleStyle.Language = Language;
  536. GoogleStyle.AccessModifierOffset = -1;
  537. GoogleStyle.AlignEscapedNewlinesLeft = true;
  538. GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
  539. GoogleStyle.AllowShortLoopsOnASingleLine = true;
  540. GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
  541. GoogleStyle.AlwaysBreakTemplateDeclarations = true;
  542. GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
  543. GoogleStyle.DerivePointerAlignment = true;
  544. GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
  545. GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
  546. GoogleStyle.IndentCaseLabels = true;
  547. GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
  548. GoogleStyle.ObjCSpaceAfterProperty = false;
  549. GoogleStyle.ObjCSpaceBeforeProtocolList = false;
  550. GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
  551. GoogleStyle.SpacesBeforeTrailingComments = 2;
  552. GoogleStyle.Standard = FormatStyle::LS_Auto;
  553. GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  554. GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
  555. if (Language == FormatStyle::LK_Java) {
  556. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  557. GoogleStyle.AlignOperands = false;
  558. GoogleStyle.AlignTrailingComments = false;
  559. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
  560. GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
  561. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  562. GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
  563. GoogleStyle.ColumnLimit = 100;
  564. GoogleStyle.SpaceAfterCStyleCast = true;
  565. GoogleStyle.SpacesBeforeTrailingComments = 1;
  566. } else if (Language == FormatStyle::LK_JavaScript) {
  567. GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
  568. GoogleStyle.AlignOperands = false;
  569. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  570. GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
  571. GoogleStyle.BreakBeforeTernaryOperators = false;
  572. GoogleStyle.CommentPragmas = "@(export|requirecss|return|see|visibility) ";
  573. GoogleStyle.MaxEmptyLinesToKeep = 3;
  574. GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
  575. GoogleStyle.SpacesInContainerLiterals = false;
  576. GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
  577. GoogleStyle.JavaScriptWrapImports = false;
  578. } else if (Language == FormatStyle::LK_Proto) {
  579. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
  580. GoogleStyle.SpacesInContainerLiterals = false;
  581. }
  582. return GoogleStyle;
  583. }
  584. FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
  585. FormatStyle ChromiumStyle = getGoogleStyle(Language);
  586. if (Language == FormatStyle::LK_Java) {
  587. ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
  588. ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
  589. ChromiumStyle.ContinuationIndentWidth = 8;
  590. ChromiumStyle.IndentWidth = 4;
  591. } else {
  592. ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  593. ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  594. ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
  595. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  596. ChromiumStyle.BinPackParameters = false;
  597. ChromiumStyle.DerivePointerAlignment = false;
  598. }
  599. ChromiumStyle.SortIncludes = false;
  600. return ChromiumStyle;
  601. }
  602. FormatStyle getMozillaStyle() {
  603. FormatStyle MozillaStyle = getLLVMStyle();
  604. MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  605. MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  606. MozillaStyle.AlwaysBreakAfterReturnType =
  607. FormatStyle::RTBS_TopLevelDefinitions;
  608. MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
  609. FormatStyle::DRTBS_TopLevel;
  610. MozillaStyle.AlwaysBreakTemplateDeclarations = true;
  611. MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
  612. MozillaStyle.BreakConstructorInitializersBeforeComma = true;
  613. MozillaStyle.ConstructorInitializerIndentWidth = 2;
  614. MozillaStyle.ContinuationIndentWidth = 2;
  615. MozillaStyle.Cpp11BracedListStyle = false;
  616. MozillaStyle.IndentCaseLabels = true;
  617. MozillaStyle.ObjCSpaceAfterProperty = true;
  618. MozillaStyle.ObjCSpaceBeforeProtocolList = false;
  619. MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  620. MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
  621. return MozillaStyle;
  622. }
  623. FormatStyle getWebKitStyle() {
  624. FormatStyle Style = getLLVMStyle();
  625. Style.AccessModifierOffset = -4;
  626. Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
  627. Style.AlignOperands = false;
  628. Style.AlignTrailingComments = false;
  629. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  630. Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
  631. Style.BreakConstructorInitializersBeforeComma = true;
  632. Style.Cpp11BracedListStyle = false;
  633. Style.ColumnLimit = 0;
  634. Style.IndentWidth = 4;
  635. Style.NamespaceIndentation = FormatStyle::NI_Inner;
  636. Style.ObjCBlockIndentWidth = 4;
  637. Style.ObjCSpaceAfterProperty = true;
  638. Style.PointerAlignment = FormatStyle::PAS_Left;
  639. Style.Standard = FormatStyle::LS_Cpp03;
  640. return Style;
  641. }
  642. FormatStyle getGNUStyle() {
  643. FormatStyle Style = getLLVMStyle();
  644. Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
  645. Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
  646. Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
  647. Style.BreakBeforeBraces = FormatStyle::BS_GNU;
  648. Style.BreakBeforeTernaryOperators = true;
  649. Style.Cpp11BracedListStyle = false;
  650. Style.ColumnLimit = 79;
  651. Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
  652. Style.Standard = FormatStyle::LS_Cpp03;
  653. return Style;
  654. }
  655. FormatStyle getNoStyle() {
  656. FormatStyle NoStyle = getLLVMStyle();
  657. NoStyle.DisableFormat = true;
  658. NoStyle.SortIncludes = false;
  659. return NoStyle;
  660. }
  661. bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
  662. FormatStyle *Style) {
  663. if (Name.equals_lower("llvm")) {
  664. *Style = getLLVMStyle();
  665. } else if (Name.equals_lower("chromium")) {
  666. *Style = getChromiumStyle(Language);
  667. } else if (Name.equals_lower("mozilla")) {
  668. *Style = getMozillaStyle();
  669. } else if (Name.equals_lower("google")) {
  670. *Style = getGoogleStyle(Language);
  671. } else if (Name.equals_lower("webkit")) {
  672. *Style = getWebKitStyle();
  673. } else if (Name.equals_lower("gnu")) {
  674. *Style = getGNUStyle();
  675. } else if (Name.equals_lower("none")) {
  676. *Style = getNoStyle();
  677. } else {
  678. return false;
  679. }
  680. Style->Language = Language;
  681. return true;
  682. }
  683. std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
  684. assert(Style);
  685. FormatStyle::LanguageKind Language = Style->Language;
  686. assert(Language != FormatStyle::LK_None);
  687. if (Text.trim().empty())
  688. return make_error_code(ParseError::Error);
  689. std::vector<FormatStyle> Styles;
  690. llvm::yaml::Input Input(Text);
  691. // DocumentListTraits<vector<FormatStyle>> uses the context to get default
  692. // values for the fields, keys for which are missing from the configuration.
  693. // Mapping also uses the context to get the language to find the correct
  694. // base style.
  695. Input.setContext(Style);
  696. Input >> Styles;
  697. if (Input.error())
  698. return Input.error();
  699. for (unsigned i = 0; i < Styles.size(); ++i) {
  700. // Ensures that only the first configuration can skip the Language option.
  701. if (Styles[i].Language == FormatStyle::LK_None && i != 0)
  702. return make_error_code(ParseError::Error);
  703. // Ensure that each language is configured at most once.
  704. for (unsigned j = 0; j < i; ++j) {
  705. if (Styles[i].Language == Styles[j].Language) {
  706. DEBUG(llvm::dbgs()
  707. << "Duplicate languages in the config file on positions " << j
  708. << " and " << i << "\n");
  709. return make_error_code(ParseError::Error);
  710. }
  711. }
  712. }
  713. // Look for a suitable configuration starting from the end, so we can
  714. // find the configuration for the specific language first, and the default
  715. // configuration (which can only be at slot 0) after it.
  716. for (int i = Styles.size() - 1; i >= 0; --i) {
  717. if (Styles[i].Language == Language ||
  718. Styles[i].Language == FormatStyle::LK_None) {
  719. *Style = Styles[i];
  720. Style->Language = Language;
  721. return make_error_code(ParseError::Success);
  722. }
  723. }
  724. return make_error_code(ParseError::Unsuitable);
  725. }
  726. std::string configurationAsText(const FormatStyle &Style) {
  727. std::string Text;
  728. llvm::raw_string_ostream Stream(Text);
  729. llvm::yaml::Output Output(Stream);
  730. // We use the same mapping method for input and output, so we need a non-const
  731. // reference here.
  732. FormatStyle NonConstStyle = expandPresets(Style);
  733. Output << NonConstStyle;
  734. return Stream.str();
  735. }
  736. namespace {
  737. class Formatter : public TokenAnalyzer {
  738. public:
  739. Formatter(const Environment &Env, const FormatStyle &Style,
  740. bool *IncompleteFormat)
  741. : TokenAnalyzer(Env, Style), IncompleteFormat(IncompleteFormat) {}
  742. tooling::Replacements
  743. analyze(TokenAnnotator &Annotator,
  744. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  745. FormatTokenLexer &Tokens, tooling::Replacements &Result) override {
  746. deriveLocalStyle(AnnotatedLines);
  747. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  748. AnnotatedLines.end());
  749. if (Style.Language == FormatStyle::LK_JavaScript &&
  750. Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
  751. requoteJSStringLiteral(AnnotatedLines, Result);
  752. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  753. Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
  754. }
  755. Annotator.setCommentLineLevels(AnnotatedLines);
  756. WhitespaceManager Whitespaces(
  757. Env.getSourceManager(), Style,
  758. inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
  759. ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
  760. Env.getSourceManager(), Whitespaces, Encoding,
  761. BinPackInconclusiveFunctions);
  762. UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
  763. IncompleteFormat)
  764. .format(AnnotatedLines);
  765. return Whitespaces.generateReplacements();
  766. }
  767. private:
  768. // If the last token is a double/single-quoted string literal, generates a
  769. // replacement with a single/double quoted string literal, re-escaping the
  770. // contents in the process.
  771. void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
  772. tooling::Replacements &Result) {
  773. for (AnnotatedLine *Line : Lines) {
  774. requoteJSStringLiteral(Line->Children, Result);
  775. if (!Line->Affected)
  776. continue;
  777. for (FormatToken *FormatTok = Line->First; FormatTok;
  778. FormatTok = FormatTok->Next) {
  779. StringRef Input = FormatTok->TokenText;
  780. if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
  781. // NB: testing for not starting with a double quote to avoid
  782. // breaking
  783. // `template strings`.
  784. (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
  785. !Input.startswith("\"")) ||
  786. (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
  787. !Input.startswith("\'")))
  788. continue;
  789. // Change start and end quote.
  790. bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
  791. SourceLocation Start = FormatTok->Tok.getLocation();
  792. auto Replace = [&](SourceLocation Start, unsigned Length,
  793. StringRef ReplacementText) {
  794. Result.insert(tooling::Replacement(Env.getSourceManager(), Start,
  795. Length, ReplacementText));
  796. };
  797. Replace(Start, 1, IsSingle ? "'" : "\"");
  798. Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
  799. IsSingle ? "'" : "\"");
  800. // Escape internal quotes.
  801. size_t ColumnWidth = FormatTok->TokenText.size();
  802. bool Escaped = false;
  803. for (size_t i = 1; i < Input.size() - 1; i++) {
  804. switch (Input[i]) {
  805. case '\\':
  806. if (!Escaped && i + 1 < Input.size() &&
  807. ((IsSingle && Input[i + 1] == '"') ||
  808. (!IsSingle && Input[i + 1] == '\''))) {
  809. // Remove this \, it's escaping a " or ' that no longer needs
  810. // escaping
  811. ColumnWidth--;
  812. Replace(Start.getLocWithOffset(i), 1, "");
  813. continue;
  814. }
  815. Escaped = !Escaped;
  816. break;
  817. case '\"':
  818. case '\'':
  819. if (!Escaped && IsSingle == (Input[i] == '\'')) {
  820. // Escape the quote.
  821. Replace(Start.getLocWithOffset(i), 0, "\\");
  822. ColumnWidth++;
  823. }
  824. Escaped = false;
  825. break;
  826. default:
  827. Escaped = false;
  828. break;
  829. }
  830. }
  831. // For formatting, count the number of non-escaped single quotes in them
  832. // and adjust ColumnWidth to take the added escapes into account.
  833. // FIXME(martinprobst): this might conflict with code breaking a long
  834. // string literal (which clang-format doesn't do, yet). For that to
  835. // work, this code would have to modify TokenText directly.
  836. FormatTok->ColumnWidth = ColumnWidth;
  837. }
  838. }
  839. }
  840. static bool inputUsesCRLF(StringRef Text) {
  841. return Text.count('\r') * 2 > Text.count('\n');
  842. }
  843. bool
  844. hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  845. for (const AnnotatedLine *Line : Lines) {
  846. if (hasCpp03IncompatibleFormat(Line->Children))
  847. return true;
  848. for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
  849. if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
  850. if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
  851. return true;
  852. if (Tok->is(TT_TemplateCloser) &&
  853. Tok->Previous->is(TT_TemplateCloser))
  854. return true;
  855. }
  856. }
  857. }
  858. return false;
  859. }
  860. int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
  861. int AlignmentDiff = 0;
  862. for (const AnnotatedLine *Line : Lines) {
  863. AlignmentDiff += countVariableAlignments(Line->Children);
  864. for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
  865. if (!Tok->is(TT_PointerOrReference))
  866. continue;
  867. bool SpaceBefore =
  868. Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
  869. bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
  870. Tok->Next->WhitespaceRange.getEnd();
  871. if (SpaceBefore && !SpaceAfter)
  872. ++AlignmentDiff;
  873. if (!SpaceBefore && SpaceAfter)
  874. --AlignmentDiff;
  875. }
  876. }
  877. return AlignmentDiff;
  878. }
  879. void
  880. deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  881. bool HasBinPackedFunction = false;
  882. bool HasOnePerLineFunction = false;
  883. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  884. if (!AnnotatedLines[i]->First->Next)
  885. continue;
  886. FormatToken *Tok = AnnotatedLines[i]->First->Next;
  887. while (Tok->Next) {
  888. if (Tok->PackingKind == PPK_BinPacked)
  889. HasBinPackedFunction = true;
  890. if (Tok->PackingKind == PPK_OnePerLine)
  891. HasOnePerLineFunction = true;
  892. Tok = Tok->Next;
  893. }
  894. }
  895. if (Style.DerivePointerAlignment)
  896. Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
  897. ? FormatStyle::PAS_Left
  898. : FormatStyle::PAS_Right;
  899. if (Style.Standard == FormatStyle::LS_Auto)
  900. Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
  901. ? FormatStyle::LS_Cpp11
  902. : FormatStyle::LS_Cpp03;
  903. BinPackInconclusiveFunctions =
  904. HasBinPackedFunction || !HasOnePerLineFunction;
  905. }
  906. bool BinPackInconclusiveFunctions;
  907. bool *IncompleteFormat;
  908. };
  909. // This class clean up the erroneous/redundant code around the given ranges in
  910. // file.
  911. class Cleaner : public TokenAnalyzer {
  912. public:
  913. Cleaner(const Environment &Env, const FormatStyle &Style)
  914. : TokenAnalyzer(Env, Style),
  915. DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
  916. // FIXME: eliminate unused parameters.
  917. tooling::Replacements
  918. analyze(TokenAnnotator &Annotator,
  919. SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  920. FormatTokenLexer &Tokens, tooling::Replacements &Result) override {
  921. // FIXME: in the current implementation the granularity of affected range
  922. // is an annotated line. However, this is not sufficient. Furthermore,
  923. // redundant code introduced by replacements does not necessarily
  924. // intercept with ranges of replacements that result in the redundancy.
  925. // To determine if some redundant code is actually introduced by
  926. // replacements(e.g. deletions), we need to come up with a more
  927. // sophisticated way of computing affected ranges.
  928. AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
  929. AnnotatedLines.end());
  930. checkEmptyNamespace(AnnotatedLines);
  931. for (auto &Line : AnnotatedLines) {
  932. if (Line->Affected) {
  933. cleanupRight(Line->First, tok::comma, tok::comma);
  934. cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
  935. cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
  936. cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
  937. }
  938. }
  939. return generateFixes();
  940. }
  941. private:
  942. bool containsOnlyComments(const AnnotatedLine &Line) {
  943. for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
  944. if (Tok->isNot(tok::comment))
  945. return false;
  946. }
  947. return true;
  948. }
  949. // Iterate through all lines and remove any empty (nested) namespaces.
  950. void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  951. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  952. auto &Line = *AnnotatedLines[i];
  953. if (Line.startsWith(tok::kw_namespace) ||
  954. Line.startsWith(tok::kw_inline, tok::kw_namespace)) {
  955. checkEmptyNamespace(AnnotatedLines, i, i);
  956. }
  957. }
  958. for (auto Line : DeletedLines) {
  959. FormatToken *Tok = AnnotatedLines[Line]->First;
  960. while (Tok) {
  961. deleteToken(Tok);
  962. Tok = Tok->Next;
  963. }
  964. }
  965. }
  966. // The function checks if the namespace, which starts from \p CurrentLine, and
  967. // its nested namespaces are empty and delete them if they are empty. It also
  968. // sets \p NewLine to the last line checked.
  969. // Returns true if the current namespace is empty.
  970. bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  971. unsigned CurrentLine, unsigned &NewLine) {
  972. unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
  973. if (Style.BraceWrapping.AfterNamespace) {
  974. // If the left brace is in a new line, we should consume it first so that
  975. // it does not make the namespace non-empty.
  976. // FIXME: error handling if there is no left brace.
  977. if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
  978. NewLine = CurrentLine;
  979. return false;
  980. }
  981. } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
  982. return false;
  983. }
  984. while (++CurrentLine < End) {
  985. if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
  986. break;
  987. if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) ||
  988. AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline,
  989. tok::kw_namespace)) {
  990. if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine))
  991. return false;
  992. CurrentLine = NewLine;
  993. continue;
  994. }
  995. if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
  996. continue;
  997. // If there is anything other than comments or nested namespaces in the
  998. // current namespace, the namespace cannot be empty.
  999. NewLine = CurrentLine;
  1000. return false;
  1001. }
  1002. NewLine = CurrentLine;
  1003. if (CurrentLine >= End)
  1004. return false;
  1005. // Check if the empty namespace is actually affected by changed ranges.
  1006. if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
  1007. AnnotatedLines[InitLine]->First->Tok.getLocation(),
  1008. AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
  1009. return false;
  1010. for (unsigned i = InitLine; i <= CurrentLine; ++i) {
  1011. DeletedLines.insert(i);
  1012. }
  1013. return true;
  1014. }
  1015. // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
  1016. // of the token in the pair if the left token has \p LK token kind and the
  1017. // right token has \p RK token kind. If \p DeleteLeft is true, the left token
  1018. // is deleted on match; otherwise, the right token is deleted.
  1019. template <typename LeftKind, typename RightKind>
  1020. void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
  1021. bool DeleteLeft) {
  1022. auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
  1023. for (auto *Res = Tok.Next; Res; Res = Res->Next)
  1024. if (!Res->is(tok::comment) &&
  1025. DeletedTokens.find(Res) == DeletedTokens.end())
  1026. return Res;
  1027. return nullptr;
  1028. };
  1029. for (auto *Left = Start; Left;) {
  1030. auto *Right = NextNotDeleted(*Left);
  1031. if (!Right)
  1032. break;
  1033. if (Left->is(LK) && Right->is(RK)) {
  1034. deleteToken(DeleteLeft ? Left : Right);
  1035. // If the right token is deleted, we should keep the left token
  1036. // unchanged and pair it with the new right token.
  1037. if (!DeleteLeft)
  1038. continue;
  1039. }
  1040. Left = Right;
  1041. }
  1042. }
  1043. template <typename LeftKind, typename RightKind>
  1044. void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
  1045. cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
  1046. }
  1047. template <typename LeftKind, typename RightKind>
  1048. void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
  1049. cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
  1050. }
  1051. // Delete the given token.
  1052. inline void deleteToken(FormatToken *Tok) {
  1053. if (Tok)
  1054. DeletedTokens.insert(Tok);
  1055. }
  1056. tooling::Replacements generateFixes() {
  1057. tooling::Replacements Fixes;
  1058. std::vector<FormatToken *> Tokens;
  1059. std::copy(DeletedTokens.begin(), DeletedTokens.end(),
  1060. std::back_inserter(Tokens));
  1061. // Merge multiple continuous token deletions into one big deletion so that
  1062. // the number of replacements can be reduced. This makes computing affected
  1063. // ranges more efficient when we run reformat on the changed code.
  1064. unsigned Idx = 0;
  1065. while (Idx < Tokens.size()) {
  1066. unsigned St = Idx, End = Idx;
  1067. while ((End + 1) < Tokens.size() &&
  1068. Tokens[End]->Next == Tokens[End + 1]) {
  1069. End++;
  1070. }
  1071. auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
  1072. Tokens[End]->Tok.getEndLoc());
  1073. Fixes.insert(tooling::Replacement(Env.getSourceManager(), SR, ""));
  1074. Idx = End + 1;
  1075. }
  1076. return Fixes;
  1077. }
  1078. // Class for less-than inequality comparason for the set `RedundantTokens`.
  1079. // We store tokens in the order they appear in the translation unit so that
  1080. // we do not need to sort them in `generateFixes()`.
  1081. struct FormatTokenLess {
  1082. FormatTokenLess(const SourceManager &SM) : SM(SM) {}
  1083. bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
  1084. return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
  1085. RHS->Tok.getLocation());
  1086. }
  1087. const SourceManager &SM;
  1088. };
  1089. // Tokens to be deleted.
  1090. std::set<FormatToken *, FormatTokenLess> DeletedTokens;
  1091. // The line numbers of lines to be deleted.
  1092. std::set<unsigned> DeletedLines;
  1093. };
  1094. struct IncludeDirective {
  1095. StringRef Filename;
  1096. StringRef Text;
  1097. unsigned Offset;
  1098. int Category;
  1099. };
  1100. } // end anonymous namespace
  1101. // Determines whether 'Ranges' intersects with ('Start', 'End').
  1102. static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
  1103. unsigned End) {
  1104. for (auto Range : Ranges) {
  1105. if (Range.getOffset() < End &&
  1106. Range.getOffset() + Range.getLength() > Start)
  1107. return true;
  1108. }
  1109. return false;
  1110. }
  1111. // Sorts a block of includes given by 'Includes' alphabetically adding the
  1112. // necessary replacement to 'Replaces'. 'Includes' must be in strict source
  1113. // order.
  1114. static void sortCppIncludes(const FormatStyle &Style,
  1115. const SmallVectorImpl<IncludeDirective> &Includes,
  1116. ArrayRef<tooling::Range> Ranges, StringRef FileName,
  1117. tooling::Replacements &Replaces, unsigned *Cursor) {
  1118. if (!affectsRange(Ranges, Includes.front().Offset,
  1119. Includes.back().Offset + Includes.back().Text.size()))
  1120. return;
  1121. SmallVector<unsigned, 16> Indices;
  1122. for (unsigned i = 0, e = Includes.size(); i != e; ++i)
  1123. Indices.push_back(i);
  1124. std::stable_sort(
  1125. Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
  1126. return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
  1127. std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
  1128. });
  1129. // If the #includes are out of order, we generate a single replacement fixing
  1130. // the entire block. Otherwise, no replacement is generated.
  1131. if (std::is_sorted(Indices.begin(), Indices.end()))
  1132. return;
  1133. std::string result;
  1134. bool CursorMoved = false;
  1135. for (unsigned Index : Indices) {
  1136. if (!result.empty())
  1137. result += "\n";
  1138. result += Includes[Index].Text;
  1139. if (Cursor && !CursorMoved) {
  1140. unsigned Start = Includes[Index].Offset;
  1141. unsigned End = Start + Includes[Index].Text.size();
  1142. if (*Cursor >= Start && *Cursor < End) {
  1143. *Cursor = Includes.front().Offset + result.size() + *Cursor - End;
  1144. CursorMoved = true;
  1145. }
  1146. }
  1147. }
  1148. // Sorting #includes shouldn't change their total number of characters.
  1149. // This would otherwise mess up 'Ranges'.
  1150. assert(result.size() ==
  1151. Includes.back().Offset + Includes.back().Text.size() -
  1152. Includes.front().Offset);
  1153. Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
  1154. result.size(), result));
  1155. }
  1156. namespace {
  1157. // This class manages priorities of #include categories and calculates
  1158. // priorities for headers.
  1159. class IncludeCategoryManager {
  1160. public:
  1161. IncludeCategoryManager(const FormatStyle &Style, StringRef FileName)
  1162. : Style(Style), FileName(FileName) {
  1163. FileStem = llvm::sys::path::stem(FileName);
  1164. for (const auto &Category : Style.IncludeCategories)
  1165. CategoryRegexs.emplace_back(Category.Regex);
  1166. IsMainFile = FileName.endswith(".c") || FileName.endswith(".cc") ||
  1167. FileName.endswith(".cpp") || FileName.endswith(".c++") ||
  1168. FileName.endswith(".cxx") || FileName.endswith(".m") ||
  1169. FileName.endswith(".mm");
  1170. }
  1171. // Returns the priority of the category which \p IncludeName belongs to.
  1172. // If \p CheckMainHeader is true and \p IncludeName is a main header, returns
  1173. // 0. Otherwise, returns the priority of the matching category or INT_MAX.
  1174. int getIncludePriority(StringRef IncludeName, bool CheckMainHeader) {
  1175. int Ret = INT_MAX;
  1176. for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i)
  1177. if (CategoryRegexs[i].match(IncludeName)) {
  1178. Ret = Style.IncludeCategories[i].Priority;
  1179. break;
  1180. }
  1181. if (CheckMainHeader && IsMainFile && Ret > 0 && isMainHeader(IncludeName))
  1182. Ret = 0;
  1183. return Ret;
  1184. }
  1185. private:
  1186. bool isMainHeader(StringRef IncludeName) const {
  1187. if (!IncludeName.startswith("\""))
  1188. return false;
  1189. StringRef HeaderStem =
  1190. llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
  1191. if (FileStem.startswith(HeaderStem)) {
  1192. llvm::Regex MainIncludeRegex(
  1193. (HeaderStem + Style.IncludeIsMainRegex).str());
  1194. if (MainIncludeRegex.match(FileStem))
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. const FormatStyle &Style;
  1200. bool IsMainFile;
  1201. StringRef FileName;
  1202. StringRef FileStem;
  1203. SmallVector<llvm::Regex, 4> CategoryRegexs;
  1204. };
  1205. const char IncludeRegexPattern[] =
  1206. R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
  1207. } // anonymous namespace
  1208. tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
  1209. ArrayRef<tooling::Range> Ranges,
  1210. StringRef FileName,
  1211. tooling::Replacements &Replaces,
  1212. unsigned *Cursor) {
  1213. unsigned Prev = 0;
  1214. unsigned SearchFrom = 0;
  1215. llvm::Regex IncludeRegex(IncludeRegexPattern);
  1216. SmallVector<StringRef, 4> Matches;
  1217. SmallVector<IncludeDirective, 16> IncludesInBlock;
  1218. // In compiled files, consider the first #include to be the main #include of
  1219. // the file if it is not a system #include. This ensures that the header
  1220. // doesn't have hidden dependencies
  1221. // (http://llvm.org/docs/CodingStandards.html#include-style).
  1222. //
  1223. // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
  1224. // cases where the first #include is unlikely to be the main header.
  1225. IncludeCategoryManager Categories(Style, FileName);
  1226. bool FirstIncludeBlock = true;
  1227. bool MainIncludeFound = false;
  1228. bool FormattingOff = false;
  1229. for (;;) {
  1230. auto Pos = Code.find('\n', SearchFrom);
  1231. StringRef Line =
  1232. Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
  1233. StringRef Trimmed = Line.trim();
  1234. if (Trimmed == "// clang-format off")
  1235. FormattingOff = true;
  1236. else if (Trimmed == "// clang-format on")
  1237. FormattingOff = false;
  1238. if (!FormattingOff && !Line.endswith("\\")) {
  1239. if (IncludeRegex.match(Line, &Matches)) {
  1240. StringRef IncludeName = Matches[2];
  1241. int Category = Categories.getIncludePriority(
  1242. IncludeName,
  1243. /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
  1244. if (Category == 0)
  1245. MainIncludeFound = true;
  1246. IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
  1247. } else if (!IncludesInBlock.empty()) {
  1248. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
  1249. Cursor);
  1250. IncludesInBlock.clear();
  1251. FirstIncludeBlock = false;
  1252. }
  1253. Prev = Pos + 1;
  1254. }
  1255. if (Pos == StringRef::npos || Pos + 1 == Code.size())
  1256. break;
  1257. SearchFrom = Pos + 1;
  1258. }
  1259. if (!IncludesInBlock.empty())
  1260. sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
  1261. return Replaces;
  1262. }
  1263. tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
  1264. ArrayRef<tooling::Range> Ranges,
  1265. StringRef FileName, unsigned *Cursor) {
  1266. tooling::Replacements Replaces;
  1267. if (!Style.SortIncludes)
  1268. return Replaces;
  1269. if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
  1270. return sortJavaScriptImports(Style, Code, Ranges, FileName);
  1271. sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
  1272. return Replaces;
  1273. }
  1274. template <typename T>
  1275. static llvm::Expected<tooling::Replacements>
  1276. processReplacements(T ProcessFunc, StringRef Code,
  1277. const tooling::Replacements &Replaces,
  1278. const FormatStyle &Style) {
  1279. if (Replaces.empty())
  1280. return tooling::Replacements();
  1281. auto NewCode = applyAllReplacements(Code, Replaces);
  1282. if (!NewCode)
  1283. return NewCode.takeError();
  1284. std::vector<tooling::Range> ChangedRanges =
  1285. tooling::calculateChangedRanges(Replaces);
  1286. StringRef FileName = Replaces.begin()->getFilePath();
  1287. tooling::Replacements FormatReplaces =
  1288. ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
  1289. return mergeReplacements(Replaces, FormatReplaces);
  1290. }
  1291. llvm::Expected<tooling::Replacements>
  1292. formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
  1293. const FormatStyle &Style) {
  1294. // We need to use lambda function here since there are two versions of
  1295. // `sortIncludes`.
  1296. auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
  1297. std::vector<tooling::Range> Ranges,
  1298. StringRef FileName) -> tooling::Replacements {
  1299. return sortIncludes(Style, Code, Ranges, FileName);
  1300. };
  1301. auto SortedReplaces =
  1302. processReplacements(SortIncludes, Code, Replaces, Style);
  1303. if (!SortedReplaces)
  1304. return SortedReplaces.takeError();
  1305. // We need to use lambda function here since there are two versions of
  1306. // `reformat`.
  1307. auto Reformat = [](const FormatStyle &Style, StringRef Code,
  1308. std::vector<tooling::Range> Ranges,
  1309. StringRef FileName) -> tooling::Replacements {
  1310. return reformat(Style, Code, Ranges, FileName);
  1311. };
  1312. return processReplacements(Reformat, Code, *SortedReplaces, Style);
  1313. }
  1314. namespace {
  1315. inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
  1316. return Replace.getOffset() == UINT_MAX &&
  1317. llvm::Regex(IncludeRegexPattern).match(Replace.getReplacementText());
  1318. }
  1319. void skipComments(Lexer &Lex, Token &Tok) {
  1320. while (Tok.is(tok::comment))
  1321. if (Lex.LexFromRawLexer(Tok))
  1322. return;
  1323. }
  1324. // Check if a sequence of tokens is like "#<Name> <raw_identifier>". If it is,
  1325. // \p Tok will be the token after this directive; otherwise, it can be any token
  1326. // after the given \p Tok (including \p Tok).
  1327. bool checkAndConsumeDirectiveWithName(Lexer &Lex, StringRef Name, Token &Tok) {
  1328. bool Matched = Tok.is(tok::hash) && !Lex.LexFromRawLexer(Tok) &&
  1329. Tok.is(tok::raw_identifier) &&
  1330. Tok.getRawIdentifier() == Name && !Lex.LexFromRawLexer(Tok) &&
  1331. Tok.is(tok::raw_identifier);
  1332. if (Matched)
  1333. Lex.LexFromRawLexer(Tok);
  1334. return Matched;
  1335. }
  1336. unsigned getOffsetAfterHeaderGuardsAndComments(StringRef FileName,
  1337. StringRef Code,
  1338. const FormatStyle &Style) {
  1339. std::unique_ptr<Environment> Env =
  1340. Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
  1341. const SourceManager &SourceMgr = Env->getSourceManager();
  1342. Lexer Lex(Env->getFileID(), SourceMgr.getBuffer(Env->getFileID()), SourceMgr,
  1343. getFormattingLangOpts(Style));
  1344. Token Tok;
  1345. // Get the first token.
  1346. Lex.LexFromRawLexer(Tok);
  1347. skipComments(Lex, Tok);
  1348. unsigned AfterComments = SourceMgr.getFileOffset(Tok.getLocation());
  1349. if (checkAndConsumeDirectiveWithName(Lex, "ifndef", Tok)) {
  1350. skipComments(Lex, Tok);
  1351. if (checkAndConsumeDirectiveWithName(Lex, "define", Tok))
  1352. return SourceMgr.getFileOffset(Tok.getLocation());
  1353. }
  1354. return AfterComments;
  1355. }
  1356. // FIXME: we also need to insert a '\n' at the end of the code if we have an
  1357. // insertion with offset Code.size(), and there is no '\n' at the end of the
  1358. // code.
  1359. // FIXME: do not insert headers into conditional #include blocks, e.g. #includes
  1360. // surrounded by compile condition "#if...".
  1361. // FIXME: insert empty lines between newly created blocks.
  1362. tooling::Replacements
  1363. fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
  1364. const FormatStyle &Style) {
  1365. if (Style.Language != FormatStyle::LanguageKind::LK_Cpp)
  1366. return Replaces;
  1367. tooling::Replacements HeaderInsertions;
  1368. for (const auto &R : Replaces) {
  1369. if (isHeaderInsertion(R))
  1370. HeaderInsertions.insert(R);
  1371. else if (R.getOffset() == UINT_MAX)
  1372. llvm::errs() << "Insertions other than header #include insertion are "
  1373. "not supported! "
  1374. << R.getReplacementText() << "\n";
  1375. }
  1376. if (HeaderInsertions.empty())
  1377. return Replaces;
  1378. tooling::Replacements Result;
  1379. std::set_difference(Replaces.begin(), Replaces.end(),
  1380. HeaderInsertions.begin(), HeaderInsertions.end(),
  1381. std::inserter(Result, Result.begin()));
  1382. llvm::Regex IncludeRegex(IncludeRegexPattern);
  1383. llvm::Regex DefineRegex(R"(^[\t\ ]*#[\t\ ]*define[\t\ ]*[^\\]*$)");
  1384. SmallVector<StringRef, 4> Matches;
  1385. StringRef FileName = Replaces.begin()->getFilePath();
  1386. IncludeCategoryManager Categories(Style, FileName);
  1387. // Record the offset of the end of the last include in each category.
  1388. std::map<int, int> CategoryEndOffsets;
  1389. // All possible priorities.
  1390. // Add 0 for main header and INT_MAX for headers that are not in any category.
  1391. std::set<int> Priorities = {0, INT_MAX};
  1392. for (const auto &Category : Style.IncludeCategories)
  1393. Priorities.insert(Category.Priority);
  1394. int FirstIncludeOffset = -1;
  1395. // All new headers should be inserted after this offset.
  1396. unsigned MinInsertOffset =
  1397. getOffsetAfterHeaderGuardsAndComments(FileName, Code, Style);
  1398. StringRef TrimmedCode = Code.drop_front(MinInsertOffset);
  1399. SmallVector<StringRef, 32> Lines;
  1400. TrimmedCode.split(Lines, '\n');
  1401. unsigned Offset = MinInsertOffset;
  1402. unsigned NextLineOffset;
  1403. std::set<StringRef> ExistingIncludes;
  1404. for (auto Line : Lines) {
  1405. NextLineOffset = std::min(Code.size(), Offset + Line.size() + 1);
  1406. if (IncludeRegex.match(Line, &Matches)) {
  1407. StringRef IncludeName = Matches[2];
  1408. ExistingIncludes.insert(IncludeName);
  1409. int Category = Categories.getIncludePriority(
  1410. IncludeName, /*CheckMainHeader=*/FirstIncludeOffset < 0);
  1411. CategoryEndOffsets[Category] = NextLineOffset;
  1412. if (FirstIncludeOffset < 0)
  1413. FirstIncludeOffset = Offset;
  1414. }
  1415. Offset = NextLineOffset;
  1416. }
  1417. // Populate CategoryEndOfssets:
  1418. // - Ensure that CategoryEndOffset[Highest] is always populated.
  1419. // - If CategoryEndOffset[Priority] isn't set, use the next higher value that
  1420. // is set, up to CategoryEndOffset[Highest].
  1421. auto Highest = Priorities.begin();
  1422. if (CategoryEndOffsets.find(*Highest) == CategoryEndOffsets.end()) {
  1423. if (FirstIncludeOffset >= 0)
  1424. CategoryEndOffsets[*Highest] = FirstIncludeOffset;
  1425. else
  1426. CategoryEndOffsets[*Highest] = MinInsertOffset;
  1427. }
  1428. // By this point, CategoryEndOffset[Highest] is always set appropriately:
  1429. // - to an appropriate location before/after existing #includes, or
  1430. // - to right after the header guard, or
  1431. // - to the beginning of the file.
  1432. for (auto I = ++Priorities.begin(), E = Priorities.end(); I != E; ++I)
  1433. if (CategoryEndOffsets.find(*I) == CategoryEndOffsets.end())
  1434. CategoryEndOffsets[*I] = CategoryEndOffsets[*std::prev(I)];
  1435. for (const auto &R : HeaderInsertions) {
  1436. auto IncludeDirective = R.getReplacementText();
  1437. bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
  1438. assert(Matched && "Header insertion replacement must have replacement text "
  1439. "'#include ...'");
  1440. (void)Matched;
  1441. auto IncludeName = Matches[2];
  1442. if (ExistingIncludes.find(IncludeName) != ExistingIncludes.end()) {
  1443. DEBUG(llvm::dbgs() << "Skip adding existing include : " << IncludeName
  1444. << "\n");
  1445. continue;
  1446. }
  1447. int Category =
  1448. Categories.getIncludePriority(IncludeName, /*CheckMainHeader=*/true);
  1449. Offset = CategoryEndOffsets[Category];
  1450. std::string NewInclude = !IncludeDirective.endswith("\n")
  1451. ? (IncludeDirective + "\n").str()
  1452. : IncludeDirective.str();
  1453. Result.insert(tooling::Replacement(FileName, Offset, 0, NewInclude));
  1454. }
  1455. return Result;
  1456. }
  1457. } // anonymous namespace
  1458. llvm::Expected<tooling::Replacements>
  1459. cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
  1460. const FormatStyle &Style) {
  1461. // We need to use lambda function here since there are two versions of
  1462. // `cleanup`.
  1463. auto Cleanup = [](const FormatStyle &Style, StringRef Code,
  1464. std::vector<tooling::Range> Ranges,
  1465. StringRef FileName) -> tooling::Replacements {
  1466. return cleanup(Style, Code, Ranges, FileName);
  1467. };
  1468. // Make header insertion replacements insert new headers into correct blocks.
  1469. tooling::Replacements NewReplaces =
  1470. fixCppIncludeInsertions(Code, Replaces, Style);
  1471. return processReplacements(Cleanup, Code, NewReplaces, Style);
  1472. }
  1473. tooling::Replacements reformat(const FormatStyle &Style, SourceManager &SM,
  1474. FileID ID, ArrayRef<CharSourceRange> Ranges,
  1475. bool *IncompleteFormat) {
  1476. FormatStyle Expanded = expandPresets(Style);
  1477. if (Expanded.DisableFormat)
  1478. return tooling::Replacements();
  1479. Environment Env(SM, ID, Ranges);
  1480. Formatter Format(Env, Expanded, IncompleteFormat);
  1481. return Format.process();
  1482. }
  1483. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  1484. ArrayRef<tooling::Range> Ranges,
  1485. StringRef FileName, bool *IncompleteFormat) {
  1486. FormatStyle Expanded = expandPresets(Style);
  1487. if (Expanded.DisableFormat)
  1488. return tooling::Replacements();
  1489. std::unique_ptr<Environment> Env =
  1490. Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  1491. Formatter Format(*Env, Expanded, IncompleteFormat);
  1492. return Format.process();
  1493. }
  1494. tooling::Replacements cleanup(const FormatStyle &Style, SourceManager &SM,
  1495. FileID ID, ArrayRef<CharSourceRange> Ranges) {
  1496. Environment Env(SM, ID, Ranges);
  1497. Cleaner Clean(Env, Style);
  1498. return Clean.process();
  1499. }
  1500. tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
  1501. ArrayRef<tooling::Range> Ranges,
  1502. StringRef FileName) {
  1503. std::unique_ptr<Environment> Env =
  1504. Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
  1505. Cleaner Clean(*Env, Style);
  1506. return Clean.process();
  1507. }
  1508. LangOptions getFormattingLangOpts(const FormatStyle &Style) {
  1509. LangOptions LangOpts;
  1510. LangOpts.CPlusPlus = 1;
  1511. LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  1512. LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  1513. LangOpts.LineComment = 1;
  1514. bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
  1515. LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
  1516. LangOpts.Bool = 1;
  1517. LangOpts.ObjC1 = 1;
  1518. LangOpts.ObjC2 = 1;
  1519. LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
  1520. LangOpts.DeclSpecKeyword = 1; // To get __declspec.
  1521. return LangOpts;
  1522. }
  1523. const char *StyleOptionHelpDescription =
  1524. "Coding style, currently supports:\n"
  1525. " LLVM, Google, Chromium, Mozilla, WebKit.\n"
  1526. "Use -style=file to load style configuration from\n"
  1527. ".clang-format file located in one of the parent\n"
  1528. "directories of the source file (or current\n"
  1529. "directory for stdin).\n"
  1530. "Use -style=\"{key: value, ...}\" to set specific\n"
  1531. "parameters, e.g.:\n"
  1532. " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
  1533. static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
  1534. if (FileName.endswith(".java"))
  1535. return FormatStyle::LK_Java;
  1536. if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
  1537. return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
  1538. if (FileName.endswith_lower(".proto") ||
  1539. FileName.endswith_lower(".protodevel"))
  1540. return FormatStyle::LK_Proto;
  1541. if (FileName.endswith_lower(".td"))
  1542. return FormatStyle::LK_TableGen;
  1543. return FormatStyle::LK_Cpp;
  1544. }
  1545. FormatStyle getStyle(StringRef StyleName, StringRef FileName,
  1546. StringRef FallbackStyle, vfs::FileSystem *FS) {
  1547. if (!FS) {
  1548. FS = vfs::getRealFileSystem().get();
  1549. }
  1550. FormatStyle Style = getLLVMStyle();
  1551. Style.Language = getLanguageByFileName(FileName);
  1552. if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
  1553. llvm::errs() << "Invalid fallback style \"" << FallbackStyle
  1554. << "\" using LLVM style\n";
  1555. return Style;
  1556. }
  1557. if (StyleName.startswith("{")) {
  1558. // Parse YAML/JSON style from the command line.
  1559. if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
  1560. llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
  1561. << FallbackStyle << " style\n";
  1562. }
  1563. return Style;
  1564. }
  1565. if (!StyleName.equals_lower("file")) {
  1566. if (!getPredefinedStyle(StyleName, Style.Language, &Style))
  1567. llvm::errs() << "Invalid value for -style, using " << FallbackStyle
  1568. << " style\n";
  1569. return Style;
  1570. }
  1571. // Look for .clang-format/_clang-format file in the file's parent directories.
  1572. SmallString<128> UnsuitableConfigFiles;
  1573. SmallString<128> Path(FileName);
  1574. llvm::sys::fs::make_absolute(Path);
  1575. for (StringRef Directory = Path; !Directory.empty();
  1576. Directory = llvm::sys::path::parent_path(Directory)) {
  1577. auto Status = FS->status(Directory);
  1578. if (!Status ||
  1579. Status->getType() != llvm::sys::fs::file_type::directory_file) {
  1580. continue;
  1581. }
  1582. SmallString<128> ConfigFile(Directory);
  1583. llvm::sys::path::append(ConfigFile, ".clang-format");
  1584. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1585. Status = FS->status(ConfigFile.str());
  1586. bool IsFile =
  1587. Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
  1588. if (!IsFile) {
  1589. // Try _clang-format too, since dotfiles are not commonly used on Windows.
  1590. ConfigFile = Directory;
  1591. llvm::sys::path::append(ConfigFile, "_clang-format");
  1592. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1593. Status = FS->status(ConfigFile.str());
  1594. IsFile = Status &&
  1595. (Status->getType() == llvm::sys::fs::file_type::regular_file);
  1596. }
  1597. if (IsFile) {
  1598. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  1599. FS->getBufferForFile(ConfigFile.str());
  1600. if (std::error_code EC = Text.getError()) {
  1601. llvm::errs() << EC.message() << "\n";
  1602. break;
  1603. }
  1604. if (std::error_code ec =
  1605. parseConfiguration(Text.get()->getBuffer(), &Style)) {
  1606. if (ec == ParseError::Unsuitable) {
  1607. if (!UnsuitableConfigFiles.empty())
  1608. UnsuitableConfigFiles.append(", ");
  1609. UnsuitableConfigFiles.append(ConfigFile);
  1610. continue;
  1611. }
  1612. llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
  1613. << "\n";
  1614. break;
  1615. }
  1616. DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
  1617. return Style;
  1618. }
  1619. }
  1620. if (!UnsuitableConfigFiles.empty()) {
  1621. llvm::errs() << "Configuration file(s) do(es) not support "
  1622. << getLanguageName(Style.Language) << ": "
  1623. << UnsuitableConfigFiles << "\n";
  1624. }
  1625. return Style;
  1626. }
  1627. } // namespace format
  1628. } // namespace clang