Format.cpp 73 KB

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