Format.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118
  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 "ContinuationIndenter.h"
  16. #include "TokenAnnotator.h"
  17. #include "UnwrappedLineParser.h"
  18. #include "WhitespaceManager.h"
  19. #include "clang/Basic/Diagnostic.h"
  20. #include "clang/Basic/DiagnosticOptions.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Format/Format.h"
  23. #include "clang/Lex/Lexer.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/Support/Allocator.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/YAMLTraits.h"
  29. #include <queue>
  30. #include <string>
  31. #define DEBUG_TYPE "format-formatter"
  32. using clang::format::FormatStyle;
  33. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
  34. namespace llvm {
  35. namespace yaml {
  36. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
  37. static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
  38. IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
  39. IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
  40. IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
  41. }
  42. };
  43. template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
  44. static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
  45. IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
  46. IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
  47. IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
  48. IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
  49. IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
  50. }
  51. };
  52. template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
  53. static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
  54. IO.enumCase(Value, "Never", FormatStyle::UT_Never);
  55. IO.enumCase(Value, "false", FormatStyle::UT_Never);
  56. IO.enumCase(Value, "Always", FormatStyle::UT_Always);
  57. IO.enumCase(Value, "true", FormatStyle::UT_Always);
  58. IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
  59. }
  60. };
  61. template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
  62. static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
  63. IO.enumCase(Value, "None", FormatStyle::SFS_None);
  64. IO.enumCase(Value, "false", FormatStyle::SFS_None);
  65. IO.enumCase(Value, "All", FormatStyle::SFS_All);
  66. IO.enumCase(Value, "true", FormatStyle::SFS_All);
  67. IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
  68. }
  69. };
  70. template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
  71. static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
  72. IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
  73. IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
  74. IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
  75. IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
  76. IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
  77. }
  78. };
  79. template <>
  80. struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
  81. static void enumeration(IO &IO,
  82. FormatStyle::NamespaceIndentationKind &Value) {
  83. IO.enumCase(Value, "None", FormatStyle::NI_None);
  84. IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
  85. IO.enumCase(Value, "All", FormatStyle::NI_All);
  86. }
  87. };
  88. template <>
  89. struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
  90. static void enumeration(IO &IO,
  91. FormatStyle::PointerAlignmentStyle &Value) {
  92. IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
  93. IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
  94. IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
  95. // For backward compability.
  96. IO.enumCase(Value, "true", FormatStyle::PAS_Left);
  97. IO.enumCase(Value, "false", FormatStyle::PAS_Right);
  98. }
  99. };
  100. template <>
  101. struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
  102. static void enumeration(IO &IO,
  103. FormatStyle::SpaceBeforeParensOptions &Value) {
  104. IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
  105. IO.enumCase(Value, "ControlStatements",
  106. FormatStyle::SBPO_ControlStatements);
  107. IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
  108. // For backward compatibility.
  109. IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
  110. IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
  111. }
  112. };
  113. template <> struct MappingTraits<FormatStyle> {
  114. static void mapping(IO &IO, FormatStyle &Style) {
  115. // When reading, read the language first, we need it for getPredefinedStyle.
  116. IO.mapOptional("Language", Style.Language);
  117. if (IO.outputting()) {
  118. StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
  119. "Mozilla", "WebKit", "GNU" };
  120. ArrayRef<StringRef> Styles(StylesArray);
  121. for (size_t i = 0, e = Styles.size(); i < e; ++i) {
  122. StringRef StyleName(Styles[i]);
  123. FormatStyle PredefinedStyle;
  124. if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
  125. Style == PredefinedStyle) {
  126. IO.mapOptional("# BasedOnStyle", StyleName);
  127. break;
  128. }
  129. }
  130. } else {
  131. StringRef BasedOnStyle;
  132. IO.mapOptional("BasedOnStyle", BasedOnStyle);
  133. if (!BasedOnStyle.empty()) {
  134. FormatStyle::LanguageKind OldLanguage = Style.Language;
  135. FormatStyle::LanguageKind Language =
  136. ((FormatStyle *)IO.getContext())->Language;
  137. if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
  138. IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
  139. return;
  140. }
  141. Style.Language = OldLanguage;
  142. }
  143. }
  144. IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
  145. IO.mapOptional("ConstructorInitializerIndentWidth",
  146. Style.ConstructorInitializerIndentWidth);
  147. IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
  148. IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
  149. IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
  150. Style.AllowAllParametersOfDeclarationOnNextLine);
  151. IO.mapOptional("AllowShortBlocksOnASingleLine",
  152. Style.AllowShortBlocksOnASingleLine);
  153. IO.mapOptional("AllowShortIfStatementsOnASingleLine",
  154. Style.AllowShortIfStatementsOnASingleLine);
  155. IO.mapOptional("AllowShortLoopsOnASingleLine",
  156. Style.AllowShortLoopsOnASingleLine);
  157. IO.mapOptional("AllowShortFunctionsOnASingleLine",
  158. Style.AllowShortFunctionsOnASingleLine);
  159. IO.mapOptional("AlwaysBreakTemplateDeclarations",
  160. Style.AlwaysBreakTemplateDeclarations);
  161. IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
  162. Style.AlwaysBreakBeforeMultilineStrings);
  163. IO.mapOptional("BreakBeforeBinaryOperators",
  164. Style.BreakBeforeBinaryOperators);
  165. IO.mapOptional("BreakBeforeTernaryOperators",
  166. Style.BreakBeforeTernaryOperators);
  167. IO.mapOptional("BreakConstructorInitializersBeforeComma",
  168. Style.BreakConstructorInitializersBeforeComma);
  169. IO.mapOptional("BinPackParameters", Style.BinPackParameters);
  170. IO.mapOptional("ColumnLimit", Style.ColumnLimit);
  171. IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
  172. Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
  173. IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
  174. IO.mapOptional("ExperimentalAutoDetectBinPacking",
  175. Style.ExperimentalAutoDetectBinPacking);
  176. IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
  177. IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
  178. IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
  179. Style.KeepEmptyLinesAtTheStartOfBlocks);
  180. IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
  181. IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
  182. IO.mapOptional("ObjCSpaceBeforeProtocolList",
  183. Style.ObjCSpaceBeforeProtocolList);
  184. IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
  185. Style.PenaltyBreakBeforeFirstCallParameter);
  186. IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
  187. IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
  188. IO.mapOptional("PenaltyBreakFirstLessLess",
  189. Style.PenaltyBreakFirstLessLess);
  190. IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
  191. IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
  192. Style.PenaltyReturnTypeOnItsOwnLine);
  193. IO.mapOptional("PointerAlignment", Style.PointerAlignment);
  194. IO.mapOptional("SpacesBeforeTrailingComments",
  195. Style.SpacesBeforeTrailingComments);
  196. IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
  197. IO.mapOptional("Standard", Style.Standard);
  198. IO.mapOptional("IndentWidth", Style.IndentWidth);
  199. IO.mapOptional("TabWidth", Style.TabWidth);
  200. IO.mapOptional("UseTab", Style.UseTab);
  201. IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
  202. IO.mapOptional("IndentFunctionDeclarationAfterType",
  203. Style.IndentFunctionDeclarationAfterType);
  204. IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
  205. IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
  206. IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
  207. IO.mapOptional("SpacesInCStyleCastParentheses",
  208. Style.SpacesInCStyleCastParentheses);
  209. IO.mapOptional("SpacesInContainerLiterals",
  210. Style.SpacesInContainerLiterals);
  211. IO.mapOptional("SpaceBeforeAssignmentOperators",
  212. Style.SpaceBeforeAssignmentOperators);
  213. IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
  214. IO.mapOptional("CommentPragmas", Style.CommentPragmas);
  215. IO.mapOptional("ForEachMacros", Style.ForEachMacros);
  216. // For backward compatibility.
  217. if (!IO.outputting()) {
  218. IO.mapOptional("SpaceAfterControlStatementKeyword",
  219. Style.SpaceBeforeParens);
  220. IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
  221. IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
  222. }
  223. IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
  224. IO.mapOptional("DisableFormat", Style.DisableFormat);
  225. }
  226. };
  227. // Allows to read vector<FormatStyle> while keeping default values.
  228. // IO.getContext() should contain a pointer to the FormatStyle structure, that
  229. // will be used to get default values for missing keys.
  230. // If the first element has no Language specified, it will be treated as the
  231. // default one for the following elements.
  232. template <> struct DocumentListTraits<std::vector<FormatStyle> > {
  233. static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
  234. return Seq.size();
  235. }
  236. static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
  237. size_t Index) {
  238. if (Index >= Seq.size()) {
  239. assert(Index == Seq.size());
  240. FormatStyle Template;
  241. if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
  242. Template = Seq[0];
  243. } else {
  244. Template = *((const FormatStyle *)IO.getContext());
  245. Template.Language = FormatStyle::LK_None;
  246. }
  247. Seq.resize(Index + 1, Template);
  248. }
  249. return Seq[Index];
  250. }
  251. };
  252. }
  253. }
  254. namespace clang {
  255. namespace format {
  256. const std::error_category &getParseCategory() {
  257. static ParseErrorCategory C;
  258. return C;
  259. }
  260. std::error_code make_error_code(ParseError e) {
  261. return std::error_code(static_cast<int>(e), getParseCategory());
  262. }
  263. const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
  264. return "clang-format.parse_error";
  265. }
  266. std::string ParseErrorCategory::message(int EV) const {
  267. switch (static_cast<ParseError>(EV)) {
  268. case ParseError::Success:
  269. return "Success";
  270. case ParseError::Error:
  271. return "Invalid argument";
  272. case ParseError::Unsuitable:
  273. return "Unsuitable";
  274. }
  275. llvm_unreachable("unexpected parse error");
  276. }
  277. FormatStyle getLLVMStyle() {
  278. FormatStyle LLVMStyle;
  279. LLVMStyle.Language = FormatStyle::LK_Cpp;
  280. LLVMStyle.AccessModifierOffset = -2;
  281. LLVMStyle.AlignEscapedNewlinesLeft = false;
  282. LLVMStyle.AlignTrailingComments = true;
  283. LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
  284. LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
  285. LLVMStyle.AllowShortBlocksOnASingleLine = false;
  286. LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
  287. LLVMStyle.AllowShortLoopsOnASingleLine = false;
  288. LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
  289. LLVMStyle.AlwaysBreakTemplateDeclarations = false;
  290. LLVMStyle.BinPackParameters = true;
  291. LLVMStyle.BreakBeforeBinaryOperators = false;
  292. LLVMStyle.BreakBeforeTernaryOperators = true;
  293. LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
  294. LLVMStyle.BreakConstructorInitializersBeforeComma = false;
  295. LLVMStyle.ColumnLimit = 80;
  296. LLVMStyle.CommentPragmas = "^ IWYU pragma:";
  297. LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
  298. LLVMStyle.ConstructorInitializerIndentWidth = 4;
  299. LLVMStyle.ContinuationIndentWidth = 4;
  300. LLVMStyle.Cpp11BracedListStyle = true;
  301. LLVMStyle.DerivePointerAlignment = false;
  302. LLVMStyle.ExperimentalAutoDetectBinPacking = false;
  303. LLVMStyle.ForEachMacros.push_back("foreach");
  304. LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
  305. LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
  306. LLVMStyle.IndentCaseLabels = false;
  307. LLVMStyle.IndentFunctionDeclarationAfterType = false;
  308. LLVMStyle.IndentWidth = 2;
  309. LLVMStyle.TabWidth = 8;
  310. LLVMStyle.MaxEmptyLinesToKeep = 1;
  311. LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
  312. LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
  313. LLVMStyle.ObjCSpaceAfterProperty = false;
  314. LLVMStyle.ObjCSpaceBeforeProtocolList = true;
  315. LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
  316. LLVMStyle.SpacesBeforeTrailingComments = 1;
  317. LLVMStyle.Standard = FormatStyle::LS_Cpp11;
  318. LLVMStyle.UseTab = FormatStyle::UT_Never;
  319. LLVMStyle.SpacesInParentheses = false;
  320. LLVMStyle.SpaceInEmptyParentheses = false;
  321. LLVMStyle.SpacesInContainerLiterals = true;
  322. LLVMStyle.SpacesInCStyleCastParentheses = false;
  323. LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
  324. LLVMStyle.SpaceBeforeAssignmentOperators = true;
  325. LLVMStyle.SpacesInAngles = false;
  326. LLVMStyle.PenaltyBreakComment = 300;
  327. LLVMStyle.PenaltyBreakFirstLessLess = 120;
  328. LLVMStyle.PenaltyBreakString = 1000;
  329. LLVMStyle.PenaltyExcessCharacter = 1000000;
  330. LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
  331. LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
  332. LLVMStyle.DisableFormat = false;
  333. return LLVMStyle;
  334. }
  335. FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
  336. FormatStyle GoogleStyle = getLLVMStyle();
  337. GoogleStyle.Language = Language;
  338. GoogleStyle.AccessModifierOffset = -1;
  339. GoogleStyle.AlignEscapedNewlinesLeft = true;
  340. GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
  341. GoogleStyle.AllowShortLoopsOnASingleLine = true;
  342. GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
  343. GoogleStyle.AlwaysBreakTemplateDeclarations = true;
  344. GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
  345. GoogleStyle.DerivePointerAlignment = true;
  346. GoogleStyle.IndentCaseLabels = true;
  347. GoogleStyle.IndentFunctionDeclarationAfterType = true;
  348. GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
  349. GoogleStyle.ObjCSpaceAfterProperty = false;
  350. GoogleStyle.ObjCSpaceBeforeProtocolList = false;
  351. GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
  352. GoogleStyle.SpacesBeforeTrailingComments = 2;
  353. GoogleStyle.Standard = FormatStyle::LS_Auto;
  354. GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  355. GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
  356. if (Language == FormatStyle::LK_JavaScript) {
  357. GoogleStyle.BreakBeforeTernaryOperators = false;
  358. GoogleStyle.MaxEmptyLinesToKeep = 3;
  359. GoogleStyle.SpacesInContainerLiterals = false;
  360. } else if (Language == FormatStyle::LK_Proto) {
  361. GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
  362. GoogleStyle.SpacesInContainerLiterals = false;
  363. }
  364. return GoogleStyle;
  365. }
  366. FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
  367. FormatStyle ChromiumStyle = getGoogleStyle(Language);
  368. ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  369. ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
  370. ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
  371. ChromiumStyle.AllowShortLoopsOnASingleLine = false;
  372. ChromiumStyle.BinPackParameters = false;
  373. ChromiumStyle.DerivePointerAlignment = false;
  374. ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
  375. return ChromiumStyle;
  376. }
  377. FormatStyle getMozillaStyle() {
  378. FormatStyle MozillaStyle = getLLVMStyle();
  379. MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
  380. MozillaStyle.Cpp11BracedListStyle = false;
  381. MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
  382. MozillaStyle.DerivePointerAlignment = true;
  383. MozillaStyle.IndentCaseLabels = true;
  384. MozillaStyle.ObjCSpaceAfterProperty = true;
  385. MozillaStyle.ObjCSpaceBeforeProtocolList = false;
  386. MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
  387. MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
  388. MozillaStyle.Standard = FormatStyle::LS_Cpp03;
  389. return MozillaStyle;
  390. }
  391. FormatStyle getWebKitStyle() {
  392. FormatStyle Style = getLLVMStyle();
  393. Style.AccessModifierOffset = -4;
  394. Style.AlignTrailingComments = false;
  395. Style.BreakBeforeBinaryOperators = true;
  396. Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
  397. Style.BreakConstructorInitializersBeforeComma = true;
  398. Style.Cpp11BracedListStyle = false;
  399. Style.ColumnLimit = 0;
  400. Style.IndentWidth = 4;
  401. Style.NamespaceIndentation = FormatStyle::NI_Inner;
  402. Style.ObjCSpaceAfterProperty = true;
  403. Style.PointerAlignment = FormatStyle::PAS_Left;
  404. Style.Standard = FormatStyle::LS_Cpp03;
  405. return Style;
  406. }
  407. FormatStyle getGNUStyle() {
  408. FormatStyle Style = getLLVMStyle();
  409. Style.BreakBeforeBinaryOperators = true;
  410. Style.BreakBeforeBraces = FormatStyle::BS_GNU;
  411. Style.BreakBeforeTernaryOperators = true;
  412. Style.Cpp11BracedListStyle = false;
  413. Style.ColumnLimit = 79;
  414. Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
  415. Style.Standard = FormatStyle::LS_Cpp03;
  416. return Style;
  417. }
  418. FormatStyle getNoStyle() {
  419. FormatStyle NoStyle = getLLVMStyle();
  420. NoStyle.DisableFormat = true;
  421. return NoStyle;
  422. }
  423. bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
  424. FormatStyle *Style) {
  425. if (Name.equals_lower("llvm")) {
  426. *Style = getLLVMStyle();
  427. } else if (Name.equals_lower("chromium")) {
  428. *Style = getChromiumStyle(Language);
  429. } else if (Name.equals_lower("mozilla")) {
  430. *Style = getMozillaStyle();
  431. } else if (Name.equals_lower("google")) {
  432. *Style = getGoogleStyle(Language);
  433. } else if (Name.equals_lower("webkit")) {
  434. *Style = getWebKitStyle();
  435. } else if (Name.equals_lower("gnu")) {
  436. *Style = getGNUStyle();
  437. } else if (Name.equals_lower("none")) {
  438. *Style = getNoStyle();
  439. } else {
  440. return false;
  441. }
  442. Style->Language = Language;
  443. return true;
  444. }
  445. std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
  446. assert(Style);
  447. FormatStyle::LanguageKind Language = Style->Language;
  448. assert(Language != FormatStyle::LK_None);
  449. if (Text.trim().empty())
  450. return make_error_code(ParseError::Error);
  451. std::vector<FormatStyle> Styles;
  452. llvm::yaml::Input Input(Text);
  453. // DocumentListTraits<vector<FormatStyle>> uses the context to get default
  454. // values for the fields, keys for which are missing from the configuration.
  455. // Mapping also uses the context to get the language to find the correct
  456. // base style.
  457. Input.setContext(Style);
  458. Input >> Styles;
  459. if (Input.error())
  460. return Input.error();
  461. for (unsigned i = 0; i < Styles.size(); ++i) {
  462. // Ensures that only the first configuration can skip the Language option.
  463. if (Styles[i].Language == FormatStyle::LK_None && i != 0)
  464. return make_error_code(ParseError::Error);
  465. // Ensure that each language is configured at most once.
  466. for (unsigned j = 0; j < i; ++j) {
  467. if (Styles[i].Language == Styles[j].Language) {
  468. DEBUG(llvm::dbgs()
  469. << "Duplicate languages in the config file on positions " << j
  470. << " and " << i << "\n");
  471. return make_error_code(ParseError::Error);
  472. }
  473. }
  474. }
  475. // Look for a suitable configuration starting from the end, so we can
  476. // find the configuration for the specific language first, and the default
  477. // configuration (which can only be at slot 0) after it.
  478. for (int i = Styles.size() - 1; i >= 0; --i) {
  479. if (Styles[i].Language == Language ||
  480. Styles[i].Language == FormatStyle::LK_None) {
  481. *Style = Styles[i];
  482. Style->Language = Language;
  483. return make_error_code(ParseError::Success);
  484. }
  485. }
  486. return make_error_code(ParseError::Unsuitable);
  487. }
  488. std::string configurationAsText(const FormatStyle &Style) {
  489. std::string Text;
  490. llvm::raw_string_ostream Stream(Text);
  491. llvm::yaml::Output Output(Stream);
  492. // We use the same mapping method for input and output, so we need a non-const
  493. // reference here.
  494. FormatStyle NonConstStyle = Style;
  495. Output << NonConstStyle;
  496. return Stream.str();
  497. }
  498. namespace {
  499. class NoColumnLimitFormatter {
  500. public:
  501. NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
  502. /// \brief Formats the line starting at \p State, simply keeping all of the
  503. /// input's line breaking decisions.
  504. void format(unsigned FirstIndent, const AnnotatedLine *Line) {
  505. LineState State =
  506. Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
  507. while (State.NextToken) {
  508. bool Newline =
  509. Indenter->mustBreak(State) ||
  510. (Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
  511. Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
  512. }
  513. }
  514. private:
  515. ContinuationIndenter *Indenter;
  516. };
  517. class LineJoiner {
  518. public:
  519. LineJoiner(const FormatStyle &Style) : Style(Style) {}
  520. /// \brief Calculates how many lines can be merged into 1 starting at \p I.
  521. unsigned
  522. tryFitMultipleLinesInOne(unsigned Indent,
  523. SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  524. SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
  525. // We can never merge stuff if there are trailing line comments.
  526. const AnnotatedLine *TheLine = *I;
  527. if (TheLine->Last->Type == TT_LineComment)
  528. return 0;
  529. if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
  530. return 0;
  531. unsigned Limit =
  532. Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
  533. // If we already exceed the column limit, we set 'Limit' to 0. The different
  534. // tryMerge..() functions can then decide whether to still do merging.
  535. Limit = TheLine->Last->TotalLength > Limit
  536. ? 0
  537. : Limit - TheLine->Last->TotalLength;
  538. if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
  539. return 0;
  540. // FIXME: TheLine->Level != 0 might or might not be the right check to do.
  541. // If necessary, change to something smarter.
  542. bool MergeShortFunctions =
  543. Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
  544. (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
  545. TheLine->Level != 0);
  546. if (TheLine->Last->Type == TT_FunctionLBrace &&
  547. TheLine->First != TheLine->Last) {
  548. return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
  549. }
  550. if (TheLine->Last->is(tok::l_brace)) {
  551. return Style.BreakBeforeBraces == FormatStyle::BS_Attach
  552. ? tryMergeSimpleBlock(I, E, Limit)
  553. : 0;
  554. }
  555. if (I[1]->First->Type == TT_FunctionLBrace &&
  556. Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
  557. // Check for Limit <= 2 to account for the " {".
  558. if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
  559. return 0;
  560. Limit -= 2;
  561. unsigned MergedLines = 0;
  562. if (MergeShortFunctions) {
  563. MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
  564. // If we managed to merge the block, count the function header, which is
  565. // on a separate line.
  566. if (MergedLines > 0)
  567. ++MergedLines;
  568. }
  569. return MergedLines;
  570. }
  571. if (TheLine->First->is(tok::kw_if)) {
  572. return Style.AllowShortIfStatementsOnASingleLine
  573. ? tryMergeSimpleControlStatement(I, E, Limit)
  574. : 0;
  575. }
  576. if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
  577. return Style.AllowShortLoopsOnASingleLine
  578. ? tryMergeSimpleControlStatement(I, E, Limit)
  579. : 0;
  580. }
  581. if (TheLine->InPPDirective &&
  582. (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
  583. return tryMergeSimplePPDirective(I, E, Limit);
  584. }
  585. return 0;
  586. }
  587. private:
  588. unsigned
  589. tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  590. SmallVectorImpl<AnnotatedLine *>::const_iterator E,
  591. unsigned Limit) {
  592. if (Limit == 0)
  593. return 0;
  594. if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
  595. return 0;
  596. if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
  597. return 0;
  598. if (1 + I[1]->Last->TotalLength > Limit)
  599. return 0;
  600. return 1;
  601. }
  602. unsigned tryMergeSimpleControlStatement(
  603. SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  604. SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
  605. if (Limit == 0)
  606. return 0;
  607. if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
  608. Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
  609. (I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
  610. return 0;
  611. if (I[1]->InPPDirective != (*I)->InPPDirective ||
  612. (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
  613. return 0;
  614. Limit = limitConsideringMacros(I + 1, E, Limit);
  615. AnnotatedLine &Line = **I;
  616. if (Line.Last->isNot(tok::r_paren))
  617. return 0;
  618. if (1 + I[1]->Last->TotalLength > Limit)
  619. return 0;
  620. if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
  621. tok::kw_while) ||
  622. I[1]->First->Type == TT_LineComment)
  623. return 0;
  624. // Only inline simple if's (no nested if or else).
  625. if (I + 2 != E && Line.First->is(tok::kw_if) &&
  626. I[2]->First->is(tok::kw_else))
  627. return 0;
  628. return 1;
  629. }
  630. unsigned
  631. tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  632. SmallVectorImpl<AnnotatedLine *>::const_iterator E,
  633. unsigned Limit) {
  634. AnnotatedLine &Line = **I;
  635. // Don't merge ObjC @ keywords and methods.
  636. if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
  637. return 0;
  638. // Check that the current line allows merging. This depends on whether we
  639. // are in a control flow statements as well as several style flags.
  640. if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
  641. return 0;
  642. if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
  643. tok::kw_catch, tok::kw_for, tok::r_brace)) {
  644. if (!Style.AllowShortBlocksOnASingleLine)
  645. return 0;
  646. if (!Style.AllowShortIfStatementsOnASingleLine &&
  647. Line.First->is(tok::kw_if))
  648. return 0;
  649. if (!Style.AllowShortLoopsOnASingleLine &&
  650. Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
  651. return 0;
  652. // FIXME: Consider an option to allow short exception handling clauses on
  653. // a single line.
  654. if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
  655. return 0;
  656. }
  657. FormatToken *Tok = I[1]->First;
  658. if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
  659. (Tok->getNextNonComment() == nullptr ||
  660. Tok->getNextNonComment()->is(tok::semi))) {
  661. // We merge empty blocks even if the line exceeds the column limit.
  662. Tok->SpacesRequiredBefore = 0;
  663. Tok->CanBreakBefore = true;
  664. return 1;
  665. } else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
  666. // We don't merge short records.
  667. if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
  668. return 0;
  669. // Check that we still have three lines and they fit into the limit.
  670. if (I + 2 == E || I[2]->Type == LT_Invalid)
  671. return 0;
  672. Limit = limitConsideringMacros(I + 2, E, Limit);
  673. if (!nextTwoLinesFitInto(I, Limit))
  674. return 0;
  675. // Second, check that the next line does not contain any braces - if it
  676. // does, readability declines when putting it into a single line.
  677. if (I[1]->Last->Type == TT_LineComment)
  678. return 0;
  679. do {
  680. if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
  681. return 0;
  682. Tok = Tok->Next;
  683. } while (Tok);
  684. // Last, check that the third line starts with a closing brace.
  685. Tok = I[2]->First;
  686. if (Tok->isNot(tok::r_brace))
  687. return 0;
  688. return 2;
  689. }
  690. return 0;
  691. }
  692. /// Returns the modified column limit for \p I if it is inside a macro and
  693. /// needs a trailing '\'.
  694. unsigned
  695. limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  696. SmallVectorImpl<AnnotatedLine *>::const_iterator E,
  697. unsigned Limit) {
  698. if (I[0]->InPPDirective && I + 1 != E &&
  699. !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
  700. return Limit < 2 ? 0 : Limit - 2;
  701. }
  702. return Limit;
  703. }
  704. bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
  705. unsigned Limit) {
  706. if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
  707. return false;
  708. return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
  709. }
  710. bool containsMustBreak(const AnnotatedLine *Line) {
  711. for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
  712. if (Tok->MustBreakBefore)
  713. return true;
  714. }
  715. return false;
  716. }
  717. const FormatStyle &Style;
  718. };
  719. class UnwrappedLineFormatter {
  720. public:
  721. UnwrappedLineFormatter(ContinuationIndenter *Indenter,
  722. WhitespaceManager *Whitespaces,
  723. const FormatStyle &Style)
  724. : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
  725. Joiner(Style) {}
  726. unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
  727. int AdditionalIndent = 0, bool FixBadIndentation = false) {
  728. // Try to look up already computed penalty in DryRun-mode.
  729. std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
  730. &Lines, AdditionalIndent);
  731. auto CacheIt = PenaltyCache.find(CacheKey);
  732. if (DryRun && CacheIt != PenaltyCache.end())
  733. return CacheIt->second;
  734. assert(!Lines.empty());
  735. unsigned Penalty = 0;
  736. std::vector<int> IndentForLevel;
  737. for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
  738. IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
  739. const AnnotatedLine *PreviousLine = nullptr;
  740. for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
  741. E = Lines.end();
  742. I != E; ++I) {
  743. const AnnotatedLine &TheLine = **I;
  744. const FormatToken *FirstTok = TheLine.First;
  745. int Offset = getIndentOffset(*FirstTok);
  746. // Determine indent and try to merge multiple unwrapped lines.
  747. unsigned Indent;
  748. if (TheLine.InPPDirective) {
  749. Indent = TheLine.Level * Style.IndentWidth;
  750. } else {
  751. while (IndentForLevel.size() <= TheLine.Level)
  752. IndentForLevel.push_back(-1);
  753. IndentForLevel.resize(TheLine.Level + 1);
  754. Indent = getIndent(IndentForLevel, TheLine.Level);
  755. }
  756. unsigned LevelIndent = Indent;
  757. if (static_cast<int>(Indent) + Offset >= 0)
  758. Indent += Offset;
  759. // Merge multiple lines if possible.
  760. unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
  761. if (MergedLines > 0 && Style.ColumnLimit == 0) {
  762. // Disallow line merging if there is a break at the start of one of the
  763. // input lines.
  764. for (unsigned i = 0; i < MergedLines; ++i) {
  765. if (I[i + 1]->First->NewlinesBefore > 0)
  766. MergedLines = 0;
  767. }
  768. }
  769. if (!DryRun) {
  770. for (unsigned i = 0; i < MergedLines; ++i) {
  771. join(*I[i], *I[i + 1]);
  772. }
  773. }
  774. I += MergedLines;
  775. bool FixIndentation =
  776. FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
  777. if (TheLine.First->is(tok::eof)) {
  778. if (PreviousLine && PreviousLine->Affected && !DryRun) {
  779. // Remove the file's trailing whitespace.
  780. unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
  781. Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
  782. /*IndentLevel=*/0, /*Spaces=*/0,
  783. /*TargetColumn=*/0);
  784. }
  785. } else if (TheLine.Type != LT_Invalid &&
  786. (TheLine.Affected || FixIndentation)) {
  787. if (FirstTok->WhitespaceRange.isValid()) {
  788. if (!DryRun)
  789. formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
  790. Indent, TheLine.InPPDirective);
  791. } else {
  792. Indent = LevelIndent = FirstTok->OriginalColumn;
  793. }
  794. // If everything fits on a single line, just put it there.
  795. unsigned ColumnLimit = Style.ColumnLimit;
  796. if (I + 1 != E) {
  797. AnnotatedLine *NextLine = I[1];
  798. if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
  799. ColumnLimit = getColumnLimit(TheLine.InPPDirective);
  800. }
  801. if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
  802. LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
  803. while (State.NextToken) {
  804. formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
  805. Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
  806. }
  807. } else if (Style.ColumnLimit == 0) {
  808. // FIXME: Implement nested blocks for ColumnLimit = 0.
  809. NoColumnLimitFormatter Formatter(Indenter);
  810. if (!DryRun)
  811. Formatter.format(Indent, &TheLine);
  812. } else {
  813. Penalty += format(TheLine, Indent, DryRun);
  814. }
  815. if (!TheLine.InPPDirective)
  816. IndentForLevel[TheLine.Level] = LevelIndent;
  817. } else if (TheLine.ChildrenAffected) {
  818. format(TheLine.Children, DryRun);
  819. } else {
  820. // Format the first token if necessary, and notify the WhitespaceManager
  821. // about the unchanged whitespace.
  822. for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
  823. if (Tok == TheLine.First &&
  824. (Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
  825. unsigned LevelIndent = Tok->OriginalColumn;
  826. if (!DryRun) {
  827. // Remove trailing whitespace of the previous line.
  828. if ((PreviousLine && PreviousLine->Affected) ||
  829. TheLine.LeadingEmptyLinesAffected) {
  830. formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
  831. TheLine.InPPDirective);
  832. } else {
  833. Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
  834. }
  835. }
  836. if (static_cast<int>(LevelIndent) - Offset >= 0)
  837. LevelIndent -= Offset;
  838. if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
  839. IndentForLevel[TheLine.Level] = LevelIndent;
  840. } else if (!DryRun) {
  841. Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
  842. }
  843. }
  844. }
  845. if (!DryRun) {
  846. for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
  847. Tok->Finalized = true;
  848. }
  849. }
  850. PreviousLine = *I;
  851. }
  852. PenaltyCache[CacheKey] = Penalty;
  853. return Penalty;
  854. }
  855. private:
  856. /// \brief Formats an \c AnnotatedLine and returns the penalty.
  857. ///
  858. /// If \p DryRun is \c false, directly applies the changes.
  859. unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
  860. bool DryRun) {
  861. LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
  862. // If the ObjC method declaration does not fit on a line, we should format
  863. // it with one arg per line.
  864. if (State.Line->Type == LT_ObjCMethodDecl)
  865. State.Stack.back().BreakBeforeParameter = true;
  866. // Find best solution in solution space.
  867. return analyzeSolutionSpace(State, DryRun);
  868. }
  869. /// \brief An edge in the solution space from \c Previous->State to \c State,
  870. /// inserting a newline dependent on the \c NewLine.
  871. struct StateNode {
  872. StateNode(const LineState &State, bool NewLine, StateNode *Previous)
  873. : State(State), NewLine(NewLine), Previous(Previous) {}
  874. LineState State;
  875. bool NewLine;
  876. StateNode *Previous;
  877. };
  878. /// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
  879. ///
  880. /// In case of equal penalties, we want to prefer states that were inserted
  881. /// first. During state generation we make sure that we insert states first
  882. /// that break the line as late as possible.
  883. typedef std::pair<unsigned, unsigned> OrderedPenalty;
  884. /// \brief An item in the prioritized BFS search queue. The \c StateNode's
  885. /// \c State has the given \c OrderedPenalty.
  886. typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
  887. /// \brief The BFS queue type.
  888. typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
  889. std::greater<QueueItem> > QueueType;
  890. /// \brief Get the offset of the line relatively to the level.
  891. ///
  892. /// For example, 'public:' labels in classes are offset by 1 or 2
  893. /// characters to the left from their level.
  894. int getIndentOffset(const FormatToken &RootToken) {
  895. if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
  896. return Style.AccessModifierOffset;
  897. return 0;
  898. }
  899. /// \brief Add a new line and the required indent before the first Token
  900. /// of the \c UnwrappedLine if there was no structural parsing error.
  901. void formatFirstToken(FormatToken &RootToken,
  902. const AnnotatedLine *PreviousLine, unsigned IndentLevel,
  903. unsigned Indent, bool InPPDirective) {
  904. unsigned Newlines =
  905. std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
  906. // Remove empty lines before "}" where applicable.
  907. if (RootToken.is(tok::r_brace) &&
  908. (!RootToken.Next ||
  909. (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
  910. Newlines = std::min(Newlines, 1u);
  911. if (Newlines == 0 && !RootToken.IsFirst)
  912. Newlines = 1;
  913. if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
  914. Newlines = 0;
  915. // Remove empty lines after "{".
  916. if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
  917. PreviousLine->Last->is(tok::l_brace) &&
  918. PreviousLine->First->isNot(tok::kw_namespace))
  919. Newlines = 1;
  920. // Insert extra new line before access specifiers.
  921. if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
  922. RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
  923. ++Newlines;
  924. // Remove empty lines after access specifiers.
  925. if (PreviousLine && PreviousLine->First->isAccessSpecifier())
  926. Newlines = std::min(1u, Newlines);
  927. Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
  928. Indent, InPPDirective &&
  929. !RootToken.HasUnescapedNewline);
  930. }
  931. /// \brief Get the indent of \p Level from \p IndentForLevel.
  932. ///
  933. /// \p IndentForLevel must contain the indent for the level \c l
  934. /// at \p IndentForLevel[l], or a value < 0 if the indent for
  935. /// that level is unknown.
  936. unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
  937. if (IndentForLevel[Level] != -1)
  938. return IndentForLevel[Level];
  939. if (Level == 0)
  940. return 0;
  941. return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
  942. }
  943. void join(AnnotatedLine &A, const AnnotatedLine &B) {
  944. assert(!A.Last->Next);
  945. assert(!B.First->Previous);
  946. if (B.Affected)
  947. A.Affected = true;
  948. A.Last->Next = B.First;
  949. B.First->Previous = A.Last;
  950. B.First->CanBreakBefore = true;
  951. unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
  952. for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
  953. Tok->TotalLength += LengthA;
  954. A.Last = Tok;
  955. }
  956. }
  957. unsigned getColumnLimit(bool InPPDirective) const {
  958. // In preprocessor directives reserve two chars for trailing " \"
  959. return Style.ColumnLimit - (InPPDirective ? 2 : 0);
  960. }
  961. struct CompareLineStatePointers {
  962. bool operator()(LineState *obj1, LineState *obj2) const {
  963. return *obj1 < *obj2;
  964. }
  965. };
  966. /// \brief Analyze the entire solution space starting from \p InitialState.
  967. ///
  968. /// This implements a variant of Dijkstra's algorithm on the graph that spans
  969. /// the solution space (\c LineStates are the nodes). The algorithm tries to
  970. /// find the shortest path (the one with lowest penalty) from \p InitialState
  971. /// to a state where all tokens are placed. Returns the penalty.
  972. ///
  973. /// If \p DryRun is \c false, directly applies the changes.
  974. unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
  975. std::set<LineState *, CompareLineStatePointers> Seen;
  976. // Increasing count of \c StateNode items we have created. This is used to
  977. // create a deterministic order independent of the container.
  978. unsigned Count = 0;
  979. QueueType Queue;
  980. // Insert start element into queue.
  981. StateNode *Node =
  982. new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
  983. Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
  984. ++Count;
  985. unsigned Penalty = 0;
  986. // While not empty, take first element and follow edges.
  987. while (!Queue.empty()) {
  988. Penalty = Queue.top().first.first;
  989. StateNode *Node = Queue.top().second;
  990. if (!Node->State.NextToken) {
  991. DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
  992. break;
  993. }
  994. Queue.pop();
  995. // Cut off the analysis of certain solutions if the analysis gets too
  996. // complex. See description of IgnoreStackForComparison.
  997. if (Count > 10000)
  998. Node->State.IgnoreStackForComparison = true;
  999. if (!Seen.insert(&Node->State).second)
  1000. // State already examined with lower penalty.
  1001. continue;
  1002. FormatDecision LastFormat = Node->State.NextToken->Decision;
  1003. if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
  1004. addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
  1005. if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
  1006. addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
  1007. }
  1008. if (Queue.empty()) {
  1009. // We were unable to find a solution, do nothing.
  1010. // FIXME: Add diagnostic?
  1011. DEBUG(llvm::dbgs() << "Could not find a solution.\n");
  1012. return 0;
  1013. }
  1014. // Reconstruct the solution.
  1015. if (!DryRun)
  1016. reconstructPath(InitialState, Queue.top().second);
  1017. DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
  1018. DEBUG(llvm::dbgs() << "---\n");
  1019. return Penalty;
  1020. }
  1021. void reconstructPath(LineState &State, StateNode *Current) {
  1022. std::deque<StateNode *> Path;
  1023. // We do not need a break before the initial token.
  1024. while (Current->Previous) {
  1025. Path.push_front(Current);
  1026. Current = Current->Previous;
  1027. }
  1028. for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
  1029. I != E; ++I) {
  1030. unsigned Penalty = 0;
  1031. formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
  1032. Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
  1033. DEBUG({
  1034. if ((*I)->NewLine) {
  1035. llvm::dbgs() << "Penalty for placing "
  1036. << (*I)->Previous->State.NextToken->Tok.getName() << ": "
  1037. << Penalty << "\n";
  1038. }
  1039. });
  1040. }
  1041. }
  1042. /// \brief Add the following state to the analysis queue \c Queue.
  1043. ///
  1044. /// Assume the current state is \p PreviousNode and has been reached with a
  1045. /// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
  1046. void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
  1047. bool NewLine, unsigned *Count, QueueType *Queue) {
  1048. if (NewLine && !Indenter->canBreak(PreviousNode->State))
  1049. return;
  1050. if (!NewLine && Indenter->mustBreak(PreviousNode->State))
  1051. return;
  1052. StateNode *Node = new (Allocator.Allocate())
  1053. StateNode(PreviousNode->State, NewLine, PreviousNode);
  1054. if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
  1055. return;
  1056. Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
  1057. Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
  1058. ++(*Count);
  1059. }
  1060. /// \brief If the \p State's next token is an r_brace closing a nested block,
  1061. /// format the nested block before it.
  1062. ///
  1063. /// Returns \c true if all children could be placed successfully and adapts
  1064. /// \p Penalty as well as \p State. If \p DryRun is false, also directly
  1065. /// creates changes using \c Whitespaces.
  1066. ///
  1067. /// The crucial idea here is that children always get formatted upon
  1068. /// encountering the closing brace right after the nested block. Now, if we
  1069. /// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
  1070. /// \c false), the entire block has to be kept on the same line (which is only
  1071. /// possible if it fits on the line, only contains a single statement, etc.
  1072. ///
  1073. /// If \p NewLine is true, we format the nested block on separate lines, i.e.
  1074. /// break after the "{", format all lines with correct indentation and the put
  1075. /// the closing "}" on yet another new line.
  1076. ///
  1077. /// This enables us to keep the simple structure of the
  1078. /// \c UnwrappedLineFormatter, where we only have two options for each token:
  1079. /// break or don't break.
  1080. bool formatChildren(LineState &State, bool NewLine, bool DryRun,
  1081. unsigned &Penalty) {
  1082. FormatToken &Previous = *State.NextToken->Previous;
  1083. const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
  1084. if (!LBrace || LBrace->isNot(tok::l_brace) ||
  1085. LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
  1086. // The previous token does not open a block. Nothing to do. We don't
  1087. // assert so that we can simply call this function for all tokens.
  1088. return true;
  1089. if (NewLine) {
  1090. int AdditionalIndent =
  1091. State.FirstIndent - State.Line->Level * Style.IndentWidth;
  1092. if (State.Stack.size() < 2 ||
  1093. !State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
  1094. AdditionalIndent = State.Stack.back().Indent -
  1095. Previous.Children[0]->Level * Style.IndentWidth;
  1096. }
  1097. Penalty += format(Previous.Children, DryRun, AdditionalIndent,
  1098. /*FixBadIndentation=*/true);
  1099. return true;
  1100. }
  1101. // Cannot merge multiple statements into a single line.
  1102. if (Previous.Children.size() > 1)
  1103. return false;
  1104. // Cannot merge into one line if this line ends on a comment.
  1105. if (Previous.is(tok::comment))
  1106. return false;
  1107. // We can't put the closing "}" on a line with a trailing comment.
  1108. if (Previous.Children[0]->Last->isTrailingComment())
  1109. return false;
  1110. // If the child line exceeds the column limit, we wouldn't want to merge it.
  1111. // We add +2 for the trailing " }".
  1112. if (Style.ColumnLimit > 0 &&
  1113. Previous.Children[0]->Last->TotalLength + State.Column + 2 >
  1114. Style.ColumnLimit)
  1115. return false;
  1116. if (!DryRun) {
  1117. Whitespaces->replaceWhitespace(
  1118. *Previous.Children[0]->First,
  1119. /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
  1120. /*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
  1121. }
  1122. Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
  1123. State.Column += 1 + Previous.Children[0]->Last->TotalLength;
  1124. return true;
  1125. }
  1126. ContinuationIndenter *Indenter;
  1127. WhitespaceManager *Whitespaces;
  1128. FormatStyle Style;
  1129. LineJoiner Joiner;
  1130. llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
  1131. // Cache to store the penalty of formatting a vector of AnnotatedLines
  1132. // starting from a specific additional offset. Improves performance if there
  1133. // are many nested blocks.
  1134. std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
  1135. unsigned> PenaltyCache;
  1136. };
  1137. class FormatTokenLexer {
  1138. public:
  1139. FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
  1140. encoding::Encoding Encoding)
  1141. : FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
  1142. Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
  1143. Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
  1144. FirstInLineIndex(0) {
  1145. Lex.SetKeepWhitespaceMode(true);
  1146. for (const std::string &ForEachMacro : Style.ForEachMacros)
  1147. ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
  1148. std::sort(ForEachMacros.begin(), ForEachMacros.end());
  1149. }
  1150. ArrayRef<FormatToken *> lex() {
  1151. assert(Tokens.empty());
  1152. assert(FirstInLineIndex == 0);
  1153. do {
  1154. Tokens.push_back(getNextToken());
  1155. tryMergePreviousTokens();
  1156. if (Tokens.back()->NewlinesBefore > 0)
  1157. FirstInLineIndex = Tokens.size() - 1;
  1158. } while (Tokens.back()->Tok.isNot(tok::eof));
  1159. return Tokens;
  1160. }
  1161. IdentifierTable &getIdentTable() { return IdentTable; }
  1162. private:
  1163. void tryMergePreviousTokens() {
  1164. if (tryMerge_TMacro())
  1165. return;
  1166. if (tryMergeConflictMarkers())
  1167. return;
  1168. if (Style.Language == FormatStyle::LK_JavaScript) {
  1169. if (tryMergeEscapeSequence())
  1170. return;
  1171. if (tryMergeJSRegexLiteral())
  1172. return;
  1173. static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
  1174. static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
  1175. static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
  1176. tok::greaterequal };
  1177. static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
  1178. // FIXME: We probably need to change token type to mimic operator with the
  1179. // correct priority.
  1180. if (tryMergeTokens(JSIdentity))
  1181. return;
  1182. if (tryMergeTokens(JSNotIdentity))
  1183. return;
  1184. if (tryMergeTokens(JSShiftEqual))
  1185. return;
  1186. if (tryMergeTokens(JSRightArrow))
  1187. return;
  1188. }
  1189. }
  1190. bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
  1191. if (Tokens.size() < Kinds.size())
  1192. return false;
  1193. SmallVectorImpl<FormatToken *>::const_iterator First =
  1194. Tokens.end() - Kinds.size();
  1195. if (!First[0]->is(Kinds[0]))
  1196. return false;
  1197. unsigned AddLength = 0;
  1198. for (unsigned i = 1; i < Kinds.size(); ++i) {
  1199. if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
  1200. First[i]->WhitespaceRange.getEnd())
  1201. return false;
  1202. AddLength += First[i]->TokenText.size();
  1203. }
  1204. Tokens.resize(Tokens.size() - Kinds.size() + 1);
  1205. First[0]->TokenText = StringRef(First[0]->TokenText.data(),
  1206. First[0]->TokenText.size() + AddLength);
  1207. First[0]->ColumnWidth += AddLength;
  1208. return true;
  1209. }
  1210. // Tries to merge an escape sequence, i.e. a "\\" and the following
  1211. // character. Use e.g. inside JavaScript regex literals.
  1212. bool tryMergeEscapeSequence() {
  1213. if (Tokens.size() < 2)
  1214. return false;
  1215. FormatToken *Previous = Tokens[Tokens.size() - 2];
  1216. if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
  1217. Tokens.back()->NewlinesBefore != 0)
  1218. return false;
  1219. Previous->ColumnWidth += Tokens.back()->ColumnWidth;
  1220. StringRef Text = Previous->TokenText;
  1221. Previous->TokenText =
  1222. StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
  1223. Tokens.resize(Tokens.size() - 1);
  1224. return true;
  1225. }
  1226. // Try to determine whether the current token ends a JavaScript regex literal.
  1227. // We heuristically assume that this is a regex literal if we find two
  1228. // unescaped slashes on a line and the token before the first slash is one of
  1229. // "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
  1230. // a division.
  1231. bool tryMergeJSRegexLiteral() {
  1232. if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
  1233. (Tokens[Tokens.size() - 2]->is(tok::unknown) &&
  1234. Tokens[Tokens.size() - 2]->TokenText == "\\"))
  1235. return false;
  1236. unsigned TokenCount = 0;
  1237. unsigned LastColumn = Tokens.back()->OriginalColumn;
  1238. for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
  1239. ++TokenCount;
  1240. if (I[0]->is(tok::slash) && I + 1 != E &&
  1241. (I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
  1242. tok::exclaim, tok::l_square, tok::colon, tok::comma,
  1243. tok::question, tok::kw_return) ||
  1244. I[1]->isBinaryOperator())) {
  1245. Tokens.resize(Tokens.size() - TokenCount);
  1246. Tokens.back()->Tok.setKind(tok::unknown);
  1247. Tokens.back()->Type = TT_RegexLiteral;
  1248. Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
  1249. return true;
  1250. }
  1251. // There can't be a newline inside a regex literal.
  1252. if (I[0]->NewlinesBefore > 0)
  1253. return false;
  1254. }
  1255. return false;
  1256. }
  1257. bool tryMerge_TMacro() {
  1258. if (Tokens.size() < 4)
  1259. return false;
  1260. FormatToken *Last = Tokens.back();
  1261. if (!Last->is(tok::r_paren))
  1262. return false;
  1263. FormatToken *String = Tokens[Tokens.size() - 2];
  1264. if (!String->is(tok::string_literal) || String->IsMultiline)
  1265. return false;
  1266. if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
  1267. return false;
  1268. FormatToken *Macro = Tokens[Tokens.size() - 4];
  1269. if (Macro->TokenText != "_T")
  1270. return false;
  1271. const char *Start = Macro->TokenText.data();
  1272. const char *End = Last->TokenText.data() + Last->TokenText.size();
  1273. String->TokenText = StringRef(Start, End - Start);
  1274. String->IsFirst = Macro->IsFirst;
  1275. String->LastNewlineOffset = Macro->LastNewlineOffset;
  1276. String->WhitespaceRange = Macro->WhitespaceRange;
  1277. String->OriginalColumn = Macro->OriginalColumn;
  1278. String->ColumnWidth = encoding::columnWidthWithTabs(
  1279. String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
  1280. Tokens.pop_back();
  1281. Tokens.pop_back();
  1282. Tokens.pop_back();
  1283. Tokens.back() = String;
  1284. return true;
  1285. }
  1286. bool tryMergeConflictMarkers() {
  1287. if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
  1288. return false;
  1289. // Conflict lines look like:
  1290. // <marker> <text from the vcs>
  1291. // For example:
  1292. // >>>>>>> /file/in/file/system at revision 1234
  1293. //
  1294. // We merge all tokens in a line that starts with a conflict marker
  1295. // into a single token with a special token type that the unwrapped line
  1296. // parser will use to correctly rebuild the underlying code.
  1297. FileID ID;
  1298. // Get the position of the first token in the line.
  1299. unsigned FirstInLineOffset;
  1300. std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
  1301. Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
  1302. StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
  1303. // Calculate the offset of the start of the current line.
  1304. auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
  1305. if (LineOffset == StringRef::npos) {
  1306. LineOffset = 0;
  1307. } else {
  1308. ++LineOffset;
  1309. }
  1310. auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
  1311. StringRef LineStart;
  1312. if (FirstSpace == StringRef::npos) {
  1313. LineStart = Buffer.substr(LineOffset);
  1314. } else {
  1315. LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
  1316. }
  1317. TokenType Type = TT_Unknown;
  1318. if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
  1319. Type = TT_ConflictStart;
  1320. } else if (LineStart == "|||||||" || LineStart == "=======" ||
  1321. LineStart == "====") {
  1322. Type = TT_ConflictAlternative;
  1323. } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
  1324. Type = TT_ConflictEnd;
  1325. }
  1326. if (Type != TT_Unknown) {
  1327. FormatToken *Next = Tokens.back();
  1328. Tokens.resize(FirstInLineIndex + 1);
  1329. // We do not need to build a complete token here, as we will skip it
  1330. // during parsing anyway (as we must not touch whitespace around conflict
  1331. // markers).
  1332. Tokens.back()->Type = Type;
  1333. Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
  1334. Tokens.push_back(Next);
  1335. return true;
  1336. }
  1337. return false;
  1338. }
  1339. FormatToken *getNextToken() {
  1340. if (GreaterStashed) {
  1341. // Create a synthesized second '>' token.
  1342. // FIXME: Increment Column and set OriginalColumn.
  1343. Token Greater = FormatTok->Tok;
  1344. FormatTok = new (Allocator.Allocate()) FormatToken;
  1345. FormatTok->Tok = Greater;
  1346. SourceLocation GreaterLocation =
  1347. FormatTok->Tok.getLocation().getLocWithOffset(1);
  1348. FormatTok->WhitespaceRange =
  1349. SourceRange(GreaterLocation, GreaterLocation);
  1350. FormatTok->TokenText = ">";
  1351. FormatTok->ColumnWidth = 1;
  1352. GreaterStashed = false;
  1353. return FormatTok;
  1354. }
  1355. FormatTok = new (Allocator.Allocate()) FormatToken;
  1356. readRawToken(*FormatTok);
  1357. SourceLocation WhitespaceStart =
  1358. FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
  1359. FormatTok->IsFirst = IsFirstToken;
  1360. IsFirstToken = false;
  1361. // Consume and record whitespace until we find a significant token.
  1362. unsigned WhitespaceLength = TrailingWhitespace;
  1363. while (FormatTok->Tok.is(tok::unknown)) {
  1364. for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
  1365. switch (FormatTok->TokenText[i]) {
  1366. case '\n':
  1367. ++FormatTok->NewlinesBefore;
  1368. // FIXME: This is technically incorrect, as it could also
  1369. // be a literal backslash at the end of the line.
  1370. if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
  1371. (FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
  1372. FormatTok->TokenText[i - 2] != '\\')))
  1373. FormatTok->HasUnescapedNewline = true;
  1374. FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
  1375. Column = 0;
  1376. break;
  1377. case '\r':
  1378. case '\f':
  1379. case '\v':
  1380. Column = 0;
  1381. break;
  1382. case ' ':
  1383. ++Column;
  1384. break;
  1385. case '\t':
  1386. Column += Style.TabWidth - Column % Style.TabWidth;
  1387. break;
  1388. case '\\':
  1389. ++Column;
  1390. if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
  1391. FormatTok->TokenText[i + 1] != '\n'))
  1392. FormatTok->Type = TT_ImplicitStringLiteral;
  1393. break;
  1394. default:
  1395. FormatTok->Type = TT_ImplicitStringLiteral;
  1396. ++Column;
  1397. break;
  1398. }
  1399. }
  1400. if (FormatTok->Type == TT_ImplicitStringLiteral)
  1401. break;
  1402. WhitespaceLength += FormatTok->Tok.getLength();
  1403. readRawToken(*FormatTok);
  1404. }
  1405. // In case the token starts with escaped newlines, we want to
  1406. // take them into account as whitespace - this pattern is quite frequent
  1407. // in macro definitions.
  1408. // FIXME: Add a more explicit test.
  1409. while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
  1410. FormatTok->TokenText[1] == '\n') {
  1411. ++FormatTok->NewlinesBefore;
  1412. WhitespaceLength += 2;
  1413. Column = 0;
  1414. FormatTok->TokenText = FormatTok->TokenText.substr(2);
  1415. }
  1416. FormatTok->WhitespaceRange = SourceRange(
  1417. WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
  1418. FormatTok->OriginalColumn = Column;
  1419. TrailingWhitespace = 0;
  1420. if (FormatTok->Tok.is(tok::comment)) {
  1421. // FIXME: Add the trimmed whitespace to Column.
  1422. StringRef UntrimmedText = FormatTok->TokenText;
  1423. FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
  1424. TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
  1425. } else if (FormatTok->Tok.is(tok::raw_identifier)) {
  1426. IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
  1427. FormatTok->Tok.setIdentifierInfo(&Info);
  1428. FormatTok->Tok.setKind(Info.getTokenID());
  1429. } else if (FormatTok->Tok.is(tok::greatergreater)) {
  1430. FormatTok->Tok.setKind(tok::greater);
  1431. FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
  1432. GreaterStashed = true;
  1433. }
  1434. // Now FormatTok is the next non-whitespace token.
  1435. StringRef Text = FormatTok->TokenText;
  1436. size_t FirstNewlinePos = Text.find('\n');
  1437. if (FirstNewlinePos == StringRef::npos) {
  1438. // FIXME: ColumnWidth actually depends on the start column, we need to
  1439. // take this into account when the token is moved.
  1440. FormatTok->ColumnWidth =
  1441. encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
  1442. Column += FormatTok->ColumnWidth;
  1443. } else {
  1444. FormatTok->IsMultiline = true;
  1445. // FIXME: ColumnWidth actually depends on the start column, we need to
  1446. // take this into account when the token is moved.
  1447. FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
  1448. Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
  1449. // The last line of the token always starts in column 0.
  1450. // Thus, the length can be precomputed even in the presence of tabs.
  1451. FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
  1452. Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
  1453. Encoding);
  1454. Column = FormatTok->LastLineColumnWidth;
  1455. }
  1456. FormatTok->IsForEachMacro =
  1457. std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
  1458. FormatTok->Tok.getIdentifierInfo());
  1459. return FormatTok;
  1460. }
  1461. FormatToken *FormatTok;
  1462. bool IsFirstToken;
  1463. bool GreaterStashed;
  1464. unsigned Column;
  1465. unsigned TrailingWhitespace;
  1466. Lexer &Lex;
  1467. SourceManager &SourceMgr;
  1468. FormatStyle &Style;
  1469. IdentifierTable IdentTable;
  1470. encoding::Encoding Encoding;
  1471. llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
  1472. // Index (in 'Tokens') of the last token that starts a new line.
  1473. unsigned FirstInLineIndex;
  1474. SmallVector<FormatToken *, 16> Tokens;
  1475. SmallVector<IdentifierInfo *, 8> ForEachMacros;
  1476. void readRawToken(FormatToken &Tok) {
  1477. Lex.LexFromRawLexer(Tok.Tok);
  1478. Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
  1479. Tok.Tok.getLength());
  1480. // For formatting, treat unterminated string literals like normal string
  1481. // literals.
  1482. if (Tok.is(tok::unknown)) {
  1483. if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
  1484. Tok.Tok.setKind(tok::string_literal);
  1485. Tok.IsUnterminatedLiteral = true;
  1486. } else if (Style.Language == FormatStyle::LK_JavaScript &&
  1487. Tok.TokenText == "''") {
  1488. Tok.Tok.setKind(tok::char_constant);
  1489. }
  1490. }
  1491. }
  1492. };
  1493. static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
  1494. switch (Language) {
  1495. case FormatStyle::LK_Cpp:
  1496. return "C++";
  1497. case FormatStyle::LK_JavaScript:
  1498. return "JavaScript";
  1499. case FormatStyle::LK_Proto:
  1500. return "Proto";
  1501. default:
  1502. return "Unknown";
  1503. }
  1504. }
  1505. class Formatter : public UnwrappedLineConsumer {
  1506. public:
  1507. Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
  1508. const std::vector<CharSourceRange> &Ranges)
  1509. : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
  1510. Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
  1511. Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
  1512. Encoding(encoding::detectEncoding(Lex.getBuffer())) {
  1513. DEBUG(llvm::dbgs() << "File encoding: "
  1514. << (Encoding == encoding::Encoding_UTF8 ? "UTF8"
  1515. : "unknown")
  1516. << "\n");
  1517. DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
  1518. << "\n");
  1519. }
  1520. tooling::Replacements format() {
  1521. tooling::Replacements Result;
  1522. FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
  1523. UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
  1524. bool StructuralError = Parser.parse();
  1525. assert(UnwrappedLines.rbegin()->empty());
  1526. for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
  1527. ++Run) {
  1528. DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
  1529. SmallVector<AnnotatedLine *, 16> AnnotatedLines;
  1530. for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
  1531. AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
  1532. }
  1533. tooling::Replacements RunResult =
  1534. format(AnnotatedLines, StructuralError, Tokens);
  1535. DEBUG({
  1536. llvm::dbgs() << "Replacements for run " << Run << ":\n";
  1537. for (tooling::Replacements::iterator I = RunResult.begin(),
  1538. E = RunResult.end();
  1539. I != E; ++I) {
  1540. llvm::dbgs() << I->toString() << "\n";
  1541. }
  1542. });
  1543. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1544. delete AnnotatedLines[i];
  1545. }
  1546. Result.insert(RunResult.begin(), RunResult.end());
  1547. Whitespaces.reset();
  1548. }
  1549. return Result;
  1550. }
  1551. tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
  1552. bool StructuralError, FormatTokenLexer &Tokens) {
  1553. TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
  1554. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1555. Annotator.annotate(*AnnotatedLines[i]);
  1556. }
  1557. deriveLocalStyle(AnnotatedLines);
  1558. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1559. Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
  1560. }
  1561. computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
  1562. Annotator.setCommentLineLevels(AnnotatedLines);
  1563. ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
  1564. BinPackInconclusiveFunctions);
  1565. UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
  1566. Formatter.format(AnnotatedLines, /*DryRun=*/false);
  1567. return Whitespaces.generateReplacements();
  1568. }
  1569. private:
  1570. // Determines which lines are affected by the SourceRanges given as input.
  1571. // Returns \c true if at least one line between I and E or one of their
  1572. // children is affected.
  1573. bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
  1574. SmallVectorImpl<AnnotatedLine *>::iterator E) {
  1575. bool SomeLineAffected = false;
  1576. const AnnotatedLine *PreviousLine = nullptr;
  1577. while (I != E) {
  1578. AnnotatedLine *Line = *I;
  1579. Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
  1580. // If a line is part of a preprocessor directive, it needs to be formatted
  1581. // if any token within the directive is affected.
  1582. if (Line->InPPDirective) {
  1583. FormatToken *Last = Line->Last;
  1584. SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
  1585. while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
  1586. Last = (*PPEnd)->Last;
  1587. ++PPEnd;
  1588. }
  1589. if (affectsTokenRange(*Line->First, *Last,
  1590. /*IncludeLeadingNewlines=*/false)) {
  1591. SomeLineAffected = true;
  1592. markAllAsAffected(I, PPEnd);
  1593. }
  1594. I = PPEnd;
  1595. continue;
  1596. }
  1597. if (nonPPLineAffected(Line, PreviousLine))
  1598. SomeLineAffected = true;
  1599. PreviousLine = Line;
  1600. ++I;
  1601. }
  1602. return SomeLineAffected;
  1603. }
  1604. // Determines whether 'Line' is affected by the SourceRanges given as input.
  1605. // Returns \c true if line or one if its children is affected.
  1606. bool nonPPLineAffected(AnnotatedLine *Line,
  1607. const AnnotatedLine *PreviousLine) {
  1608. bool SomeLineAffected = false;
  1609. Line->ChildrenAffected =
  1610. computeAffectedLines(Line->Children.begin(), Line->Children.end());
  1611. if (Line->ChildrenAffected)
  1612. SomeLineAffected = true;
  1613. // Stores whether one of the line's tokens is directly affected.
  1614. bool SomeTokenAffected = false;
  1615. // Stores whether we need to look at the leading newlines of the next token
  1616. // in order to determine whether it was affected.
  1617. bool IncludeLeadingNewlines = false;
  1618. // Stores whether the first child line of any of this line's tokens is
  1619. // affected.
  1620. bool SomeFirstChildAffected = false;
  1621. for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
  1622. // Determine whether 'Tok' was affected.
  1623. if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
  1624. SomeTokenAffected = true;
  1625. // Determine whether the first child of 'Tok' was affected.
  1626. if (!Tok->Children.empty() && Tok->Children.front()->Affected)
  1627. SomeFirstChildAffected = true;
  1628. IncludeLeadingNewlines = Tok->Children.empty();
  1629. }
  1630. // Was this line moved, i.e. has it previously been on the same line as an
  1631. // affected line?
  1632. bool LineMoved = PreviousLine && PreviousLine->Affected &&
  1633. Line->First->NewlinesBefore == 0;
  1634. bool IsContinuedComment =
  1635. Line->First->is(tok::comment) && Line->First->Next == nullptr &&
  1636. Line->First->NewlinesBefore < 2 && PreviousLine &&
  1637. PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
  1638. if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
  1639. IsContinuedComment) {
  1640. Line->Affected = true;
  1641. SomeLineAffected = true;
  1642. }
  1643. return SomeLineAffected;
  1644. }
  1645. // Marks all lines between I and E as well as all their children as affected.
  1646. void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
  1647. SmallVectorImpl<AnnotatedLine *>::iterator E) {
  1648. while (I != E) {
  1649. (*I)->Affected = true;
  1650. markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
  1651. ++I;
  1652. }
  1653. }
  1654. // Returns true if the range from 'First' to 'Last' intersects with one of the
  1655. // input ranges.
  1656. bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
  1657. bool IncludeLeadingNewlines) {
  1658. SourceLocation Start = First.WhitespaceRange.getBegin();
  1659. if (!IncludeLeadingNewlines)
  1660. Start = Start.getLocWithOffset(First.LastNewlineOffset);
  1661. SourceLocation End = Last.getStartOfNonWhitespace();
  1662. if (Last.TokenText.size() > 0)
  1663. End = End.getLocWithOffset(Last.TokenText.size() - 1);
  1664. CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
  1665. return affectsCharSourceRange(Range);
  1666. }
  1667. // Returns true if one of the input ranges intersect the leading empty lines
  1668. // before 'Tok'.
  1669. bool affectsLeadingEmptyLines(const FormatToken &Tok) {
  1670. CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
  1671. Tok.WhitespaceRange.getBegin(),
  1672. Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
  1673. return affectsCharSourceRange(EmptyLineRange);
  1674. }
  1675. // Returns true if 'Range' intersects with one of the input ranges.
  1676. bool affectsCharSourceRange(const CharSourceRange &Range) {
  1677. for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
  1678. E = Ranges.end();
  1679. I != E; ++I) {
  1680. if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
  1681. !SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
  1682. return true;
  1683. }
  1684. return false;
  1685. }
  1686. static bool inputUsesCRLF(StringRef Text) {
  1687. return Text.count('\r') * 2 > Text.count('\n');
  1688. }
  1689. void
  1690. deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
  1691. unsigned CountBoundToVariable = 0;
  1692. unsigned CountBoundToType = 0;
  1693. bool HasCpp03IncompatibleFormat = false;
  1694. bool HasBinPackedFunction = false;
  1695. bool HasOnePerLineFunction = false;
  1696. for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
  1697. if (!AnnotatedLines[i]->First->Next)
  1698. continue;
  1699. FormatToken *Tok = AnnotatedLines[i]->First->Next;
  1700. while (Tok->Next) {
  1701. if (Tok->Type == TT_PointerOrReference) {
  1702. bool SpacesBefore =
  1703. Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
  1704. bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
  1705. Tok->Next->WhitespaceRange.getEnd();
  1706. if (SpacesBefore && !SpacesAfter)
  1707. ++CountBoundToVariable;
  1708. else if (!SpacesBefore && SpacesAfter)
  1709. ++CountBoundToType;
  1710. }
  1711. if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
  1712. if (Tok->is(tok::coloncolon) &&
  1713. Tok->Previous->Type == TT_TemplateOpener)
  1714. HasCpp03IncompatibleFormat = true;
  1715. if (Tok->Type == TT_TemplateCloser &&
  1716. Tok->Previous->Type == TT_TemplateCloser)
  1717. HasCpp03IncompatibleFormat = true;
  1718. }
  1719. if (Tok->PackingKind == PPK_BinPacked)
  1720. HasBinPackedFunction = true;
  1721. if (Tok->PackingKind == PPK_OnePerLine)
  1722. HasOnePerLineFunction = true;
  1723. Tok = Tok->Next;
  1724. }
  1725. }
  1726. if (Style.DerivePointerAlignment) {
  1727. if (CountBoundToType > CountBoundToVariable)
  1728. Style.PointerAlignment = FormatStyle::PAS_Left;
  1729. else if (CountBoundToType < CountBoundToVariable)
  1730. Style.PointerAlignment = FormatStyle::PAS_Right;
  1731. }
  1732. if (Style.Standard == FormatStyle::LS_Auto) {
  1733. Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
  1734. : FormatStyle::LS_Cpp03;
  1735. }
  1736. BinPackInconclusiveFunctions =
  1737. HasBinPackedFunction || !HasOnePerLineFunction;
  1738. }
  1739. void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
  1740. assert(!UnwrappedLines.empty());
  1741. UnwrappedLines.back().push_back(TheLine);
  1742. }
  1743. void finishRun() override {
  1744. UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
  1745. }
  1746. FormatStyle Style;
  1747. Lexer &Lex;
  1748. SourceManager &SourceMgr;
  1749. WhitespaceManager Whitespaces;
  1750. SmallVector<CharSourceRange, 8> Ranges;
  1751. SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
  1752. encoding::Encoding Encoding;
  1753. bool BinPackInconclusiveFunctions;
  1754. };
  1755. } // end anonymous namespace
  1756. tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
  1757. SourceManager &SourceMgr,
  1758. std::vector<CharSourceRange> Ranges) {
  1759. if (Style.DisableFormat) {
  1760. tooling::Replacements EmptyResult;
  1761. return EmptyResult;
  1762. }
  1763. Formatter formatter(Style, Lex, SourceMgr, Ranges);
  1764. return formatter.format();
  1765. }
  1766. tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
  1767. std::vector<tooling::Range> Ranges,
  1768. StringRef FileName) {
  1769. FileManager Files((FileSystemOptions()));
  1770. DiagnosticsEngine Diagnostics(
  1771. IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
  1772. new DiagnosticOptions);
  1773. SourceManager SourceMgr(Diagnostics, Files);
  1774. llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
  1775. const clang::FileEntry *Entry =
  1776. Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
  1777. SourceMgr.overrideFileContents(Entry, Buf);
  1778. FileID ID =
  1779. SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
  1780. Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
  1781. getFormattingLangOpts(Style.Standard));
  1782. SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
  1783. std::vector<CharSourceRange> CharRanges;
  1784. for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
  1785. SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
  1786. SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
  1787. CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
  1788. }
  1789. return reformat(Style, Lex, SourceMgr, CharRanges);
  1790. }
  1791. LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
  1792. LangOptions LangOpts;
  1793. LangOpts.CPlusPlus = 1;
  1794. LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  1795. LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
  1796. LangOpts.LineComment = 1;
  1797. LangOpts.CXXOperatorNames = 1;
  1798. LangOpts.Bool = 1;
  1799. LangOpts.ObjC1 = 1;
  1800. LangOpts.ObjC2 = 1;
  1801. return LangOpts;
  1802. }
  1803. const char *StyleOptionHelpDescription =
  1804. "Coding style, currently supports:\n"
  1805. " LLVM, Google, Chromium, Mozilla, WebKit.\n"
  1806. "Use -style=file to load style configuration from\n"
  1807. ".clang-format file located in one of the parent\n"
  1808. "directories of the source file (or current\n"
  1809. "directory for stdin).\n"
  1810. "Use -style=\"{key: value, ...}\" to set specific\n"
  1811. "parameters, e.g.:\n"
  1812. " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
  1813. static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
  1814. if (FileName.endswith_lower(".js")) {
  1815. return FormatStyle::LK_JavaScript;
  1816. } else if (FileName.endswith_lower(".proto") ||
  1817. FileName.endswith_lower(".protodevel")) {
  1818. return FormatStyle::LK_Proto;
  1819. }
  1820. return FormatStyle::LK_Cpp;
  1821. }
  1822. FormatStyle getStyle(StringRef StyleName, StringRef FileName,
  1823. StringRef FallbackStyle) {
  1824. FormatStyle Style = getLLVMStyle();
  1825. Style.Language = getLanguageByFileName(FileName);
  1826. if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
  1827. llvm::errs() << "Invalid fallback style \"" << FallbackStyle
  1828. << "\" using LLVM style\n";
  1829. return Style;
  1830. }
  1831. if (StyleName.startswith("{")) {
  1832. // Parse YAML/JSON style from the command line.
  1833. if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
  1834. llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
  1835. << FallbackStyle << " style\n";
  1836. }
  1837. return Style;
  1838. }
  1839. if (!StyleName.equals_lower("file")) {
  1840. if (!getPredefinedStyle(StyleName, Style.Language, &Style))
  1841. llvm::errs() << "Invalid value for -style, using " << FallbackStyle
  1842. << " style\n";
  1843. return Style;
  1844. }
  1845. // Look for .clang-format/_clang-format file in the file's parent directories.
  1846. SmallString<128> UnsuitableConfigFiles;
  1847. SmallString<128> Path(FileName);
  1848. llvm::sys::fs::make_absolute(Path);
  1849. for (StringRef Directory = Path; !Directory.empty();
  1850. Directory = llvm::sys::path::parent_path(Directory)) {
  1851. if (!llvm::sys::fs::is_directory(Directory))
  1852. continue;
  1853. SmallString<128> ConfigFile(Directory);
  1854. llvm::sys::path::append(ConfigFile, ".clang-format");
  1855. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1856. bool IsFile = false;
  1857. // Ignore errors from is_regular_file: we only need to know if we can read
  1858. // the file or not.
  1859. llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
  1860. if (!IsFile) {
  1861. // Try _clang-format too, since dotfiles are not commonly used on Windows.
  1862. ConfigFile = Directory;
  1863. llvm::sys::path::append(ConfigFile, "_clang-format");
  1864. DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
  1865. llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
  1866. }
  1867. if (IsFile) {
  1868. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  1869. llvm::MemoryBuffer::getFile(ConfigFile.c_str());
  1870. if (std::error_code EC = Text.getError()) {
  1871. llvm::errs() << EC.message() << "\n";
  1872. break;
  1873. }
  1874. if (std::error_code ec =
  1875. parseConfiguration(Text.get()->getBuffer(), &Style)) {
  1876. if (ec == ParseError::Unsuitable) {
  1877. if (!UnsuitableConfigFiles.empty())
  1878. UnsuitableConfigFiles.append(", ");
  1879. UnsuitableConfigFiles.append(ConfigFile);
  1880. continue;
  1881. }
  1882. llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
  1883. << "\n";
  1884. break;
  1885. }
  1886. DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
  1887. return Style;
  1888. }
  1889. }
  1890. llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
  1891. << " style\n";
  1892. if (!UnsuitableConfigFiles.empty()) {
  1893. llvm::errs() << "Configuration file(s) do(es) not support "
  1894. << getLanguageName(Style.Language) << ": "
  1895. << UnsuitableConfigFiles << "\n";
  1896. }
  1897. return Style;
  1898. }
  1899. } // namespace format
  1900. } // namespace clang