Format.cpp 95 KB

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