value.h 52 KB

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