value.h 53 KB

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