value.h 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744
  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. #ifndef CARBON_EXPLORER_AST_VALUE_H_
  5. #define CARBON_EXPLORER_AST_VALUE_H_
  6. #include <optional>
  7. #include <string>
  8. #include <variant>
  9. #include <vector>
  10. #include "common/ostream.h"
  11. #include "explorer/ast/address.h"
  12. #include "explorer/ast/bindings.h"
  13. #include "explorer/ast/declaration.h"
  14. #include "explorer/ast/element.h"
  15. #include "explorer/ast/element_path.h"
  16. #include "explorer/ast/expression_category.h"
  17. #include "explorer/ast/statement.h"
  18. #include "explorer/base/nonnull.h"
  19. #include "llvm/ADT/StringMap.h"
  20. #include "llvm/Support/Compiler.h"
  21. namespace Carbon {
  22. class AssociatedConstant;
  23. class ChoiceType;
  24. class TupleValue;
  25. // A trait type that describes how to allocate an instance of `T` in an arena.
  26. // Returns the created object, which is not required to be of type `T`.
  27. template <typename T>
  28. struct AllocateTrait {
  29. template <typename... Args>
  30. static auto New(Nonnull<Arena*> arena, Args&&... args) -> Nonnull<const T*> {
  31. return arena->New<T>(std::forward<Args>(args)...);
  32. }
  33. };
  34. using VTable =
  35. llvm::StringMap<std::pair<Nonnull<const CallableDeclaration*>, int>>;
  36. // Returns a pointer to an empty VTable that will never be deallocated.
  37. //
  38. // Using this instead of `new VTable()` avoids unnecessary allocations, and
  39. // takes better advantage of Arena canonicalization when a VTable pointer is
  40. // used as a constructor argument.
  41. inline auto EmptyVTable() -> Nonnull<const VTable*> {
  42. static Nonnull<const VTable*> result = new VTable();
  43. return result;
  44. }
  45. // Abstract base class of all AST nodes representing values.
  46. //
  47. // Value and its derived classes support LLVM-style RTTI, including
  48. // llvm::isa, llvm::cast, and llvm::dyn_cast. To support this, every
  49. // class derived from Value must provide a `classof` operation, and
  50. // every concrete derived class must have a corresponding enumerator
  51. // in `Kind`; see https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html for
  52. // details.
  53. //
  54. // Arena's canonicalization support is enabled for Value and all derived types.
  55. // As a result, all Values must be immutable, and all their constructor
  56. // arguments must be copyable, equality-comparable, and hashable. See
  57. // Arena's documentation for details.
  58. class Value : public Printable<Value> {
  59. public:
  60. using EnableCanonicalizedAllocation = void;
  61. enum class Kind {
  62. #define CARBON_VALUE_KIND(kind) kind,
  63. #include "explorer/ast/value_kinds.def"
  64. };
  65. Value(const Value&) = delete;
  66. auto operator=(const Value&) -> Value& = delete;
  67. // Call `f` on this value, cast to its most-derived type. `R` specifies the
  68. // expected return type of `f`.
  69. template <typename R, typename F>
  70. auto Visit(F f) const -> R;
  71. void Print(llvm::raw_ostream& out) const;
  72. // Returns the sub-Value specified by `path`, which must be a valid element
  73. // path for *this. If the sub-Value is a method and its self_pattern is an
  74. // AddrPattern, then pass the LocationValue representing the receiver as
  75. // `me_value`, otherwise pass `*this`.
  76. auto GetElement(Nonnull<Arena*> arena, const ElementPath& path,
  77. SourceLocation source_loc,
  78. std::optional<Nonnull<const Value*>> me_value) const
  79. -> ErrorOr<Nonnull<const Value*>>;
  80. // Returns a copy of *this, but with the sub-Value specified by `path`
  81. // set to `field_value`. `path` must be a valid field path for *this.
  82. auto SetField(Nonnull<Arena*> arena, const ElementPath& path,
  83. Nonnull<const Value*> field_value,
  84. SourceLocation source_loc) const
  85. -> ErrorOr<Nonnull<const Value*>>;
  86. // Returns the enumerator corresponding to the most-derived type of this
  87. // object.
  88. auto kind() const -> Kind { return kind_; }
  89. protected:
  90. // Constructs a Value. `kind` must be the enumerator corresponding to the
  91. // most-derived type being constructed.
  92. explicit Value(Kind kind) : kind_(kind) {}
  93. private:
  94. const Kind kind_;
  95. };
  96. // Returns whether the fully-resolved kind that this value will eventually have
  97. // is currently unknown, because it depends on a generic parameter.
  98. inline auto IsValueKindDependent(Nonnull<const Value*> type) -> bool {
  99. return type->kind() == Value::Kind::VariableType ||
  100. type->kind() == Value::Kind::AssociatedConstant;
  101. }
  102. // Base class for types holding contextual information by which we can
  103. // determine whether values are equal.
  104. class EqualityContext {
  105. public:
  106. virtual auto VisitEqualValues(
  107. Nonnull<const Value*> value,
  108. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const
  109. -> bool = 0;
  110. protected:
  111. virtual ~EqualityContext() = default;
  112. };
  113. auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2,
  114. std::optional<Nonnull<const EqualityContext*>> equality_ctx)
  115. -> bool;
  116. auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2,
  117. std::optional<Nonnull<const EqualityContext*>> equality_ctx)
  118. -> bool;
  119. // Call the given `visitor` on all values nested within the given value,
  120. // including `value` itself, in a preorder traversal. Aborts and returns
  121. // `false` if `visitor` returns `false`, otherwise returns `true`.
  122. auto VisitNestedValues(Nonnull<const Value*> value,
  123. llvm::function_ref<bool(const Value*)> visitor) -> bool;
  124. // An integer value.
  125. class IntValue : public Value {
  126. public:
  127. explicit IntValue(int value) : Value(Kind::IntValue), value_(value) {}
  128. static auto classof(const Value* value) -> bool {
  129. return value->kind() == Kind::IntValue;
  130. }
  131. template <typename F>
  132. auto Decompose(F f) const {
  133. return f(value_);
  134. }
  135. auto value() const -> int { return value_; }
  136. private:
  137. int value_;
  138. };
  139. // A function or bound method value.
  140. class FunctionOrMethodValue : public Value {
  141. public:
  142. explicit FunctionOrMethodValue(
  143. Kind kind, Nonnull<const FunctionDeclaration*> declaration,
  144. Nonnull<const Bindings*> bindings)
  145. : Value(kind), declaration_(declaration), bindings_(bindings) {}
  146. static auto classof(const Value* value) -> bool {
  147. return value->kind() == Kind::FunctionValue ||
  148. value->kind() == Kind::BoundMethodValue;
  149. }
  150. auto declaration() const -> const FunctionDeclaration& {
  151. return *declaration_;
  152. }
  153. auto bindings() const -> const Bindings& { return *bindings_; }
  154. auto type_args() const -> const BindingMap& { return bindings_->args(); }
  155. auto witnesses() const -> const ImplWitnessMap& {
  156. return bindings_->witnesses();
  157. }
  158. private:
  159. Nonnull<const FunctionDeclaration*> declaration_;
  160. Nonnull<const Bindings*> bindings_;
  161. };
  162. // A function value.
  163. class FunctionValue : public FunctionOrMethodValue {
  164. public:
  165. explicit FunctionValue(Nonnull<const FunctionDeclaration*> declaration,
  166. Nonnull<const Bindings*> bindings)
  167. : FunctionOrMethodValue(Kind::FunctionValue, declaration, bindings) {}
  168. static auto classof(const Value* value) -> bool {
  169. return value->kind() == Kind::FunctionValue;
  170. }
  171. template <typename F>
  172. auto Decompose(F f) const {
  173. return f(&declaration(), &bindings());
  174. }
  175. };
  176. // A bound method value. It includes the receiver object.
  177. class BoundMethodValue : public FunctionOrMethodValue {
  178. public:
  179. explicit BoundMethodValue(Nonnull<const FunctionDeclaration*> declaration,
  180. Nonnull<const Value*> receiver,
  181. Nonnull<const Bindings*> bindings)
  182. : FunctionOrMethodValue(Kind::BoundMethodValue, declaration, bindings),
  183. receiver_(receiver) {}
  184. static auto classof(const Value* value) -> bool {
  185. return value->kind() == Kind::BoundMethodValue;
  186. }
  187. template <typename F>
  188. auto Decompose(F f) const {
  189. return f(&declaration(), receiver_, &bindings());
  190. }
  191. auto receiver() const -> Nonnull<const Value*> { return receiver_; }
  192. private:
  193. Nonnull<const Value*> receiver_;
  194. };
  195. // A destructor value.
  196. class DestructorValue : public Value {
  197. public:
  198. explicit DestructorValue(Nonnull<const DestructorDeclaration*> declaration)
  199. : Value(Kind::DestructorValue), declaration_(declaration) {}
  200. static auto classof(const Value* value) -> bool {
  201. return value->kind() == Kind::DestructorValue;
  202. }
  203. template <typename F>
  204. auto Decompose(F f) const {
  205. return f(declaration_);
  206. }
  207. auto declaration() const -> const DestructorDeclaration& {
  208. return *declaration_;
  209. }
  210. private:
  211. Nonnull<const DestructorDeclaration*> declaration_;
  212. };
  213. // The value of a location in memory.
  214. class LocationValue : public Value {
  215. public:
  216. explicit LocationValue(Address value)
  217. : Value(Kind::LocationValue), value_(std::move(value)) {}
  218. static auto classof(const Value* value) -> bool {
  219. return value->kind() == Kind::LocationValue;
  220. }
  221. template <typename F>
  222. auto Decompose(F f) const {
  223. return f(value_);
  224. }
  225. auto address() const -> const Address& { return value_; }
  226. private:
  227. Address value_;
  228. };
  229. // Contains the result of the evaluation of an expression, including a value,
  230. // the original expression category, and an optional address if available.
  231. class ExpressionResult {
  232. public:
  233. static auto Value(Nonnull<const Carbon::Value*> v) -> ExpressionResult {
  234. return ExpressionResult(v, std::nullopt, ExpressionCategory::Value);
  235. }
  236. static auto Reference(Nonnull<const Carbon::Value*> v, Address address)
  237. -> ExpressionResult {
  238. return ExpressionResult(v, std::move(address),
  239. ExpressionCategory::Reference);
  240. }
  241. static auto Initializing(Nonnull<const Carbon::Value*> v, Address address)
  242. -> ExpressionResult {
  243. return ExpressionResult(v, std::move(address),
  244. ExpressionCategory::Initializing);
  245. }
  246. ExpressionResult(Nonnull<const Carbon::Value*> v,
  247. std::optional<Address> address, ExpressionCategory cat)
  248. : value_(v), address_(std::move(address)), expr_cat_(cat) {}
  249. auto value() const -> Nonnull<const Carbon::Value*> { return value_; }
  250. auto address() const -> const std::optional<Address>& { return address_; }
  251. auto expression_category() const -> ExpressionCategory { return expr_cat_; }
  252. private:
  253. Nonnull<const Carbon::Value*> value_;
  254. std::optional<Address> address_;
  255. ExpressionCategory expr_cat_;
  256. };
  257. // Represents the result of the evaluation of a reference expression, and
  258. // holds the resulting `Value*` and its `Address`.
  259. class ReferenceExpressionValue : public Value {
  260. public:
  261. ReferenceExpressionValue(Nonnull<const Value*> value, Address address)
  262. : Value(Kind::ReferenceExpressionValue),
  263. value_(value),
  264. address_(std::move(address)) {}
  265. static auto classof(const Value* value) -> bool {
  266. return value->kind() == Kind::ReferenceExpressionValue;
  267. }
  268. template <typename F>
  269. auto Decompose(F f) const {
  270. return f(value_, address_);
  271. }
  272. auto value() const -> Nonnull<const Value*> { return value_; }
  273. auto address() const -> const Address& { return address_; }
  274. private:
  275. Nonnull<const Value*> value_;
  276. Address address_;
  277. };
  278. // A pointer value
  279. class PointerValue : public Value {
  280. public:
  281. explicit PointerValue(Address value)
  282. : Value(Kind::PointerValue), value_(std::move(value)) {}
  283. static auto classof(const Value* value) -> bool {
  284. return value->kind() == Kind::PointerValue;
  285. }
  286. template <typename F>
  287. auto Decompose(F f) const {
  288. return f(value_);
  289. }
  290. auto address() const -> const Address& { return value_; }
  291. private:
  292. Address value_;
  293. };
  294. // A bool value.
  295. class BoolValue : public Value {
  296. public:
  297. explicit BoolValue(bool value) : Value(Kind::BoolValue), value_(value) {}
  298. static auto classof(const Value* value) -> bool {
  299. return value->kind() == Kind::BoolValue;
  300. }
  301. template <typename F>
  302. auto Decompose(F f) const {
  303. return f(value_);
  304. }
  305. auto value() const -> bool { return value_; }
  306. private:
  307. bool value_;
  308. };
  309. // A value of a struct type. Note that the expression `{}` is a value of type
  310. // `{} as type`; the former is a `StructValue` and the latter is a
  311. // `StructType`.
  312. class StructValue : public Value {
  313. public:
  314. explicit StructValue(std::vector<NamedValue> elements)
  315. : Value(Kind::StructValue), elements_(std::move(elements)) {}
  316. static auto classof(const Value* value) -> bool {
  317. return value->kind() == Kind::StructValue;
  318. }
  319. template <typename F>
  320. auto Decompose(F f) const {
  321. return f(elements_);
  322. }
  323. auto elements() const -> llvm::ArrayRef<NamedValue> { return elements_; }
  324. // Returns the value of the field named `name` in this struct, or
  325. // nullopt if there is no such field.
  326. auto FindField(std::string_view name) const
  327. -> std::optional<Nonnull<const Value*>>;
  328. private:
  329. std::vector<NamedValue> elements_;
  330. };
  331. // A value of a nominal class type, i.e., an object.
  332. class NominalClassValue : public Value {
  333. public:
  334. static constexpr llvm::StringLiteral BaseField{"base"};
  335. // Takes the class type, inits, an optional base, a pointer to a
  336. // NominalClassValue*, that must be common to all NominalClassValue of the
  337. // same object. The pointee is updated, when `NominalClassValue`s are
  338. // constructed, to point to the `NominalClassValue` corresponding to the
  339. // child-most class type. Sets *class_value_ptr = this, which corresponds to
  340. // the static type of the value matching its dynamic type.
  341. NominalClassValue(Nonnull<const Value*> type, Nonnull<const Value*> inits,
  342. std::optional<Nonnull<const NominalClassValue*>> base,
  343. Nonnull<const NominalClassValue** const> class_value_ptr);
  344. static auto classof(const Value* value) -> bool {
  345. return value->kind() == Kind::NominalClassValue;
  346. }
  347. template <typename F>
  348. auto Decompose(F f) const {
  349. return f(type_, inits_, base_, class_value_ptr_);
  350. }
  351. auto type() const -> const Value& { return *type_; }
  352. auto inits() const -> const Value& { return *inits_; }
  353. auto base() const -> std::optional<Nonnull<const NominalClassValue*>> {
  354. return base_;
  355. }
  356. // Returns a pointer of pointer to the child-most class value.
  357. auto class_value_ptr() const -> Nonnull<const NominalClassValue**> {
  358. return class_value_ptr_;
  359. }
  360. private:
  361. Nonnull<const Value*> type_;
  362. Nonnull<const Value*> inits_; // The initializing StructValue.
  363. std::optional<Nonnull<const NominalClassValue*>> base_;
  364. Nonnull<const NominalClassValue** const> class_value_ptr_;
  365. };
  366. // An alternative constructor value.
  367. class AlternativeConstructorValue : public Value {
  368. public:
  369. AlternativeConstructorValue(Nonnull<const ChoiceType*> choice,
  370. Nonnull<const AlternativeSignature*> alternative)
  371. : Value(Kind::AlternativeConstructorValue),
  372. choice_(choice),
  373. alternative_(alternative) {}
  374. static auto classof(const Value* value) -> bool {
  375. return value->kind() == Kind::AlternativeConstructorValue;
  376. }
  377. template <typename F>
  378. auto Decompose(F f) const {
  379. return f(&choice(), &alternative());
  380. }
  381. auto choice() const -> const ChoiceType& { return *choice_; }
  382. auto alternative() const -> const AlternativeSignature& {
  383. return *alternative_;
  384. }
  385. private:
  386. Nonnull<const ChoiceType*> choice_;
  387. Nonnull<const AlternativeSignature*> alternative_;
  388. };
  389. // An alternative value.
  390. class AlternativeValue : public Value {
  391. public:
  392. AlternativeValue(Nonnull<const ChoiceType*> choice,
  393. Nonnull<const AlternativeSignature*> alternative,
  394. std::optional<Nonnull<const TupleValue*>> argument)
  395. : Value(Kind::AlternativeValue),
  396. choice_(choice),
  397. alternative_(alternative),
  398. argument_(argument) {}
  399. static auto classof(const Value* value) -> bool {
  400. return value->kind() == Kind::AlternativeValue;
  401. }
  402. template <typename F>
  403. auto Decompose(F f) const {
  404. return f(&choice(), &alternative(), argument_);
  405. }
  406. auto choice() const -> const ChoiceType& { return *choice_; }
  407. auto alternative() const -> const AlternativeSignature& {
  408. return *alternative_;
  409. }
  410. auto argument() const -> std::optional<Nonnull<const TupleValue*>> {
  411. return argument_;
  412. }
  413. private:
  414. Nonnull<const ChoiceType*> choice_;
  415. Nonnull<const AlternativeSignature*> alternative_;
  416. std::optional<Nonnull<const TupleValue*>> argument_;
  417. };
  418. // Base class for tuple types and tuple values. These are the same other than
  419. // their type-of-type, but we separate them to make it easier to tell types and
  420. // values apart.
  421. class TupleValueBase : public Value {
  422. public:
  423. explicit TupleValueBase(Value::Kind kind,
  424. std::vector<Nonnull<const Value*>> elements)
  425. : Value(kind), elements_(std::move(elements)) {}
  426. auto elements() const -> llvm::ArrayRef<Nonnull<const Value*>> {
  427. return elements_;
  428. }
  429. static auto classof(const Value* value) -> bool {
  430. return value->kind() == Kind::TupleValue ||
  431. value->kind() == Kind::TupleType;
  432. }
  433. template <typename F>
  434. auto Decompose(F f) const {
  435. return f(elements_);
  436. }
  437. private:
  438. std::vector<Nonnull<const Value*>> elements_;
  439. };
  440. // A tuple value.
  441. class TupleValue : public TupleValueBase {
  442. public:
  443. // An empty tuple.
  444. static auto Empty() -> Nonnull<const TupleValue*> {
  445. static const TupleValue empty =
  446. TupleValue(std::vector<Nonnull<const Value*>>());
  447. return static_cast<Nonnull<const TupleValue*>>(&empty);
  448. }
  449. explicit TupleValue(std::vector<Nonnull<const Value*>> elements)
  450. : TupleValueBase(Kind::TupleValue, std::move(elements)) {}
  451. static auto classof(const Value* value) -> bool {
  452. return value->kind() == Kind::TupleValue;
  453. }
  454. };
  455. // A tuple type. These values are produced by converting a tuple value
  456. // containing only types to type `type`.
  457. class TupleType : public TupleValueBase {
  458. public:
  459. // The unit type.
  460. static auto Empty() -> Nonnull<const TupleType*> {
  461. static const TupleType empty =
  462. TupleType(std::vector<Nonnull<const Value*>>());
  463. return static_cast<Nonnull<const TupleType*>>(&empty);
  464. }
  465. explicit TupleType(std::vector<Nonnull<const Value*>> elements)
  466. : TupleValueBase(Kind::TupleType, std::move(elements)) {}
  467. static auto classof(const Value* value) -> bool {
  468. return value->kind() == Kind::TupleType;
  469. }
  470. };
  471. // A binding placeholder value.
  472. class BindingPlaceholderValue : public Value {
  473. public:
  474. // Represents the `_` placeholder.
  475. explicit BindingPlaceholderValue() : Value(Kind::BindingPlaceholderValue) {}
  476. // Represents a named placeholder.
  477. explicit BindingPlaceholderValue(ValueNodeView value_node)
  478. : Value(Kind::BindingPlaceholderValue),
  479. value_node_(std::move(value_node)) {}
  480. static auto classof(const Value* value) -> bool {
  481. return value->kind() == Kind::BindingPlaceholderValue;
  482. }
  483. template <typename F>
  484. auto Decompose(F f) const {
  485. return value_node_ ? f(*value_node_) : f();
  486. }
  487. auto value_node() const -> const std::optional<ValueNodeView>& {
  488. return value_node_;
  489. }
  490. private:
  491. std::optional<ValueNodeView> value_node_;
  492. };
  493. // Value for addr pattern
  494. class AddrValue : public Value {
  495. public:
  496. explicit AddrValue(Nonnull<const Value*> pattern)
  497. : Value(Kind::AddrValue), pattern_(pattern) {}
  498. static auto classof(const Value* value) -> bool {
  499. return value->kind() == Kind::AddrValue;
  500. }
  501. template <typename F>
  502. auto Decompose(F f) const {
  503. return f(pattern_);
  504. }
  505. auto pattern() const -> const Value& { return *pattern_; }
  506. private:
  507. Nonnull<const Value*> pattern_;
  508. };
  509. // Value for uninitialized local variables.
  510. class UninitializedValue : public Value {
  511. public:
  512. explicit UninitializedValue(Nonnull<const Value*> pattern)
  513. : Value(Kind::UninitializedValue), pattern_(pattern) {}
  514. static auto classof(const Value* value) -> bool {
  515. return value->kind() == Kind::UninitializedValue;
  516. }
  517. template <typename F>
  518. auto Decompose(F f) const {
  519. return f(pattern_);
  520. }
  521. auto pattern() const -> const Value& { return *pattern_; }
  522. private:
  523. Nonnull<const Value*> pattern_;
  524. };
  525. // The int type.
  526. class IntType : public Value {
  527. public:
  528. IntType() : Value(Kind::IntType) {}
  529. static auto classof(const Value* value) -> bool {
  530. return value->kind() == Kind::IntType;
  531. }
  532. template <typename F>
  533. auto Decompose(F f) const {
  534. return f();
  535. }
  536. };
  537. // The bool type.
  538. class BoolType : public Value {
  539. public:
  540. BoolType() : Value(Kind::BoolType) {}
  541. static auto classof(const Value* value) -> bool {
  542. return value->kind() == Kind::BoolType;
  543. }
  544. template <typename F>
  545. auto Decompose(F f) const {
  546. return f();
  547. }
  548. };
  549. // A type type.
  550. class TypeType : public Value {
  551. public:
  552. TypeType() : Value(Kind::TypeType) {}
  553. static auto classof(const Value* value) -> bool {
  554. return value->kind() == Kind::TypeType;
  555. }
  556. template <typename F>
  557. auto Decompose(F f) const {
  558. return f();
  559. }
  560. };
  561. // A function type.
  562. class FunctionType : public Value {
  563. public:
  564. // An explicit function parameter that is a `:!` binding:
  565. //
  566. // fn MakeEmptyVector(T:! type) -> Vector(T);
  567. struct GenericParameter : public HashFromDecompose<GenericParameter> {
  568. template <typename F>
  569. auto Decompose(F f) const {
  570. return f(index, binding);
  571. }
  572. size_t index;
  573. Nonnull<const GenericBinding*> binding;
  574. };
  575. // For methods with unbound `self` parameters.
  576. struct MethodSelf : public HashFromDecompose<MethodSelf> {
  577. template <typename F>
  578. auto Decompose(F f) const {
  579. return f(addr_self, self_type);
  580. }
  581. // True if `self` parameter uses an `addr` pattern.
  582. bool addr_self;
  583. // Type of `self` parameter.
  584. const Value* self_type;
  585. };
  586. FunctionType(std::optional<MethodSelf> method_self,
  587. Nonnull<const Value*> parameters,
  588. Nonnull<const Value*> return_type)
  589. : FunctionType(method_self, parameters, {}, return_type, {}, {},
  590. /*is_initializing=*/false) {}
  591. FunctionType(std::optional<MethodSelf> method_self,
  592. Nonnull<const Value*> parameters,
  593. std::vector<GenericParameter> generic_parameters,
  594. Nonnull<const Value*> return_type,
  595. std::vector<Nonnull<const GenericBinding*>> deduced_bindings,
  596. std::vector<Nonnull<const ImplBinding*>> impl_bindings,
  597. bool is_initializing)
  598. : Value(Kind::FunctionType),
  599. method_self_(method_self),
  600. parameters_(parameters),
  601. generic_parameters_(std::move(generic_parameters)),
  602. return_type_(return_type),
  603. deduced_bindings_(std::move(deduced_bindings)),
  604. impl_bindings_(std::move(impl_bindings)),
  605. is_initializing_(is_initializing) {}
  606. struct ExceptSelf : public HashFromDecompose<ExceptSelf> {
  607. template <typename F>
  608. auto Decompose(F f) const {
  609. return f();
  610. }
  611. };
  612. FunctionType(ExceptSelf, const FunctionType* clone)
  613. : FunctionType(std::nullopt, clone->parameters_,
  614. clone->generic_parameters_, clone->return_type_,
  615. clone->deduced_bindings_, clone->impl_bindings_,
  616. clone->is_initializing_) {}
  617. static auto classof(const Value* value) -> bool {
  618. return value->kind() == Kind::FunctionType;
  619. }
  620. template <typename F>
  621. auto Decompose(F f) const {
  622. return f(method_self_, parameters_, generic_parameters_, return_type_,
  623. deduced_bindings_, impl_bindings_, is_initializing_);
  624. }
  625. // The type of the function parameter tuple.
  626. auto parameters() const -> const Value& { return *parameters_; }
  627. // Parameters that use a generic `:!` binding at the top level.
  628. auto generic_parameters() const -> llvm::ArrayRef<GenericParameter> {
  629. return generic_parameters_;
  630. }
  631. // The function return type.
  632. auto return_type() const -> const Value& { return *return_type_; }
  633. // All generic bindings in this function's signature that should be deduced
  634. // in a call. This excludes any generic parameters.
  635. auto deduced_bindings() const
  636. -> llvm::ArrayRef<Nonnull<const GenericBinding*>> {
  637. return deduced_bindings_;
  638. }
  639. // The bindings for the impl witness tables required by the
  640. // bounds on the type parameters of the generic function.
  641. auto impl_bindings() const -> llvm::ArrayRef<Nonnull<const ImplBinding*>> {
  642. return impl_bindings_;
  643. }
  644. // Return whether the function type is an initializing expression or not.
  645. auto is_initializing() const -> bool { return is_initializing_; }
  646. // Binding for the implicit `self` parameter, if this is an unbound method.
  647. auto method_self() const -> std::optional<MethodSelf> { return method_self_; }
  648. private:
  649. std::optional<MethodSelf> method_self_;
  650. Nonnull<const Value*> parameters_;
  651. std::vector<GenericParameter> generic_parameters_;
  652. Nonnull<const Value*> return_type_;
  653. std::vector<Nonnull<const GenericBinding*>> deduced_bindings_;
  654. std::vector<Nonnull<const ImplBinding*>> impl_bindings_;
  655. bool is_initializing_;
  656. };
  657. // A pointer type.
  658. class PointerType : public Value {
  659. public:
  660. // Constructs a pointer type with the given pointee type.
  661. explicit PointerType(Nonnull<const Value*> pointee_type)
  662. : Value(Kind::PointerType), pointee_type_(pointee_type) {}
  663. static auto classof(const Value* value) -> bool {
  664. return value->kind() == Kind::PointerType;
  665. }
  666. template <typename F>
  667. auto Decompose(F f) const {
  668. return f(pointee_type_);
  669. }
  670. auto pointee_type() const -> const Value& { return *pointee_type_; }
  671. private:
  672. Nonnull<const Value*> pointee_type_;
  673. };
  674. // The `auto` type.
  675. class AutoType : public Value {
  676. public:
  677. AutoType() : Value(Kind::AutoType) {}
  678. static auto classof(const Value* value) -> bool {
  679. return value->kind() == Kind::AutoType;
  680. }
  681. template <typename F>
  682. auto Decompose(F f) const {
  683. return f();
  684. }
  685. };
  686. // A struct type.
  687. class StructType : public Value {
  688. public:
  689. StructType() : StructType(std::vector<NamedValue>{}) {}
  690. explicit StructType(std::vector<NamedValue> fields)
  691. : Value(Kind::StructType), fields_(std::move(fields)) {}
  692. static auto classof(const Value* value) -> bool {
  693. return value->kind() == Kind::StructType;
  694. }
  695. template <typename F>
  696. auto Decompose(F f) const {
  697. return f(fields_);
  698. }
  699. auto fields() const -> llvm::ArrayRef<NamedValue> { return fields_; }
  700. private:
  701. std::vector<NamedValue> fields_;
  702. };
  703. // A class type.
  704. class NominalClassType : public Value {
  705. public:
  706. explicit NominalClassType(
  707. Nonnull<const ClassDeclaration*> declaration,
  708. Nonnull<const Bindings*> bindings,
  709. std::optional<Nonnull<const NominalClassType*>> base,
  710. Nonnull<const VTable*> class_vtable)
  711. : Value(Kind::NominalClassType),
  712. declaration_(declaration),
  713. bindings_(bindings),
  714. base_(base),
  715. vtable_(class_vtable),
  716. hierarchy_level_(base ? (*base)->hierarchy_level() + 1 : 0) {}
  717. static auto classof(const Value* value) -> bool {
  718. return value->kind() == Kind::NominalClassType;
  719. }
  720. template <typename F>
  721. auto Decompose(F f) const {
  722. return f(declaration_, bindings_, base_, vtable_);
  723. }
  724. auto declaration() const -> const ClassDeclaration& { return *declaration_; }
  725. auto bindings() const -> const Bindings& { return *bindings_; }
  726. auto base() const -> std::optional<Nonnull<const NominalClassType*>> {
  727. return base_;
  728. }
  729. auto type_args() const -> const BindingMap& { return bindings_->args(); }
  730. // Witnesses for each of the class's impl bindings.
  731. auto witnesses() const -> const ImplWitnessMap& {
  732. return bindings_->witnesses();
  733. }
  734. auto vtable() const -> const VTable& { return *vtable_; }
  735. // Returns how many levels from the top ancestor class it is. i.e. a class
  736. // with no base returns `0`, while a class with a `.base` and `.base.base`
  737. // returns `2`.
  738. auto hierarchy_level() const -> int { return hierarchy_level_; }
  739. // Returns whether this a parameterized class. That is, a class with
  740. // parameters and no corresponding arguments.
  741. auto IsParameterized() const -> bool {
  742. return declaration_->type_params().has_value() && type_args().empty();
  743. }
  744. // Returns whether this class is, or inherits `other`.
  745. auto InheritsClass(Nonnull<const Value*> other) const -> bool;
  746. private:
  747. Nonnull<const ClassDeclaration*> declaration_;
  748. Nonnull<const Bindings*> bindings_ = Bindings::None();
  749. const std::optional<Nonnull<const NominalClassType*>> base_;
  750. Nonnull<const VTable*> vtable_;
  751. int hierarchy_level_;
  752. };
  753. class MixinPseudoType : public Value {
  754. public:
  755. explicit MixinPseudoType(Nonnull<const MixinDeclaration*> declaration)
  756. : Value(Kind::MixinPseudoType), declaration_(declaration) {
  757. CARBON_CHECK(!declaration->params().has_value())
  758. << "missing arguments for parameterized mixin type";
  759. }
  760. explicit MixinPseudoType(Nonnull<const MixinDeclaration*> declaration,
  761. Nonnull<const Bindings*> bindings)
  762. : Value(Kind::MixinPseudoType),
  763. declaration_(declaration),
  764. bindings_(bindings) {}
  765. static auto classof(const Value* value) -> bool {
  766. return value->kind() == Kind::MixinPseudoType;
  767. }
  768. template <typename F>
  769. auto Decompose(F f) const {
  770. return f(declaration_, bindings_);
  771. }
  772. auto declaration() const -> const MixinDeclaration& { return *declaration_; }
  773. auto bindings() const -> const Bindings& { return *bindings_; }
  774. auto args() const -> const BindingMap& { return bindings_->args(); }
  775. auto witnesses() const -> const ImplWitnessMap& {
  776. return bindings_->witnesses();
  777. }
  778. auto FindFunction(const std::string_view& name) const
  779. -> std::optional<Nonnull<const FunctionValue*>>;
  780. private:
  781. Nonnull<const MixinDeclaration*> declaration_;
  782. Nonnull<const Bindings*> bindings_ = Bindings::None();
  783. };
  784. // Returns the value of the function named `name` in this class, or
  785. // nullopt if there is no such function.
  786. auto FindFunction(std::string_view name,
  787. llvm::ArrayRef<Nonnull<Declaration*>> members)
  788. -> std::optional<Nonnull<const FunctionValue*>>;
  789. // Returns the value of the function named `name` in this class and its
  790. // parents, or nullopt if there is no such function.
  791. auto FindFunctionWithParents(std::string_view name,
  792. const ClassDeclaration& class_decl)
  793. -> std::optional<Nonnull<const FunctionValue*>>;
  794. // Return the declaration of the member with the given name.
  795. auto FindMember(std::string_view name,
  796. llvm::ArrayRef<Nonnull<Declaration*>> members)
  797. -> std::optional<Nonnull<const Declaration*>>;
  798. // An interface type.
  799. class InterfaceType : public Value {
  800. public:
  801. explicit InterfaceType(Nonnull<const InterfaceDeclaration*> declaration)
  802. : Value(Kind::InterfaceType), declaration_(declaration) {
  803. CARBON_CHECK(!declaration->params().has_value())
  804. << "missing arguments for parameterized interface type";
  805. }
  806. explicit InterfaceType(Nonnull<const InterfaceDeclaration*> declaration,
  807. Nonnull<const Bindings*> bindings)
  808. : Value(Kind::InterfaceType),
  809. declaration_(declaration),
  810. bindings_(bindings) {}
  811. static auto classof(const Value* value) -> bool {
  812. return value->kind() == Kind::InterfaceType;
  813. }
  814. template <typename F>
  815. auto Decompose(F f) const {
  816. return f(declaration_, bindings_);
  817. }
  818. auto declaration() const -> const InterfaceDeclaration& {
  819. return *declaration_;
  820. }
  821. auto bindings() const -> const Bindings& { return *bindings_; }
  822. auto args() const -> const BindingMap& { return bindings_->args(); }
  823. auto witnesses() const -> const ImplWitnessMap& {
  824. return bindings_->witnesses();
  825. }
  826. private:
  827. Nonnull<const InterfaceDeclaration*> declaration_;
  828. Nonnull<const Bindings*> bindings_ = Bindings::None();
  829. };
  830. // A named constraint type.
  831. class NamedConstraintType : public Value {
  832. public:
  833. explicit NamedConstraintType(
  834. Nonnull<const ConstraintDeclaration*> declaration,
  835. Nonnull<const Bindings*> bindings)
  836. : Value(Kind::NamedConstraintType),
  837. declaration_(declaration),
  838. bindings_(bindings) {}
  839. static auto classof(const Value* value) -> bool {
  840. return value->kind() == Kind::NamedConstraintType;
  841. }
  842. template <typename F>
  843. auto Decompose(F f) const {
  844. return f(declaration_, bindings_);
  845. }
  846. auto declaration() const -> const ConstraintDeclaration& {
  847. return *declaration_;
  848. }
  849. auto bindings() const -> const Bindings& { return *bindings_; }
  850. private:
  851. Nonnull<const ConstraintDeclaration*> declaration_;
  852. Nonnull<const Bindings*> bindings_ = Bindings::None();
  853. };
  854. // A constraint that requires implementation of an interface.
  855. struct ImplsConstraint : public HashFromDecompose<ImplsConstraint> {
  856. template <typename F>
  857. auto Decompose(F f) const {
  858. return f(type, interface);
  859. }
  860. // The type that is required to implement the interface.
  861. Nonnull<const Value*> type;
  862. // The interface that is required to be implemented.
  863. Nonnull<const InterfaceType*> interface;
  864. };
  865. // A constraint that requires an intrinsic property of a type.
  866. struct IntrinsicConstraint : public HashFromDecompose<IntrinsicConstraint>,
  867. public Printable<IntrinsicConstraint> {
  868. enum Kind {
  869. // `type` intrinsically implicitly converts to `parameters[0]`.
  870. // TODO: Split ImplicitAs into more specific constraints (such as
  871. // derived-to-base pointer conversions).
  872. ImplicitAs,
  873. };
  874. explicit IntrinsicConstraint(Nonnull<const Value*> type, Kind kind,
  875. std::vector<Nonnull<const Value*>> arguments)
  876. : type(type), kind(kind), arguments(std::move(arguments)) {}
  877. template <typename F>
  878. auto Decompose(F f) const {
  879. return f(type, kind, arguments);
  880. }
  881. // Print the intrinsic constraint.
  882. void Print(llvm::raw_ostream& out) const;
  883. // The type that is required to satisfy the intrinsic property.
  884. Nonnull<const Value*> type;
  885. // The kind of the intrinsic property.
  886. Kind kind;
  887. // Arguments for the intrinsic property. The meaning of these depends on
  888. // `kind`.
  889. std::vector<Nonnull<const Value*>> arguments;
  890. };
  891. // A constraint that a collection of values are known to be the same.
  892. struct EqualityConstraint : public HashFromDecompose<EqualityConstraint> {
  893. template <typename F>
  894. auto Decompose(F f) const {
  895. return f(values);
  896. }
  897. // Visit the values in this equality constraint that are a single step away
  898. // from the given value according to this equality constraint. That is: if
  899. // `value` is identical to a value in `values`, then call the visitor on all
  900. // values in `values` that are not identical to `value`. Otherwise, do not
  901. // call the visitor.
  902. //
  903. // Stops and returns `false` if any call to the visitor returns `false`,
  904. // otherwise returns `true`.
  905. auto VisitEqualValues(
  906. Nonnull<const Value*> value,
  907. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool;
  908. std::vector<Nonnull<const Value*>> values;
  909. };
  910. // A constraint indicating that access to an associated constant should be
  911. // replaced by another value.
  912. struct RewriteConstraint : public HashFromDecompose<RewriteConstraint> {
  913. template <typename F>
  914. auto Decompose(F f) const {
  915. return f(constant, unconverted_replacement, unconverted_replacement_type,
  916. converted_replacement);
  917. }
  918. // The associated constant value that is rewritten.
  919. Nonnull<const AssociatedConstant*> constant;
  920. // The replacement in its original type.
  921. Nonnull<const Value*> unconverted_replacement;
  922. // The type of the replacement.
  923. Nonnull<const Value*> unconverted_replacement_type;
  924. // The replacement after conversion to the type of the associated constant.
  925. Nonnull<const Value*> converted_replacement;
  926. };
  927. // A context in which we might look up a name.
  928. struct LookupContext : public HashFromDecompose<LookupContext> {
  929. template <typename F>
  930. auto Decompose(F f) const {
  931. return f(context);
  932. }
  933. Nonnull<const Value*> context;
  934. };
  935. // A type-of-type for an unknown constrained type.
  936. //
  937. // These types are formed by the `&` operator that combines constraints and by
  938. // `where` expressions.
  939. //
  940. // A constraint has three main properties:
  941. //
  942. // * A collection of (type, interface) pairs for interfaces that are known to
  943. // be implemented by a type satisfying the constraint.
  944. // * A collection of (type, intrinsic) pairs for intrinsic properties that are
  945. // known to be satisfied by a type satisfying the constraint.
  946. // * A collection of sets of values, typically associated constants, that are
  947. // known to be the same.
  948. // * A collection of contexts in which member name lookups will be performed
  949. // for a type variable whose type is this constraint.
  950. //
  951. // Within these properties, the constrained type can be referred to with a
  952. // `VariableType` naming the `self_binding`.
  953. class ConstraintType : public Value {
  954. public:
  955. explicit ConstraintType(
  956. Nonnull<const GenericBinding*> self_binding,
  957. std::vector<ImplsConstraint> impls_constraints,
  958. std::vector<IntrinsicConstraint> intrinsic_constraints,
  959. std::vector<EqualityConstraint> equality_constraints,
  960. std::vector<RewriteConstraint> rewrite_constraints,
  961. std::vector<LookupContext> lookup_contexts)
  962. : Value(Kind::ConstraintType),
  963. self_binding_(self_binding),
  964. impls_constraints_(std::move(impls_constraints)),
  965. intrinsic_constraints_(std::move(intrinsic_constraints)),
  966. equality_constraints_(std::move(equality_constraints)),
  967. rewrite_constraints_(std::move(rewrite_constraints)),
  968. lookup_contexts_(std::move(lookup_contexts)) {}
  969. static auto classof(const Value* value) -> bool {
  970. return value->kind() == Kind::ConstraintType;
  971. }
  972. template <typename F>
  973. auto Decompose(F f) const {
  974. return f(self_binding_, impls_constraints_, intrinsic_constraints_,
  975. equality_constraints_, rewrite_constraints_, lookup_contexts_);
  976. }
  977. auto self_binding() const -> Nonnull<const GenericBinding*> {
  978. return self_binding_;
  979. }
  980. auto impls_constraints() const -> llvm::ArrayRef<ImplsConstraint> {
  981. return impls_constraints_;
  982. }
  983. auto intrinsic_constraints() const -> llvm::ArrayRef<IntrinsicConstraint> {
  984. return intrinsic_constraints_;
  985. }
  986. auto equality_constraints() const -> llvm::ArrayRef<EqualityConstraint> {
  987. return equality_constraints_;
  988. }
  989. auto rewrite_constraints() const -> llvm::ArrayRef<RewriteConstraint> {
  990. return rewrite_constraints_;
  991. }
  992. auto lookup_contexts() const -> llvm::ArrayRef<LookupContext> {
  993. return lookup_contexts_;
  994. }
  995. // Visit the values in that are a single step away from the given value
  996. // according to equality constraints in this constraint type, that is, the
  997. // values `v` that are not identical to `value` but for which we have a
  998. // `value == v` equality constraint in this constraint type.
  999. //
  1000. // Stops and returns `false` if any call to the visitor returns `false`,
  1001. // otherwise returns `true`.
  1002. auto VisitEqualValues(
  1003. Nonnull<const Value*> value,
  1004. llvm::function_ref<bool(Nonnull<const Value*>)> visitor) const -> bool;
  1005. private:
  1006. Nonnull<const GenericBinding*> self_binding_;
  1007. std::vector<ImplsConstraint> impls_constraints_;
  1008. std::vector<IntrinsicConstraint> intrinsic_constraints_;
  1009. std::vector<EqualityConstraint> equality_constraints_;
  1010. std::vector<RewriteConstraint> rewrite_constraints_;
  1011. std::vector<LookupContext> lookup_contexts_;
  1012. };
  1013. // A witness table.
  1014. class Witness : public Value {
  1015. protected:
  1016. explicit Witness(Value::Kind kind) : Value(kind) {}
  1017. public:
  1018. static auto classof(const Value* value) -> bool {
  1019. return value->kind() == Kind::ImplWitness ||
  1020. value->kind() == Kind::BindingWitness ||
  1021. value->kind() == Kind::ConstraintWitness ||
  1022. value->kind() == Kind::ConstraintImplWitness;
  1023. }
  1024. };
  1025. // The witness table for an impl.
  1026. class ImplWitness : public Witness {
  1027. public:
  1028. // Construct a witness for an impl.
  1029. explicit ImplWitness(Nonnull<const ImplDeclaration*> declaration,
  1030. Nonnull<const Bindings*> bindings)
  1031. : Witness(Kind::ImplWitness),
  1032. declaration_(declaration),
  1033. bindings_(bindings) {}
  1034. static auto classof(const Value* value) -> bool {
  1035. return value->kind() == Kind::ImplWitness;
  1036. }
  1037. template <typename F>
  1038. auto Decompose(F f) const {
  1039. return f(declaration_, bindings_);
  1040. }
  1041. auto declaration() const -> const ImplDeclaration& { return *declaration_; }
  1042. auto bindings() const -> const Bindings& { return *bindings_; }
  1043. auto type_args() const -> const BindingMap& { return bindings_->args(); }
  1044. auto witnesses() const -> const ImplWitnessMap& {
  1045. return bindings_->witnesses();
  1046. }
  1047. private:
  1048. Nonnull<const ImplDeclaration*> declaration_;
  1049. Nonnull<const Bindings*> bindings_ = Bindings::None();
  1050. };
  1051. // The symbolic witness corresponding to an unresolved impl binding.
  1052. class BindingWitness : public Witness {
  1053. public:
  1054. // Construct a witness for an impl binding.
  1055. explicit BindingWitness(Nonnull<const ImplBinding*> binding)
  1056. : Witness(Kind::BindingWitness), binding_(binding) {}
  1057. static auto classof(const Value* value) -> bool {
  1058. return value->kind() == Kind::BindingWitness;
  1059. }
  1060. template <typename F>
  1061. auto Decompose(F f) const {
  1062. return f(binding_);
  1063. }
  1064. auto binding() const -> Nonnull<const ImplBinding*> { return binding_; }
  1065. private:
  1066. Nonnull<const ImplBinding*> binding_;
  1067. };
  1068. // A witness for a constraint type, expressed as a tuple of witnesses for the
  1069. // individual impls constraints in the constraint type.
  1070. class ConstraintWitness : public Witness {
  1071. public:
  1072. explicit ConstraintWitness(std::vector<Nonnull<const Witness*>> witnesses)
  1073. : Witness(Kind::ConstraintWitness), witnesses_(std::move(witnesses)) {}
  1074. static auto classof(const Value* value) -> bool {
  1075. return value->kind() == Kind::ConstraintWitness;
  1076. }
  1077. template <typename F>
  1078. auto Decompose(F f) const {
  1079. return f(witnesses_);
  1080. }
  1081. auto witnesses() const -> llvm::ArrayRef<Nonnull<const Witness*>> {
  1082. return witnesses_;
  1083. }
  1084. private:
  1085. std::vector<Nonnull<const Witness*>> witnesses_;
  1086. };
  1087. // A witness for an impls constraint in a constraint type, expressed in terms of
  1088. // a symbolic witness for the constraint type.
  1089. class ConstraintImplWitness : public Witness {
  1090. public:
  1091. // Make a witness for the given impls_constraint of the given `ConstraintType`
  1092. // witness. If we're indexing into a known tuple of witnesses, pull out the
  1093. // element.
  1094. static auto Make(Nonnull<Arena*> arena, Nonnull<const Witness*> witness,
  1095. int index) -> Nonnull<const Witness*> {
  1096. CARBON_CHECK(!llvm::isa<ImplWitness>(witness))
  1097. << "impl witness has no components to access";
  1098. if (const auto* constraint_witness =
  1099. llvm::dyn_cast<ConstraintWitness>(witness)) {
  1100. return constraint_witness->witnesses()[index];
  1101. }
  1102. return arena->New<ConstraintImplWitness>(witness, index);
  1103. }
  1104. explicit ConstraintImplWitness(Nonnull<const Witness*> constraint_witness,
  1105. int index)
  1106. : Witness(Kind::ConstraintImplWitness),
  1107. constraint_witness_(constraint_witness),
  1108. index_(index) {
  1109. CARBON_CHECK(!llvm::isa<ConstraintWitness>(constraint_witness))
  1110. << "should have resolved element from constraint witness";
  1111. }
  1112. static auto classof(const Value* value) -> bool {
  1113. return value->kind() == Kind::ConstraintImplWitness;
  1114. }
  1115. template <typename F>
  1116. auto Decompose(F f) const {
  1117. return f(constraint_witness_, index_);
  1118. }
  1119. // Get the witness for the complete `ConstraintType`.
  1120. auto constraint_witness() const -> Nonnull<const Witness*> {
  1121. return constraint_witness_;
  1122. }
  1123. // Get the index of the impls constraint within the constraint type.
  1124. auto index() const -> int { return index_; }
  1125. private:
  1126. Nonnull<const Witness*> constraint_witness_;
  1127. int index_;
  1128. };
  1129. // Allocate a `ConstraintImplWitness` using the custom `Make` function.
  1130. template <>
  1131. struct AllocateTrait<ConstraintImplWitness> {
  1132. template <typename... Args>
  1133. static auto New(Nonnull<Arena*> arena, Args&&... args)
  1134. -> Nonnull<const Witness*> {
  1135. return ConstraintImplWitness::Make(arena, std::forward<Args>(args)...);
  1136. }
  1137. };
  1138. // A choice type.
  1139. class ChoiceType : public Value {
  1140. public:
  1141. ChoiceType(Nonnull<const ChoiceDeclaration*> declaration,
  1142. Nonnull<const Bindings*> bindings)
  1143. : Value(Kind::ChoiceType),
  1144. declaration_(declaration),
  1145. bindings_(bindings) {}
  1146. static auto classof(const Value* value) -> bool {
  1147. return value->kind() == Kind::ChoiceType;
  1148. }
  1149. template <typename F>
  1150. auto Decompose(F f) const {
  1151. return f(declaration_, bindings_);
  1152. }
  1153. auto bindings() const -> const Bindings& { return *bindings_; }
  1154. auto type_args() const -> const BindingMap& { return bindings_->args(); }
  1155. auto declaration() const -> const ChoiceDeclaration& { return *declaration_; }
  1156. auto IsParameterized() const -> bool {
  1157. return declaration_->type_params().has_value();
  1158. }
  1159. private:
  1160. Nonnull<const ChoiceDeclaration*> declaration_;
  1161. Nonnull<const Bindings*> bindings_;
  1162. };
  1163. // A variable type.
  1164. class VariableType : public Value {
  1165. public:
  1166. explicit VariableType(Nonnull<const GenericBinding*> binding)
  1167. : Value(Kind::VariableType), binding_(binding) {}
  1168. static auto classof(const Value* value) -> bool {
  1169. return value->kind() == Kind::VariableType;
  1170. }
  1171. template <typename F>
  1172. auto Decompose(F f) const {
  1173. return f(binding_);
  1174. }
  1175. auto binding() const -> const GenericBinding& { return *binding_; }
  1176. private:
  1177. Nonnull<const GenericBinding*> binding_;
  1178. };
  1179. // A name of an entity that has explicit parameters, such as a parameterized
  1180. // class or interface. When arguments for those parameters are provided in a
  1181. // call, the result will be a class type or interface type.
  1182. class ParameterizedEntityName : public Value {
  1183. public:
  1184. explicit ParameterizedEntityName(Nonnull<const Declaration*> declaration,
  1185. Nonnull<const TuplePattern*> params)
  1186. : Value(Kind::ParameterizedEntityName),
  1187. declaration_(declaration),
  1188. params_(params) {}
  1189. static auto classof(const Value* value) -> bool {
  1190. return value->kind() == Kind::ParameterizedEntityName;
  1191. }
  1192. template <typename F>
  1193. auto Decompose(F f) const {
  1194. return f(declaration_, params_);
  1195. }
  1196. auto declaration() const -> const Declaration& { return *declaration_; }
  1197. auto params() const -> const TuplePattern& { return *params_; }
  1198. private:
  1199. Nonnull<const Declaration*> declaration_;
  1200. Nonnull<const TuplePattern*> params_;
  1201. };
  1202. // The name of a member of a class or interface.
  1203. //
  1204. // These values are used to represent the second operand of a compound member
  1205. // access expression: `x.(A.B)`, and can also be the value of an alias
  1206. // declaration, but cannot be used in most other contexts.
  1207. class MemberName : public Value, public Printable<MemberName> {
  1208. public:
  1209. MemberName(std::optional<Nonnull<const Value*>> base_type,
  1210. std::optional<Nonnull<const InterfaceType*>> interface,
  1211. Nonnull<const NamedElement*> member)
  1212. : Value(Kind::MemberName),
  1213. base_type_(base_type),
  1214. interface_(interface),
  1215. member_(member) {
  1216. CARBON_CHECK(base_type || interface)
  1217. << "member name must be in a type, an interface, or both";
  1218. }
  1219. static auto classof(const Value* value) -> bool {
  1220. return value->kind() == Kind::MemberName;
  1221. }
  1222. template <typename F>
  1223. auto Decompose(F f) const {
  1224. return f(base_type_, interface_, member_);
  1225. }
  1226. // The type for which `name` is a member or a member of an `impl`.
  1227. auto base_type() const -> std::optional<Nonnull<const Value*>> {
  1228. return base_type_;
  1229. }
  1230. // The interface for which `name` is a member, if any.
  1231. auto interface() const -> std::optional<Nonnull<const InterfaceType*>> {
  1232. return interface_;
  1233. }
  1234. // The member.
  1235. auto member() const -> const NamedElement& { return *member_; }
  1236. // The name of the member.
  1237. auto name() const -> std::string_view { return member().name(); }
  1238. private:
  1239. std::optional<Nonnull<const Value*>> base_type_;
  1240. std::optional<Nonnull<const InterfaceType*>> interface_;
  1241. Nonnull<const NamedElement*> member_;
  1242. };
  1243. // A symbolic value representing an associated constant.
  1244. //
  1245. // This is a value of the form `A.B` or `A.B.C` or similar, where `A` is a
  1246. // `VariableType`.
  1247. class AssociatedConstant : public Value {
  1248. public:
  1249. explicit AssociatedConstant(
  1250. Nonnull<const Value*> base, Nonnull<const InterfaceType*> interface,
  1251. Nonnull<const AssociatedConstantDeclaration*> constant,
  1252. Nonnull<const Witness*> witness)
  1253. : Value(Kind::AssociatedConstant),
  1254. base_(base),
  1255. interface_(interface),
  1256. constant_(constant),
  1257. witness_(witness) {}
  1258. static auto classof(const Value* value) -> bool {
  1259. return value->kind() == Kind::AssociatedConstant;
  1260. }
  1261. template <typename F>
  1262. auto Decompose(F f) const {
  1263. return f(base_, interface_, constant_, witness_);
  1264. }
  1265. // The type for which we denote an associated constant.
  1266. auto base() const -> const Value& { return *base_; }
  1267. // The interface within which the constant was declared.
  1268. auto interface() const -> const InterfaceType& { return *interface_; }
  1269. // The associated constant whose value is being denoted.
  1270. auto constant() const -> const AssociatedConstantDeclaration& {
  1271. return *constant_;
  1272. }
  1273. // Witness within which the constant's value can be found.
  1274. auto witness() const -> const Witness& { return *witness_; }
  1275. private:
  1276. Nonnull<const Value*> base_;
  1277. Nonnull<const InterfaceType*> interface_;
  1278. Nonnull<const AssociatedConstantDeclaration*> constant_;
  1279. Nonnull<const Witness*> witness_;
  1280. };
  1281. // The String type.
  1282. class StringType : public Value {
  1283. public:
  1284. StringType() : Value(Kind::StringType) {}
  1285. static auto classof(const Value* value) -> bool {
  1286. return value->kind() == Kind::StringType;
  1287. }
  1288. template <typename F>
  1289. auto Decompose(F f) const {
  1290. return f();
  1291. }
  1292. };
  1293. // A string value.
  1294. class StringValue : public Value {
  1295. public:
  1296. explicit StringValue(std::string value)
  1297. : Value(Kind::StringValue), value_(std::move(value)) {}
  1298. static auto classof(const Value* value) -> bool {
  1299. return value->kind() == Kind::StringValue;
  1300. }
  1301. template <typename F>
  1302. auto Decompose(F f) const {
  1303. return f(value_);
  1304. }
  1305. auto value() const -> const std::string& { return value_; }
  1306. private:
  1307. std::string value_;
  1308. };
  1309. class TypeOfMixinPseudoType : public Value {
  1310. public:
  1311. explicit TypeOfMixinPseudoType(Nonnull<const MixinPseudoType*> class_type)
  1312. : Value(Kind::TypeOfMixinPseudoType), mixin_type_(class_type) {}
  1313. static auto classof(const Value* value) -> bool {
  1314. return value->kind() == Kind::TypeOfMixinPseudoType;
  1315. }
  1316. template <typename F>
  1317. auto Decompose(F f) const {
  1318. return f(mixin_type_);
  1319. }
  1320. auto mixin_type() const -> const MixinPseudoType& { return *mixin_type_; }
  1321. private:
  1322. Nonnull<const MixinPseudoType*> mixin_type_;
  1323. };
  1324. // The type of an expression whose value is the name of a parameterized entity.
  1325. // Such an expression can only be used as the operand of a call expression that
  1326. // provides arguments for the parameters.
  1327. class TypeOfParameterizedEntityName : public Value {
  1328. public:
  1329. explicit TypeOfParameterizedEntityName(
  1330. Nonnull<const ParameterizedEntityName*> name)
  1331. : Value(Kind::TypeOfParameterizedEntityName), name_(name) {}
  1332. static auto classof(const Value* value) -> bool {
  1333. return value->kind() == Kind::TypeOfParameterizedEntityName;
  1334. }
  1335. template <typename F>
  1336. auto Decompose(F f) const {
  1337. return f(name_);
  1338. }
  1339. auto name() const -> const ParameterizedEntityName& { return *name_; }
  1340. private:
  1341. Nonnull<const ParameterizedEntityName*> name_;
  1342. };
  1343. // The type of a member name expression.
  1344. //
  1345. // This is used for member names that don't denote a specific object or value
  1346. // until used on the right-hand side of a `.`, such as an instance method or
  1347. // field name, or any member function in an interface.
  1348. //
  1349. // Such expressions can appear only as the target of an `alias` declaration or
  1350. // as the member name in a compound member access.
  1351. class TypeOfMemberName : public Value {
  1352. public:
  1353. explicit TypeOfMemberName(Nonnull<const NamedElement*> member)
  1354. : Value(Kind::TypeOfMemberName), member_(member) {}
  1355. static auto classof(const Value* value) -> bool {
  1356. return value->kind() == Kind::TypeOfMemberName;
  1357. }
  1358. template <typename F>
  1359. auto Decompose(F f) const {
  1360. return f(member_);
  1361. }
  1362. // TODO: consider removing this or moving it elsewhere in the AST,
  1363. // since it's arguably part of the expression value rather than its type.
  1364. auto member() const -> const NamedElement& { return *member_; }
  1365. private:
  1366. Nonnull<const NamedElement*> member_;
  1367. };
  1368. // The type of a namespace name.
  1369. //
  1370. // Such expressions can appear only as the target of an `alias` declaration or
  1371. // as the left-hand side of a simple member access expression.
  1372. class TypeOfNamespaceName : public Value {
  1373. public:
  1374. explicit TypeOfNamespaceName(
  1375. Nonnull<const NamespaceDeclaration*> namespace_decl)
  1376. : Value(Kind::TypeOfNamespaceName), namespace_decl_(namespace_decl) {}
  1377. static auto classof(const Value* value) -> bool {
  1378. return value->kind() == Kind::TypeOfNamespaceName;
  1379. }
  1380. template <typename F>
  1381. auto Decompose(F f) const {
  1382. return f(namespace_decl_);
  1383. }
  1384. auto namespace_decl() const -> Nonnull<const NamespaceDeclaration*> {
  1385. return namespace_decl_;
  1386. }
  1387. private:
  1388. Nonnull<const NamespaceDeclaration*> namespace_decl_;
  1389. };
  1390. // The type of a statically-sized array.
  1391. //
  1392. // Note that values of this type are represented as tuples.
  1393. class StaticArrayType : public Value {
  1394. public:
  1395. // Constructs a statically-sized array type with the given element type and
  1396. // size.
  1397. StaticArrayType(Nonnull<const Value*> element_type,
  1398. std::optional<size_t> size)
  1399. : Value(Kind::StaticArrayType),
  1400. element_type_(element_type),
  1401. size_(size) {}
  1402. static auto classof(const Value* value) -> bool {
  1403. return value->kind() == Kind::StaticArrayType;
  1404. }
  1405. template <typename F>
  1406. auto Decompose(F f) const {
  1407. return f(element_type_, size_);
  1408. }
  1409. auto element_type() const -> const Value& { return *element_type_; }
  1410. auto size() const -> size_t {
  1411. CARBON_CHECK(has_size());
  1412. return *size_;
  1413. }
  1414. auto has_size() const -> bool { return size_.has_value(); }
  1415. private:
  1416. Nonnull<const Value*> element_type_;
  1417. std::optional<size_t> size_;
  1418. };
  1419. template <typename R, typename F>
  1420. auto Value::Visit(F f) const -> R {
  1421. switch (kind()) {
  1422. #define CARBON_VALUE_KIND(kind) \
  1423. case Kind::kind: \
  1424. return f(static_cast<const kind*>(this));
  1425. #include "explorer/ast/value_kinds.def"
  1426. }
  1427. }
  1428. } // namespace Carbon
  1429. #endif // CARBON_EXPLORER_AST_VALUE_H_