source_gen.cpp 37 KB

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