source_gen.cpp 37 KB

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