Format.cpp 85 KB

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