Format.cpp 88 KB

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