source_gen.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "testing/base/source_gen.h"
  5. #include <numeric>
  6. #include "common/raw_string_ostream.h"
  7. #include "llvm/ADT/ArrayRef.h"
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. #include "llvm/Support/FormatVariadic.h"
  12. #include "toolchain/lex/token_kind.h"
  13. namespace Carbon::Testing {
  14. auto SourceGen::Global() -> SourceGen& {
  15. static SourceGen global_gen;
  16. return global_gen;
  17. }
  18. SourceGen::SourceGen(Language language) : language_(language) {}
  19. // Heuristic numbers used in synthesizing various identifier sequences.
  20. constexpr static int MinClassNameLength = 5;
  21. constexpr static int MinMemberNameLength = 4;
  22. // The shuffled state used to generate some number of classes.
  23. //
  24. // This state encodes everything used to generate class definitions. The state
  25. // will be consumed until empty.
  26. //
  27. // Detailed comments for out-of-line methods are on their definitions.
  28. class SourceGen::ClassGenState {
  29. public:
  30. ClassGenState(SourceGen& gen, int num_classes,
  31. const ClassParams& class_params,
  32. const TypeUseParams& type_use_params);
  33. auto public_function_param_counts() -> llvm::SmallVectorImpl<int>& {
  34. return public_function_param_counts_;
  35. }
  36. auto public_method_param_counts() -> llvm::SmallVectorImpl<int>& {
  37. return public_method_param_counts_;
  38. }
  39. auto private_function_param_counts() -> llvm::SmallVectorImpl<int>& {
  40. return private_function_param_counts_;
  41. }
  42. auto private_method_param_counts() -> llvm::SmallVectorImpl<int>& {
  43. return private_method_param_counts_;
  44. }
  45. auto class_names() -> llvm::SmallVectorImpl<llvm::StringRef>& {
  46. return class_names_;
  47. }
  48. auto member_names() -> llvm::SmallVectorImpl<llvm::StringRef>& {
  49. return member_names_;
  50. }
  51. auto param_names() -> llvm::SmallVectorImpl<llvm::StringRef>& {
  52. return param_names_;
  53. }
  54. auto type_names() -> llvm::SmallVectorImpl<llvm::StringRef>& {
  55. return type_names_;
  56. }
  57. auto AddValidTypeName(llvm::StringRef type_name) -> void {
  58. valid_type_names_.Insert(type_name);
  59. }
  60. auto GetValidTypeName() -> llvm::StringRef;
  61. private:
  62. auto BuildClassAndTypeNames(SourceGen& gen, int num_classes, int num_types,
  63. const TypeUseParams& type_use_params) -> void;
  64. llvm::SmallVector<int> public_function_param_counts_;
  65. llvm::SmallVector<int> public_method_param_counts_;
  66. llvm::SmallVector<int> private_function_param_counts_;
  67. llvm::SmallVector<int> private_method_param_counts_;
  68. llvm::SmallVector<llvm::StringRef> class_names_;
  69. llvm::SmallVector<llvm::StringRef> member_names_;
  70. llvm::SmallVector<llvm::StringRef> param_names_;
  71. llvm::SmallVector<llvm::StringRef> type_names_;
  72. Set<llvm::StringRef> valid_type_names_;
  73. int last_type_name_index_ = 0;
  74. };
  75. // A helper to sum elements of a range.
  76. template <typename T>
  77. static auto Sum(const T& range) -> int {
  78. return std::accumulate(range.begin(), range.end(), 0);
  79. }
  80. // Given a number of class definitions and the params with which to generate
  81. // them, builds the state that will be used while generating that many classes.
  82. //
  83. // We build the state first and across all the class definitions that will be
  84. // generated so that we can distribute random components across all the
  85. // definitions.
  86. SourceGen::ClassGenState::ClassGenState(SourceGen& gen, int num_classes,
  87. const ClassParams& class_params,
  88. const TypeUseParams& type_use_params) {
  89. public_function_param_counts_ =
  90. gen.GetShuffledInts(num_classes * class_params.public_function_decls, 0,
  91. class_params.public_function_decl_params.max_params);
  92. public_method_param_counts_ =
  93. gen.GetShuffledInts(num_classes * class_params.public_method_decls, 0,
  94. class_params.public_method_decl_params.max_params);
  95. private_function_param_counts_ =
  96. gen.GetShuffledInts(num_classes * class_params.private_function_decls, 0,
  97. class_params.private_function_decl_params.max_params);
  98. private_method_param_counts_ =
  99. gen.GetShuffledInts(num_classes * class_params.private_method_decls, 0,
  100. class_params.private_method_decl_params.max_params);
  101. int num_members =
  102. num_classes *
  103. (class_params.public_function_decls + class_params.public_method_decls +
  104. class_params.private_function_decls + class_params.private_method_decls +
  105. class_params.private_field_decls);
  106. member_names_ = gen.GetShuffledIdentifiers(
  107. num_members, /*min_length=*/MinMemberNameLength);
  108. int num_params =
  109. Sum(public_function_param_counts_) + Sum(public_method_param_counts_) +
  110. Sum(private_function_param_counts_) + Sum(private_method_param_counts_);
  111. param_names_ = gen.GetShuffledIdentifiers(num_params);
  112. BuildClassAndTypeNames(gen, num_classes, num_members + num_params,
  113. type_use_params);
  114. }
  115. auto SourceGen::ClassGenState::GetValidTypeName() -> llvm::StringRef {
  116. // Check that we don't completely wrap the type names by tracking where we
  117. // started.
  118. int initial_last_type_name_index = last_type_name_index_;
  119. // Now search the type names, starting from the last used index, to find the
  120. // first valid name.
  121. for (;;) {
  122. if (last_type_name_index_ == 0) {
  123. last_type_name_index_ = type_names_.size();
  124. }
  125. --last_type_name_index_;
  126. llvm::StringRef& type_name = type_names_[last_type_name_index_];
  127. if (valid_type_names_.Contains(type_name)) {
  128. // Found a valid type name, swap it with the back and pop that off.
  129. std::swap(type_names_.back(), type_name);
  130. return type_names_.pop_back_val();
  131. }
  132. CARBON_CHECK(last_type_name_index_ != initial_last_type_name_index,
  133. "Failed to find a valid type name with {0} candidates, an "
  134. "initial index of {1}, and with {2} classes left to emit!",
  135. type_names_.size(), initial_last_type_name_index,
  136. class_names_.size());
  137. }
  138. }
  139. // Build both the class names this file will declare and a list of type
  140. // references to use throughout those classes.
  141. //
  142. // We combine a list of fixed types in the `type_use_params` with the list of
  143. // class names that will be defined to form the spelling of all the referenced
  144. // types. The `type_use_params` provides weights for each fixed type as well as
  145. // an overall weight for referencing class names that are being declared. We
  146. // build a set of type references so that its histogram will roughly match these
  147. // weights.
  148. //
  149. // For each of the fixed types, `type_use_params` provides a spelling for both
  150. // Carbon and C++.
  151. //
  152. // We distribute our references to declared class names evenly to the extent
  153. // possible.
  154. //
  155. // Before all the references are formed, the class names are kept their original
  156. // unshuffled order. This ensures that any uneven sampling of names is done
  157. // deterministically. At the end, we randomly shuffle the sequences of both the
  158. // declared class names and type references to provide an unpredictable order in
  159. // the generated output.
  160. auto SourceGen::ClassGenState::BuildClassAndTypeNames(
  161. SourceGen& gen, int num_classes, int num_types,
  162. const TypeUseParams& type_use_params) -> void {
  163. // Initially get the sequence of class names without shuffling so we can
  164. // compute our type name pool from them prior to any shuffling.
  165. class_names_ =
  166. gen.GetUniqueIdentifiers(num_classes, /*min_length=*/MinClassNameLength);
  167. type_names_.reserve(num_types);
  168. // Compute the sum of weights and pre-process the fixed types.
  169. int type_weight_sum = type_use_params.declared_types_weight;
  170. for (const auto& fixed_type_weight : type_use_params.fixed_type_weights) {
  171. type_weight_sum += fixed_type_weight.weight;
  172. // Add all the fixed type spellings as immediately valid.
  173. valid_type_names_.Insert(gen.IsCpp() ? fixed_type_weight.cpp_spelling
  174. : fixed_type_weight.carbon_spelling);
  175. }
  176. // Compute the number of declared types used. We expect to have a decent
  177. // number of repeated names, so we repeatedly append the entire sequence of
  178. // class names until there is some remainder of names needed.
  179. int num_declared_types =
  180. num_types * type_use_params.declared_types_weight / type_weight_sum;
  181. for ([[maybe_unused]] auto _ : llvm::seq(num_declared_types / num_classes)) {
  182. llvm::append_range(type_names_, class_names_);
  183. }
  184. // Now append the remainder number of class names. This is where the class
  185. // names being un-shuffled is essential. We're going to have one extra
  186. // reference to some fraction of the class names and we want that to be a
  187. // stable subset.
  188. type_names_.append(class_names_.begin(),
  189. class_names_.begin() + (num_declared_types % num_classes));
  190. CARBON_CHECK(static_cast<int>(type_names_.size()) == num_declared_types);
  191. // Use each fixed type weight to append the expected number of copies of that
  192. // type. This isn't exact however, and is designed to stop short.
  193. for (const auto& fixed_type_weight : type_use_params.fixed_type_weights) {
  194. int num_fixed_type = num_types * fixed_type_weight.weight / type_weight_sum;
  195. type_names_.append(num_fixed_type, gen.IsCpp()
  196. ? fixed_type_weight.cpp_spelling
  197. : fixed_type_weight.carbon_spelling);
  198. }
  199. // If we need a tail of types to hit the exact number, simply round-robin
  200. // through the fixed types without any weighting. With reasonably large
  201. // numbers of types this won't distort the distribution in an interesting way
  202. // and is simpler than trying to scale the distribution down.
  203. while (static_cast<int>(type_names_.size()) < num_types) {
  204. for (const auto& fixed_type_weight :
  205. llvm::ArrayRef(type_use_params.fixed_type_weights)
  206. .take_front(num_types - type_names_.size())) {
  207. type_names_.push_back(gen.IsCpp() ? fixed_type_weight.cpp_spelling
  208. : fixed_type_weight.carbon_spelling);
  209. }
  210. }
  211. CARBON_CHECK(static_cast<int>(type_names_.size()) == num_types);
  212. last_type_name_index_ = num_types;
  213. // Now shuffle both the class names and the type names.
  214. std::shuffle(class_names_.begin(), class_names_.end(), gen.rng_);
  215. std::shuffle(type_names_.begin(), type_names_.end(), gen.rng_);
  216. }
  217. // Some heuristic numbers used when formatting generated code. These heuristics
  218. // are loosely based on what we expect to make Carbon code readable, and might
  219. // not fit as well in C++, but we use the same heuristics across languages for
  220. // simplicity and to make the output in different languages more directly
  221. // comparable.
  222. constexpr static int NumSingleLineFunctionParams = 3;
  223. constexpr static int NumSingleLineMethodParams = 2;
  224. constexpr static int MaxParamsPerLine = 4;
  225. static auto EstimateAvgFunctionDeclLines(SourceGen::FunctionDeclParams params)
  226. -> double {
  227. // Currently model a uniform distribution [0, max] parameters. Assume a line
  228. // break before the first parameter for >3 and after every 4th.
  229. int param_lines = 0;
  230. for (int num_params : llvm::seq_inclusive(0, params.max_params)) {
  231. if (num_params > NumSingleLineFunctionParams) {
  232. param_lines += (num_params + MaxParamsPerLine - 1) / MaxParamsPerLine;
  233. }
  234. }
  235. return 1.0 + static_cast<double>(param_lines) / (params.max_params + 1);
  236. }
  237. static auto EstimateAvgMethodDeclLines(SourceGen::MethodDeclParams params)
  238. -> double {
  239. // Currently model a uniform distribution [0, max] parameters. Assume a line
  240. // break before the first parameter for >2 and after every 4th.
  241. int param_lines = 0;
  242. for (int num_params : llvm::seq_inclusive(0, params.max_params)) {
  243. if (num_params > NumSingleLineMethodParams) {
  244. param_lines += (num_params + MaxParamsPerLine - 1) / MaxParamsPerLine;
  245. }
  246. }
  247. return 1.0 + static_cast<double>(param_lines) / (params.max_params + 1);
  248. }
  249. // Note that this should match the heuristics used when formatting.
  250. // TODO: See top-level TODO about line estimates and formatting.
  251. static auto EstimateAvgClassDefLines(SourceGen::ClassParams params) -> double {
  252. // Comment line, and class open line.
  253. double avg = 2.0;
  254. // One comment line and blank line per function, plus the function lines.
  255. avg +=
  256. (2.0 + EstimateAvgFunctionDeclLines(params.public_function_decl_params)) *
  257. params.public_function_decls;
  258. avg += (2.0 + EstimateAvgMethodDeclLines(params.public_method_decl_params)) *
  259. params.public_method_decls;
  260. avg += (2.0 +
  261. EstimateAvgFunctionDeclLines(params.private_function_decl_params)) *
  262. params.private_function_decls;
  263. avg += (2.0 + EstimateAvgMethodDeclLines(params.private_method_decl_params)) *
  264. params.private_method_decls;
  265. // A blank line and all the fields (if any).
  266. if (params.private_field_decls > 0) {
  267. avg += 1.0 + params.private_field_decls;
  268. }
  269. // No need to account for the class close line, we have an extra blank line
  270. // count for the last of the above.
  271. return avg;
  272. }
  273. auto SourceGen::GenApiFileDenseDecls(int target_lines,
  274. const DenseDeclParams& params)
  275. -> std::string {
  276. RawStringOstream source;
  277. // Figure out how many classes fit in our target lines, each separated by a
  278. // blank line. We need to account the comment lines below to start the file.
  279. // Note that we want a blank line after our file comment block, so every class
  280. // needs a blank line.
  281. constexpr int NumFileCommentLines = 4;
  282. double avg_class_lines = EstimateAvgClassDefLines(params.class_params);
  283. CARBON_CHECK(target_lines > NumFileCommentLines + avg_class_lines,
  284. "Not enough target lines to generate a single class!");
  285. int num_classes = static_cast<double>(target_lines - NumFileCommentLines) /
  286. (avg_class_lines + 1);
  287. int expected_lines =
  288. NumFileCommentLines + num_classes * (avg_class_lines + 1);
  289. source << "// Generated " << (!IsCpp() ? "Carbon" : "C++")
  290. << " source file.\n";
  291. source << llvm::formatv(
  292. "// {0} target lines: {1} classes, {2} expected lines",
  293. target_lines, num_classes, expected_lines)
  294. << "\n";
  295. source << "//\n// Generating as an API file with dense declarations.\n";
  296. // Carbon uses an implicitly imported prelude to get builtin types, but C++
  297. // requires header files so include those.
  298. if (IsCpp()) {
  299. source << "\n";
  300. // Header for specific integer types like `std::int64_t`.
  301. source << "#include <cstdint>\n";
  302. // Header for `std::pair`.
  303. source << "#include <utility>\n";
  304. }
  305. auto class_gen_state = ClassGenState(*this, num_classes, params.class_params,
  306. params.type_use_params);
  307. for ([[maybe_unused]] auto _ : llvm::seq(num_classes)) {
  308. source << "\n";
  309. GenerateClassDef(params.class_params, class_gen_state, source);
  310. }
  311. // Make sure we consumed all the state.
  312. CARBON_CHECK(class_gen_state.public_function_param_counts().empty());
  313. CARBON_CHECK(class_gen_state.public_method_param_counts().empty());
  314. CARBON_CHECK(class_gen_state.private_function_param_counts().empty());
  315. CARBON_CHECK(class_gen_state.private_method_param_counts().empty());
  316. CARBON_CHECK(class_gen_state.class_names().empty());
  317. CARBON_CHECK(class_gen_state.type_names().empty());
  318. return source.TakeStr();
  319. }
  320. auto SourceGen::GetShuffledIdentifiers(int number, int min_length,
  321. int max_length, bool uniform)
  322. -> llvm::SmallVector<llvm::StringRef> {
  323. llvm::SmallVector<llvm::StringRef> idents =
  324. GetIdentifiers(number, min_length, max_length, uniform);
  325. std::shuffle(idents.begin(), idents.end(), rng_);
  326. return idents;
  327. }
  328. auto SourceGen::GetShuffledUniqueIdentifiers(int number, int min_length,
  329. int max_length, bool uniform)
  330. -> llvm::SmallVector<llvm::StringRef> {
  331. CARBON_CHECK(min_length >= 4,
  332. "Cannot trivially guarantee enough distinct, unique identifiers "
  333. "for lengths <= 3");
  334. llvm::SmallVector<llvm::StringRef> idents =
  335. GetUniqueIdentifiers(number, min_length, max_length, uniform);
  336. std::shuffle(idents.begin(), idents.end(), rng_);
  337. return idents;
  338. }
  339. auto SourceGen::GetIdentifiers(int number, int min_length, int max_length,
  340. bool uniform)
  341. -> llvm::SmallVector<llvm::StringRef> {
  342. llvm::SmallVector<llvm::StringRef> idents = GetIdentifiersImpl(
  343. number, min_length, max_length, uniform,
  344. [this](int length, int length_count,
  345. llvm::SmallVectorImpl<llvm::StringRef>& dest) {
  346. llvm::append_range(dest,
  347. GetSingleLengthIdentifiers(length, length_count));
  348. });
  349. return idents;
  350. }
  351. auto SourceGen::GetUniqueIdentifiers(int number, int min_length, int max_length,
  352. bool uniform)
  353. -> llvm::SmallVector<llvm::StringRef> {
  354. CARBON_CHECK(min_length >= 4,
  355. "Cannot trivially guarantee enough distinct, unique identifiers "
  356. "for lengths <= 3");
  357. llvm::SmallVector<llvm::StringRef> idents =
  358. GetIdentifiersImpl(number, min_length, max_length, uniform,
  359. [this](int length, int length_count,
  360. llvm::SmallVectorImpl<llvm::StringRef>& dest) {
  361. AppendUniqueIdentifiers(length, length_count, dest);
  362. });
  363. return idents;
  364. }
  365. auto SourceGen::GetSingleLengthIdentifiers(int length, int number)
  366. -> llvm::ArrayRef<llvm::StringRef> {
  367. llvm::SmallVector<llvm::StringRef>& idents =
  368. identifiers_by_length_.Insert(length, {}).value();
  369. if (static_cast<int>(idents.size()) < number) {
  370. idents.reserve(number);
  371. for ([[maybe_unused]] auto _ : llvm::seq<int>(idents.size(), number)) {
  372. auto ident_storage =
  373. llvm::MutableArrayRef(reinterpret_cast<char*>(storage_.Allocate(
  374. /*Size=*/length, /*Alignment=*/1)),
  375. length);
  376. GenerateRandomIdentifier(ident_storage);
  377. llvm::StringRef new_id(ident_storage.data(), length);
  378. idents.push_back(new_id);
  379. }
  380. CARBON_CHECK(static_cast<int>(idents.size()) == number);
  381. }
  382. return llvm::ArrayRef(idents).slice(0, number);
  383. }
  384. static auto IdentifierStartChars() -> llvm::ArrayRef<char> {
  385. static llvm::SmallVector<char> chars = [] {
  386. llvm::SmallVector<char> chars;
  387. for (char c : llvm::seq_inclusive('A', 'Z')) {
  388. chars.push_back(c);
  389. }
  390. for (char c : llvm::seq_inclusive('a', 'z')) {
  391. chars.push_back(c);
  392. }
  393. return chars;
  394. }();
  395. return chars;
  396. }
  397. static auto IdentifierChars() -> llvm::ArrayRef<char> {
  398. static llvm::SmallVector<char> chars = [] {
  399. llvm::ArrayRef<char> start_chars = IdentifierStartChars();
  400. llvm::SmallVector<char> chars(start_chars.begin(), start_chars.end());
  401. chars.push_back('_');
  402. for (char c : llvm::seq_inclusive('0', '9')) {
  403. chars.push_back(c);
  404. }
  405. return chars;
  406. }();
  407. return chars;
  408. }
  409. constexpr static llvm::StringRef NonCarbonCppKeywords[] = {
  410. "asm", "do", "double", "float", "int", "long", "new", "signed",
  411. "std", "try", "unix", "unsigned", "xor", "NAN", "M_E", "M_PI",
  412. };
  413. // Returns a random identifier string of the specified length.
  414. //
  415. // Ensures this is a valid identifier, avoiding any overlapping syntaxes or
  416. // keywords both in Carbon and C++.
  417. //
  418. // This routine is somewhat expensive and so is useful to cache and reduce the
  419. // frequency of calls. However, each time it is called it computes a completely
  420. // new random identifier and so can be useful to eventually find a distinct
  421. // identifier when needed.
  422. auto SourceGen::GenerateRandomIdentifier(
  423. llvm::MutableArrayRef<char> dest_storage) -> void {
  424. llvm::ArrayRef<char> start_chars = IdentifierStartChars();
  425. llvm::ArrayRef<char> chars = IdentifierChars();
  426. llvm::StringRef ident(dest_storage.data(), dest_storage.size());
  427. do {
  428. dest_storage[0] =
  429. start_chars[absl::Uniform<int>(rng_, 0, start_chars.size())];
  430. for (int i : llvm::seq<int>(1, dest_storage.size())) {
  431. dest_storage[i] = chars[absl::Uniform<int>(rng_, 0, chars.size())];
  432. }
  433. } while (
  434. // TODO: Clean up and simplify this code. With some small refactorings and
  435. // post-processing we should be able to make this both easier to read and
  436. // less inefficient.
  437. llvm::any_of(
  438. Lex::TokenKind::KeywordTokens,
  439. [ident](auto token) { return ident == token.fixed_spelling(); }) ||
  440. llvm::is_contained(NonCarbonCppKeywords, ident) ||
  441. ident.ends_with("_t") || ident.ends_with("_MIN") ||
  442. ident.ends_with("_MAX") || ident.ends_with("_C") ||
  443. (llvm::is_contained({'i', 'u', 'f'}, ident[0]) &&
  444. llvm::all_of(ident.substr(1),
  445. [](const char c) { return llvm::isDigit(c); })));
  446. }
  447. // Appends a number of unique, random identifiers with a particular length to
  448. // the provided destination vector.
  449. //
  450. // Uses, and when necessary grows, a cached sequence of random identifiers with
  451. // the specified length. Because these are cached, this is efficient to call
  452. // repeatedly, but will not produce a different sequence of identifiers.
  453. auto SourceGen::AppendUniqueIdentifiers(
  454. int length, int number, llvm::SmallVectorImpl<llvm::StringRef>& dest)
  455. -> void {
  456. auto& [count, unique_idents] =
  457. unique_identifiers_by_length_.Insert(length, {}).value();
  458. // See if we need to grow our pool of unique identifiers with the requested
  459. // length.
  460. if (count < number) {
  461. // We'll need to insert exactly the requested new unique identifiers. All
  462. // our other inserts will find an existing entry.
  463. unique_idents.GrowForInsertCount(count - number);
  464. // Generate the needed number of identifiers.
  465. for ([[maybe_unused]] auto _ : llvm::seq<int>(count, number)) {
  466. // Allocate stable storage for the identifier so we can form stable
  467. // `StringRef`s to it.
  468. auto ident_storage =
  469. llvm::MutableArrayRef(reinterpret_cast<char*>(storage_.Allocate(
  470. /*Size=*/length, /*Alignment=*/1)),
  471. length);
  472. // Repeatedly generate novel identifiers of this length until we find a
  473. // new unique one.
  474. for (;;) {
  475. GenerateRandomIdentifier(ident_storage);
  476. auto result =
  477. unique_idents.Insert(llvm::StringRef(ident_storage.data(), length));
  478. if (result.is_inserted()) {
  479. break;
  480. }
  481. }
  482. }
  483. count = number;
  484. }
  485. // Append all the identifiers directly out of the set. We make no guarantees
  486. // about the relative order so we just use the non-deterministic order of the
  487. // set and avoid additional storage.
  488. //
  489. // TODO: It's awkward the `ForEach` here can't early-exit. This just walks the
  490. // whole set which is harmless if inefficient. We should add early exiting
  491. // the loop support to `Set` and update this code.
  492. unique_idents.ForEach([&](llvm::StringRef ident) {
  493. if (number > 0) {
  494. dest.push_back(ident);
  495. --number;
  496. }
  497. });
  498. CARBON_CHECK(number == 0);
  499. }
  500. // An array of the counts that should be used for each identifier length to
  501. // produce our desired distribution.
  502. //
  503. // Note that the zero-based index corresponds to a 1-based length, so the count
  504. // for identifiers of length 1 is at index 0.
  505. static constexpr std::array<int, 64> IdentifierLengthCounts = [] {
  506. std::array<int, 64> ident_length_counts;
  507. // For non-uniform distribution, we simulate a distribution roughly based on
  508. // the observed histogram of identifier lengths, but smoothed a bit and
  509. // reduced to small counts so that we cycle through all the lengths
  510. // reasonably quickly. We want sampling of even 10% of NumTokens from this
  511. // in a round-robin form to not be skewed overly much. This still inherently
  512. // compresses the long tail as we'd rather have coverage even though it
  513. // distorts the distribution a bit.
  514. //
  515. // The distribution here comes from a script that analyzes source code run
  516. // over a few directories of LLVM. The script renders a visual ascii-art
  517. // histogram along with the data for each bucket, and that output is
  518. // included in comments above each bucket size below to help visualize the
  519. // rough shape we're aiming for.
  520. //
  521. // 1 characters [3976] ███████████████████████████████▊
  522. ident_length_counts[0] = 40;
  523. // 2 characters [3724] █████████████████████████████▊
  524. ident_length_counts[1] = 40;
  525. // 3 characters [4173] █████████████████████████████████▍
  526. ident_length_counts[2] = 40;
  527. // 4 characters [5000] ████████████████████████████████████████
  528. ident_length_counts[3] = 50;
  529. // 5 characters [1568] ████████████▌
  530. ident_length_counts[4] = 20;
  531. // 6 characters [2226] █████████████████▊
  532. ident_length_counts[5] = 20;
  533. // 7 characters [2380] ███████████████████
  534. ident_length_counts[6] = 20;
  535. // 8 characters [1786] ██████████████▎
  536. ident_length_counts[7] = 18;
  537. // 9 characters [1397] ███████████▏
  538. ident_length_counts[8] = 12;
  539. // 10 characters [ 739] █████▉
  540. ident_length_counts[9] = 12;
  541. // 11 characters [ 779] ██████▎
  542. ident_length_counts[10] = 12;
  543. // 12 characters [1344] ██████████▊
  544. ident_length_counts[11] = 12;
  545. // 13 characters [ 498] ████
  546. ident_length_counts[12] = 5;
  547. // 14 characters [ 284] ██▎
  548. ident_length_counts[13] = 3;
  549. // 15 characters [ 172] █▍
  550. // 16 characters [ 278] ██▎
  551. // 17 characters [ 191] █▌
  552. // 18 characters [ 207] █▋
  553. for (int i = 14; i < 18; ++i) {
  554. ident_length_counts[i] = 2;
  555. }
  556. // 19 - 63 characters are all <100 but non-zero, and we map them to 1 for
  557. // coverage despite slightly over weighting the tail.
  558. for (int i = 18; i < 64; ++i) {
  559. ident_length_counts[i] = 1;
  560. }
  561. return ident_length_counts;
  562. }();
  563. // A template function that implements the common logic of `GetIdentifiers` and
  564. // `GetUniqueIdentifiers`. Most parameters correspond to the parameters of those
  565. // functions. Additionally, an `AppendFunc` callable is provided to implement
  566. // the appending operation.
  567. //
  568. // The main functionality provided here is collecting the correct number of
  569. // identifiers from each of the lengths in the range [min_length, max_length]
  570. // and either in our default representative distribution or a uniform
  571. // distribution.
  572. auto SourceGen::GetIdentifiersImpl(int number, int min_length, int max_length,
  573. bool uniform,
  574. llvm::function_ref<AppendFn> append)
  575. -> llvm::SmallVector<llvm::StringRef> {
  576. CARBON_CHECK(min_length <= max_length);
  577. CARBON_CHECK(
  578. uniform || max_length <= 64,
  579. "Cannot produce a meaningful non-uniform distribution of lengths longer "
  580. "than 64 as those are exceedingly rare in our observed data sets.");
  581. llvm::SmallVector<llvm::StringRef> idents;
  582. idents.reserve(number);
  583. // First, compute the total weight of the distribution so we know how many
  584. // identifiers we'll get each time we collect from it.
  585. int num_lengths = max_length - min_length + 1;
  586. auto length_counts =
  587. llvm::ArrayRef(IdentifierLengthCounts).slice(min_length - 1, num_lengths);
  588. int count_sum = uniform ? num_lengths : Sum(length_counts);
  589. CARBON_CHECK(count_sum >= 1);
  590. int number_rem = number % count_sum;
  591. // Finally, walk through each length in the distribution.
  592. for (int length : llvm::seq_inclusive(min_length, max_length)) {
  593. // Scale how many identifiers we want of this length if computing a
  594. // non-uniform distribution. For uniform, we always take one.
  595. int scale = uniform ? 1 : IdentifierLengthCounts[length - 1];
  596. // Now we can compute how many identifiers of this length to request.
  597. int length_count = (number / count_sum) * scale;
  598. if (number_rem > 0) {
  599. int rem_adjustment = std::min(scale, number_rem);
  600. length_count += rem_adjustment;
  601. number_rem -= rem_adjustment;
  602. }
  603. append(length, length_count, idents);
  604. }
  605. CARBON_CHECK(number_rem == 0, "Unexpected number remaining: {0}", number_rem);
  606. CARBON_CHECK(static_cast<int>(idents.size()) == number,
  607. "Ended up with {0} identifiers instead of the requested {1}",
  608. idents.size(), number);
  609. return idents;
  610. }
  611. // Returns a shuffled sequence of integers in the range [min, max].
  612. //
  613. // The order of the returned integers is random, but each integer in the range
  614. // appears the same number of times in the result, with the number of
  615. // appearances rounded up for lower numbers and rounded down for higher numbers
  616. // in order to exactly produce `number` results.
  617. auto SourceGen::GetShuffledInts(int number, int min, int max)
  618. -> llvm::SmallVector<int> {
  619. llvm::SmallVector<int> ints;
  620. ints.reserve(number);
  621. // Evenly distribute to each value between min and max.
  622. int num_values = max - min + 1;
  623. for (int i : llvm::seq_inclusive(min, max)) {
  624. int i_count = number / num_values;
  625. i_count += i < (min + (number % num_values));
  626. ints.append(i_count, i);
  627. }
  628. CARBON_CHECK(static_cast<int>(ints.size()) == number);
  629. std::shuffle(ints.begin(), ints.end(), rng_);
  630. return ints;
  631. }
  632. // A helper to pop series of unique identifiers off a sequence of random
  633. // identifiers that may have duplicates.
  634. //
  635. // This is particularly designed to work with the sequences of non-unique
  636. // identifiers produced by `GetShuffledIdentifiers` with the important property
  637. // that while popping off unique identifiers found in the shuffled list, we
  638. // don't change the distribution of identifier lengths.
  639. //
  640. // The uniqueness is only per-instance of the class, and so an instance can be
  641. // used to extract a series of names that share a scope.
  642. //
  643. // It works by scanning the sequence to extract each unique identifier found,
  644. // swapping it to the back and popping it off the list. This does shuffle the
  645. // order, but it isn't expected to do so in an interesting way.
  646. //
  647. // It also provides a fallback path in case there are no unique identifiers left
  648. // which computes fresh, random identifiers with the same length as the next one
  649. // in the sequence until a unique one is found.
  650. //
  651. // For simplicity of the fallback path, the lifetime of the identifiers produced
  652. // is bound to the lifetime of the popper instance, and not the generator as a
  653. // whole. If this is ever a problematic constraint, we can start copying
  654. // fallback identifiers into the generator's storage.
  655. class SourceGen::UniqueIdentifierPopper {
  656. public:
  657. explicit UniqueIdentifierPopper(SourceGen& gen,
  658. llvm::SmallVectorImpl<llvm::StringRef>& data)
  659. : gen_(&gen), data_(&data), it_(data_->rbegin()) {}
  660. // Pop the next unique identifier that can be found in the data, or synthesize
  661. // one with a valid length. Always consumes exactly one identifier from the
  662. // data.
  663. //
  664. // Note that the lifetime of the underlying identifier is that of the popper
  665. // and not the underlying data.
  666. auto Pop() -> llvm::StringRef {
  667. for (auto end = data_->rend(); it_ != end; ++it_) {
  668. auto insert = set_.Insert(*it_);
  669. if (!insert.is_inserted()) {
  670. continue;
  671. }
  672. if (it_ != data_->rbegin()) {
  673. std::swap(*data_->rbegin(), *it_);
  674. }
  675. CARBON_CHECK(insert.key() == data_->back());
  676. return data_->pop_back_val();
  677. }
  678. // Out of unique elements. Overwrite the back, preserving its length,
  679. // generating a new identifiers until we find a unique one and return that.
  680. // This ensures we continue to consume the structure and produce the same
  681. // size identifiers even in the fallback.
  682. int length = data_->pop_back_val().size();
  683. auto fallback_ident_storage =
  684. llvm::MutableArrayRef(reinterpret_cast<char*>(gen_->storage_.Allocate(
  685. /*Size=*/length, /*Alignment=*/1)),
  686. length);
  687. for (;;) {
  688. gen_->GenerateRandomIdentifier(fallback_ident_storage);
  689. auto fallback_id = llvm::StringRef(fallback_ident_storage.data(), length);
  690. if (set_.Insert(fallback_id).is_inserted()) {
  691. return fallback_id;
  692. }
  693. }
  694. }
  695. private:
  696. SourceGen* gen_;
  697. llvm::SmallVectorImpl<llvm::StringRef>* data_;
  698. llvm::SmallVectorImpl<llvm::StringRef>::reverse_iterator it_;
  699. Set<llvm::StringRef> set_;
  700. };
  701. // Generates a function declaration and writes it to the provided stream.
  702. //
  703. // The declaration can be configured with a function name, private modifier,
  704. // whether it is a method, the parameter count, an how indented it is.
  705. //
  706. // This is also provided a collection of identifiers to consume as parameter
  707. // names -- it will use a unique popper to extract unique parameter names from
  708. // this collection.
  709. auto SourceGen::GenerateFunctionDecl(
  710. llvm::StringRef name, bool is_private, bool is_method, int param_count,
  711. llvm::StringRef indent, llvm::SmallVectorImpl<llvm::StringRef>& param_names,
  712. llvm::function_ref<auto()->llvm::StringRef> get_type_name,
  713. llvm::raw_ostream& os) -> void {
  714. os << indent << "// TODO: make better comment text\n";
  715. if (!IsCpp()) {
  716. os << indent << (is_private ? "private " : "") << "fn " << name;
  717. if (is_method) {
  718. os << "[self: Self]";
  719. }
  720. } else {
  721. os << indent;
  722. if (!is_method) {
  723. os << "static ";
  724. }
  725. os << "auto " << name;
  726. }
  727. os << "(";
  728. if (param_count >
  729. (is_method ? NumSingleLineMethodParams : NumSingleLineFunctionParams)) {
  730. os << "\n" << indent << " ";
  731. }
  732. UniqueIdentifierPopper unique_param_names(*this, param_names);
  733. for (int i : llvm::seq(param_count)) {
  734. if (i > 0) {
  735. if ((i % MaxParamsPerLine) == 0) {
  736. os << ",\n" << indent << " ";
  737. } else {
  738. os << ", ";
  739. }
  740. }
  741. if (!IsCpp()) {
  742. os << unique_param_names.Pop() << ": " << get_type_name();
  743. } else {
  744. os << get_type_name() << " " << unique_param_names.Pop();
  745. }
  746. }
  747. os << ")";
  748. os << " -> " << get_type_name();
  749. os << ";\n";
  750. }
  751. // Generate a class definition and write it to the provided stream.
  752. //
  753. // The structure of the definition is guided by the `params` provided, and it
  754. // consumes the provided state.
  755. auto SourceGen::GenerateClassDef(const ClassParams& params,
  756. ClassGenState& state, llvm::raw_ostream& os)
  757. -> void {
  758. llvm::StringRef name = state.class_names().pop_back_val();
  759. os << "// TODO: make better comment text\n";
  760. os << "class " << name << " {\n";
  761. if (IsCpp()) {
  762. os << " public:\n";
  763. }
  764. // Field types can't be the class we're currently declaring. We enforce this
  765. // by collecting them before inserting that type into the valid set.
  766. llvm::SmallVector<llvm::StringRef> field_type_names;
  767. field_type_names.reserve(params.private_field_decls);
  768. for ([[maybe_unused]] auto _ : llvm::seq(params.private_field_decls)) {
  769. field_type_names.push_back(state.GetValidTypeName());
  770. }
  771. // Mark this class as now a valid type now that field type names have been
  772. // collected. We can reference this class from functions and methods within
  773. // the definition.
  774. state.AddValidTypeName(name);
  775. UniqueIdentifierPopper unique_member_names(*this, state.member_names());
  776. llvm::ListSeparator line_sep("\n");
  777. for ([[maybe_unused]] auto _ : llvm::seq(params.public_function_decls)) {
  778. os << line_sep;
  779. GenerateFunctionDecl(
  780. unique_member_names.Pop(), /*is_private=*/false,
  781. /*is_method=*/false,
  782. state.public_function_param_counts().pop_back_val(),
  783. /*indent=*/" ", state.param_names(),
  784. [&] { return state.GetValidTypeName(); }, os);
  785. }
  786. for ([[maybe_unused]] auto _ : llvm::seq(params.public_method_decls)) {
  787. os << line_sep;
  788. GenerateFunctionDecl(
  789. unique_member_names.Pop(), /*is_private=*/false,
  790. /*is_method=*/true, state.public_method_param_counts().pop_back_val(),
  791. /*indent=*/" ", state.param_names(),
  792. [&] { return state.GetValidTypeName(); }, os);
  793. }
  794. if (IsCpp()) {
  795. os << "\n private:\n";
  796. // Reset the separator.
  797. line_sep = llvm::ListSeparator("\n");
  798. }
  799. for ([[maybe_unused]] auto _ : llvm::seq(params.private_function_decls)) {
  800. os << line_sep;
  801. GenerateFunctionDecl(
  802. unique_member_names.Pop(), /*is_private=*/true,
  803. /*is_method=*/false,
  804. state.private_function_param_counts().pop_back_val(),
  805. /*indent=*/" ", state.param_names(),
  806. [&] { return state.GetValidTypeName(); }, os);
  807. }
  808. for ([[maybe_unused]] auto _ : llvm::seq(params.private_method_decls)) {
  809. os << line_sep;
  810. GenerateFunctionDecl(
  811. unique_member_names.Pop(), /*is_private=*/true,
  812. /*is_method=*/true, state.private_method_param_counts().pop_back_val(),
  813. /*indent=*/" ", state.param_names(),
  814. [&] { return state.GetValidTypeName(); }, os);
  815. }
  816. os << line_sep;
  817. for (llvm::StringRef type_name : field_type_names) {
  818. if (!IsCpp()) {
  819. os << " private var " << unique_member_names.Pop() << ": " << type_name
  820. << ";\n";
  821. } else {
  822. os << " " << type_name << " " << unique_member_names.Pop() << ";\n";
  823. }
  824. }
  825. os << "}" << (IsCpp() ? ";" : "") << "\n";
  826. }
  827. } // namespace Carbon::Testing