Format.cpp 96 KB

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