interfaces, impls, and constrained generics (basics) (#1073)

* interfaces, impls, and constrained generics (basics)

* separate type checking into declare vs. type check, removing redundancy

* external impls

* added impl scopes to handle generics calling generics

* cleanup

* more cleanup

* Update executable_semantics/testdata/interface/external_impl_point_vector.carbon

Co-authored-by: josh11b <josh11b@users.noreply.github.com>

* Update executable_semantics/testdata/interface/generic_call_generic.carbon

Co-authored-by: josh11b <josh11b@users.noreply.github.com>

* Update executable_semantics/testdata/interface/tuple_vector_add_scale.carbon

Co-authored-by: josh11b <josh11b@users.noreply.github.com>

* Update executable_semantics/testdata/interface/vector_point_add_scale.carbon

Co-authored-by: josh11b <josh11b@users.noreply.github.com>

* change ImplementationDeclaration to ImplDeclaration

* remove impl_type_value

* split NamedEntity into two

* changed GetName to be a free function

* adding comments

* more edits to respond to review

* introduce ImplBinding, remove punning on GenericBinding

* new test case and some minor edits

* refactor GetMember and GetField to move impl logic to interpreter

* remove commennt

* change EntityView to ImplBinding in FieldAccess...

* move ImplBinding

* review response

* added example to impl_scope.h

* minor edits

* Update executable_semantics/interpreter/field_path.h

Co-authored-by: Geoff Romer <gromer@google.com>

* Update executable_semantics/interpreter/value.cpp

Co-authored-by: Geoff Romer <gromer@google.com>

* Update executable_semantics/interpreter/interpreter.cpp

Co-authored-by: Geoff Romer <gromer@google.com>

* Update executable_semantics/ast/expression.h

Co-authored-by: Geoff Romer <gromer@google.com>

* Update executable_semantics/ast/expression.h

Co-authored-by: Geoff Romer <gromer@google.com>

* Update executable_semantics/ast/generic_binding.h

Co-authored-by: Geoff Romer <gromer@google.com>

* more edits from review

* review response

* Update executable_semantics/ast/static_scope.h

Co-authored-by: Geoff Romer <gromer@google.com>

* remove ImplType, renamed node_view to value_node

Co-authored-by: josh11b <josh11b@users.noreply.github.com>
Co-authored-by: Geoff Romer <gromer@google.com>
This commit is contained in:
Jeremy G. Siek
2022-03-02 15:58:45 -05:00
committed by GitHub
co-authored by josh11b Geoff Romer
parent 8f6e42d866
commit 7cce1bd124
43 changed files with 1722 additions and 441 deletions
+18
View File
@@ -69,6 +69,22 @@ cc_test(
],
)
cc_library(
name = "generic_binding",
hdrs = [
"generic_binding.h",
],
deps = [
":ast_node",
":source_location",
":value_category",
"//common:check",
"//common:ostream",
"//executable_semantics/common:nonnull",
"@llvm-project//llvm:Support",
],
)
cc_library(
name = "declaration",
srcs = ["declaration.cpp"],
@@ -77,6 +93,7 @@ cc_library(
],
deps = [
":ast_node",
":generic_binding",
":pattern",
":return_term",
":source_location",
@@ -108,6 +125,7 @@ cc_library(
hdrs = ["expression.h"],
deps = [
":ast_node",
":generic_binding",
":paren_contents",
":source_location",
":static_scope",
+1 -1
View File
@@ -40,5 +40,5 @@ inheritance, we handle these cases using a form of type erasure: we specify a
notional interface that those types conform to, and then define a "view" class
that behaves like a pointer to an instance of that interface. Types declare that
they model an interface `Foo` by defining a public static member named
`ImplementsCarbonFoo`. See [NamedEntityView](static_scope.h) for an example of
`ImplementsCarbonFoo`. See [ValueNodeView](static_scope.h) for an example of
this pattern.
+3
View File
@@ -14,7 +14,10 @@ abstract class Declaration : AstNode;
class ClassDeclaration : Declaration;
class ChoiceDeclaration : Declaration;
class VariableDeclaration : Declaration;
class InterfaceDeclaration : Declaration;
class ImplDeclaration : Declaration;
class GenericBinding : AstNode;
class ImplBinding : AstNode;
class AlternativeSignature : AstNode;
abstract class Statement : AstNode;
class ExpressionStatement : Statement;
+44
View File
@@ -15,6 +15,32 @@ Declaration::~Declaration() = default;
void Declaration::Print(llvm::raw_ostream& out) const {
switch (kind()) {
case DeclarationKind::InterfaceDeclaration: {
const auto& iface_decl = cast<InterfaceDeclaration>(*this);
out << "interface " << iface_decl.name() << " {\n";
for (Nonnull<Declaration*> m : iface_decl.members()) {
out << *m;
}
out << "}\n";
break;
}
case DeclarationKind::ImplDeclaration: {
const auto& impl_decl = cast<ImplDeclaration>(*this);
switch (impl_decl.kind()) {
case ImplKind::InternalImpl:
break;
case ImplKind::ExternalImpl:
out << "external ";
break;
}
out << "impl " << *impl_decl.impl_type() << " as "
<< impl_decl.interface() << " {\n";
for (Nonnull<Declaration*> m : impl_decl.members()) {
out << *m;
}
out << "}\n";
break;
}
case DeclarationKind::FunctionDeclaration:
cast<FunctionDeclaration>(*this).PrintDepth(-1, out);
break;
@@ -51,6 +77,23 @@ void Declaration::Print(llvm::raw_ostream& out) const {
}
}
auto GetName(const Declaration& declaration) -> std::optional<std::string> {
switch (declaration.kind()) {
case DeclarationKind::FunctionDeclaration:
return cast<FunctionDeclaration>(declaration).name();
case DeclarationKind::ClassDeclaration:
return cast<ClassDeclaration>(declaration).name();
case DeclarationKind::ChoiceDeclaration:
return cast<ChoiceDeclaration>(declaration).name();
case DeclarationKind::InterfaceDeclaration:
return cast<InterfaceDeclaration>(declaration).name();
case DeclarationKind::VariableDeclaration:
return cast<VariableDeclaration>(declaration).binding().name();
case DeclarationKind::ImplDeclaration:
return std::nullopt;
}
}
void GenericBinding::Print(llvm::raw_ostream& out) const {
out << name() << ":! " << type();
}
@@ -63,6 +106,7 @@ void ReturnTerm::Print(llvm::raw_ostream& out) const {
out << "-> auto";
return;
case ReturnKind::Expression:
CHECK(type_expression_.has_value());
out << "-> " << **type_expression_;
return;
}
+107 -57
View File
@@ -11,6 +11,7 @@
#include "common/ostream.h"
#include "executable_semantics/ast/ast_node.h"
#include "executable_semantics/ast/generic_binding.h"
#include "executable_semantics/ast/pattern.h"
#include "executable_semantics/ast/return_term.h"
#include "executable_semantics/ast/source_location.h"
@@ -56,7 +57,10 @@ class Declaration : public AstNode {
// Sets the static type of the declared entity. Can only be called once,
// during typechecking.
void set_static_type(Nonnull<const Value*> type) { static_type_ = type; }
void set_static_type(Nonnull<const Value*> type) {
CHECK(!static_type_.has_value());
static_type_ = type;
}
// Returns whether the static type has been set. Should only be called
// during typechecking: before typechecking it's guaranteed to be false,
@@ -74,62 +78,9 @@ class Declaration : public AstNode {
std::optional<Nonnull<const Value*>> static_type_;
};
// TODO: expand the kinds of things that can be deduced parameters.
// For now, only generic parameters are supported.
class GenericBinding : public AstNode {
public:
using ImplementsCarbonNamedEntity = void;
GenericBinding(SourceLocation source_loc, std::string name,
Nonnull<Expression*> type)
: AstNode(AstNodeKind::GenericBinding, source_loc),
name_(std::move(name)),
type_(type) {}
void Print(llvm::raw_ostream& out) const override;
static auto classof(const AstNode* node) -> bool {
return InheritsFromGenericBinding(node->kind());
}
auto name() const -> const std::string& { return name_; }
auto type() const -> const Expression& { return *type_; }
auto type() -> Expression& { return *type_; }
// The static type of the binding. Cannot be called before typechecking.
auto static_type() const -> const Value& { return **static_type_; }
// Sets the static type of the binding. Can only be called once, during
// typechecking.
void set_static_type(Nonnull<const Value*> type) { static_type_ = type; }
// Returns whether the static type has been set. Should only be called
// during typechecking: before typechecking it's guaranteed to be false,
// and after typechecking it's guaranteed to be true.
auto has_static_type() const -> bool { return static_type_.has_value(); }
auto value_category() const -> ValueCategory { return ValueCategory::Let; }
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
return constant_value_;
}
// Sets the value returned by constant_value(). Can only be called once,
// during typechecking.
void set_constant_value(Nonnull<const Value*> value) {
CHECK(!constant_value_.has_value());
constant_value_ = value;
}
private:
std::string name_;
Nonnull<Expression*> type_;
std::optional<Nonnull<const Value*>> static_type_;
std::optional<Nonnull<const Value*>> constant_value_;
};
class FunctionDeclaration : public Declaration {
public:
using ImplementsCarbonNamedEntity = void;
using ImplementsCarbonValueNode = void;
FunctionDeclaration(SourceLocation source_loc, std::string name,
std::vector<Nonnull<AstNode*>> deduced_params,
@@ -196,7 +147,7 @@ class FunctionDeclaration : public Declaration {
class ClassDeclaration : public Declaration {
public:
using ImplementsCarbonNamedEntity = void;
using ImplementsCarbonValueNode = void;
ClassDeclaration(SourceLocation source_loc, std::string name,
std::vector<Nonnull<Declaration*>> members)
@@ -256,7 +207,7 @@ class AlternativeSignature : public AstNode {
class ChoiceDeclaration : public Declaration {
public:
using ImplementsCarbonNamedEntity = void;
using ImplementsCarbonValueNode = void;
ChoiceDeclaration(SourceLocation source_loc, std::string name,
std::vector<Nonnull<AlternativeSignature*>> alternatives)
@@ -324,6 +275,105 @@ class VariableDeclaration : public Declaration {
std::optional<Nonnull<Expression*>> initializer_;
};
class InterfaceDeclaration : public Declaration {
public:
using ImplementsCarbonValueNode = void;
InterfaceDeclaration(SourceLocation source_loc, std::string name,
Nonnull<GenericBinding*> self,
std::vector<Nonnull<Declaration*>> members)
: Declaration(AstNodeKind::InterfaceDeclaration, source_loc),
name_(std::move(name)),
members_(std::move(members)),
self_(self) {}
static auto classof(const AstNode* node) -> bool {
return InheritsFromInterfaceDeclaration(node->kind());
}
auto name() const -> const std::string& { return name_; }
auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
return members_;
}
auto self() const -> Nonnull<const GenericBinding*> { return self_; }
auto self() -> Nonnull<GenericBinding*> { return self_; }
auto value_category() const -> ValueCategory { return ValueCategory::Let; }
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
return constant_value_;
}
// Sets the value returned by constant_value(). Can only be called once,
// during typechecking.
void set_constant_value(Nonnull<const Value*> value) {
CHECK(!constant_value_.has_value());
constant_value_ = value;
}
private:
std::string name_;
std::vector<Nonnull<Declaration*>> members_;
std::optional<Nonnull<const Value*>> constant_value_;
Nonnull<GenericBinding*> self_;
};
enum class ImplKind { InternalImpl, ExternalImpl };
class ImplDeclaration : public Declaration {
public:
using ImplementsCarbonValueNode = void;
ImplDeclaration(SourceLocation source_loc, ImplKind kind,
Nonnull<Expression*> impl_type,
Nonnull<Expression*> interface,
std::vector<Nonnull<Declaration*>> members)
: Declaration(AstNodeKind::ImplDeclaration, source_loc),
kind_(kind),
impl_type_(impl_type),
interface_(interface),
members_(members) {}
static auto classof(const AstNode* node) -> bool {
return InheritsFromImplDeclaration(node->kind());
}
// Return whether this is an external or internal impl.
auto kind() const -> ImplKind { return kind_; }
// Return the type that is doing the implementing.
auto impl_type() const -> Nonnull<Expression*> { return impl_type_; }
// Return the interface that is being implemented.
auto interface() const -> const Expression& { return *interface_; }
auto interface() -> Expression& { return *interface_; }
void set_interface_type(Nonnull<const Value*> iface_type) {
interface_type_ = iface_type;
}
auto interface_type() const -> Nonnull<const Value*> {
return *interface_type_;
}
auto members() const -> llvm::ArrayRef<Nonnull<Declaration*>> {
return members_;
}
// Return the witness table for this impl.
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
return constant_value_;
}
void set_constant_value(Nonnull<const Value*> value) {
CHECK(!constant_value_.has_value());
constant_value_ = value;
}
auto value_category() const -> ValueCategory { return ValueCategory::Let; }
private:
ImplKind kind_;
Nonnull<Expression*> impl_type_; // TODO: make this optional
Nonnull<Expression*> interface_;
std::optional<Nonnull<const Value*>> interface_type_;
std::vector<Nonnull<Declaration*>> members_;
std::optional<Nonnull<const Value*>> constant_value_;
};
// Return the name of a declaration, if it has one.
auto GetName(const Declaration&) -> std::optional<std::string>;
} // namespace Carbon
#endif // EXECUTABLE_SEMANTICS_AST_DECLARATION_H_
+46 -13
View File
@@ -12,6 +12,7 @@
#include "common/ostream.h"
#include "executable_semantics/ast/ast_node.h"
#include "executable_semantics/ast/generic_binding.h"
#include "executable_semantics/ast/paren_contents.h"
#include "executable_semantics/ast/source_location.h"
#include "executable_semantics/ast/static_scope.h"
@@ -23,6 +24,7 @@
namespace Carbon {
class Value;
class VariableType;
class Expression : public AstNode {
public:
@@ -45,12 +47,10 @@ class Expression : public AstNode {
// Sets the static type of this expression. Can only be called once, during
// typechecking.
void set_static_type(Nonnull<const Value*> type) { static_type_ = type; }
// Returns whether the static type has been set. Should only be called
// during typechecking: before typechecking it's guaranteed to be false,
// and after typechecking it's guaranteed to be true.
auto has_static_type() const -> bool { return static_type_.has_value(); }
void set_static_type(Nonnull<const Value*> type) {
CHECK(!static_type_.has_value());
static_type_ = type;
}
// The value category of this expression. Cannot be called before
// typechecking.
@@ -123,20 +123,20 @@ class IdentifierExpression : public Expression {
auto name() const -> const std::string& { return name_; }
// Returns the NamedEntityView this identifier refers to. Cannot be called
// Returns the ValueNodeView this identifier refers to. Cannot be called
// before name resolution.
auto named_entity() const -> const NamedEntityView& { return *named_entity_; }
auto value_node() const -> const ValueNodeView& { return *value_node_; }
// Sets the value returned by named_entity. Can be called only once,
// Sets the value returned by value_node. Can be called only once,
// during name resolution.
void set_named_entity(NamedEntityView named_entity) {
CHECK(!named_entity_.has_value());
named_entity_ = std::move(named_entity);
void set_value_node(ValueNodeView value_node) {
CHECK(!value_node_.has_value());
value_node_ = std::move(value_node);
}
private:
std::string name_;
std::optional<NamedEntityView> named_entity_;
std::optional<ValueNodeView> value_node_;
};
class FieldAccessExpression : public Expression {
@@ -156,9 +156,23 @@ class FieldAccessExpression : public Expression {
auto aggregate() -> Expression& { return *aggregate_; }
auto field() const -> const std::string& { return field_; }
// If `aggregate` has a generic type, returns the `ImplBinding` that
// identifies its witness table. Otherwise, returns `std::nullopt`. Should not
// be called before typechecking.
auto impl() const -> std::optional<Nonnull<const ImplBinding*>> {
return impl_;
}
// Can only be called once, during typechecking.
void set_impl(Nonnull<const ImplBinding*> impl) {
CHECK(!impl_.has_value());
impl_ = impl;
}
private:
Nonnull<Expression*> aggregate_;
std::string field_;
std::optional<Nonnull<const ImplBinding*>> impl_;
};
class IndexExpression : public Expression {
@@ -340,6 +354,8 @@ class PrimitiveOperatorExpression : public Expression {
std::vector<Nonnull<Expression*>> arguments_;
};
class ImplBinding;
class CallExpression : public Expression {
public:
explicit CallExpression(SourceLocation source_loc,
@@ -358,9 +374,26 @@ class CallExpression : public Expression {
auto argument() const -> const Expression& { return *argument_; }
auto argument() -> Expression& { return *argument_; }
// Maps each of `function`'s generic parameters to the AST node
// that identifies the witness table for the corresponding argument.
// Should not be called before typechecking, or if `function` is not
// a generic function.
auto impls() const
-> const std::map<Nonnull<const ImplBinding*>, ValueNodeView>& {
return impls_;
}
// Can only be called once, during typechecking.
void set_impls(
const std::map<Nonnull<const ImplBinding*>, ValueNodeView>& impls) {
CHECK(impls_.empty());
impls_ = impls;
}
private:
Nonnull<Expression*> function_;
Nonnull<Expression*> argument_;
std::map<Nonnull<const ImplBinding*>, ValueNodeView> impls_;
};
class FunctionTypeLiteral : public Expression {
+139
View File
@@ -0,0 +1,139 @@
// Part of the Carbon Language project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#ifndef EXECUTABLE_SEMANTICS_AST_GENERIC_BINDING_H_
#define EXECUTABLE_SEMANTICS_AST_GENERIC_BINDING_H_
#include <map>
#include "common/check.h"
#include "common/ostream.h"
#include "executable_semantics/ast/ast_node.h"
#include "executable_semantics/ast/value_category.h"
namespace Carbon {
class Value;
class Expression;
class ImplBinding;
// TODO: expand the kinds of things that can be deduced parameters.
// For now, only generic parameters are supported.
class GenericBinding : public AstNode {
public:
using ImplementsCarbonValueNode = void;
GenericBinding(SourceLocation source_loc, std::string name,
Nonnull<Expression*> type)
: AstNode(AstNodeKind::GenericBinding, source_loc),
name_(std::move(name)),
type_(type) {}
void Print(llvm::raw_ostream& out) const override;
static auto classof(const AstNode* node) -> bool {
return InheritsFromGenericBinding(node->kind());
}
auto name() const -> const std::string& { return name_; }
auto type() const -> const Expression& { return *type_; }
auto type() -> Expression& { return *type_; }
// The static type of the binding. Cannot be called before typechecking.
auto static_type() const -> const Value& { return **static_type_; }
// Sets the static type of the binding. Can only be called once, during
// typechecking.
void set_static_type(Nonnull<const Value*> type) {
CHECK(!static_type_.has_value());
static_type_ = type;
}
auto value_category() const -> ValueCategory { return ValueCategory::Let; }
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
return constant_value_;
}
// Sets the value returned by constant_value(). Can only be called once,
// during typechecking.
void set_constant_value(Nonnull<const Value*> value) {
CHECK(!constant_value_.has_value());
constant_value_ = value;
}
// The impl binding associated with this type variable.
auto impl_binding() const -> std::optional<Nonnull<const ImplBinding*>> {
return impl_binding_;
}
// Set the impl binding.
void set_impl_binding(Nonnull<const ImplBinding*> binding) {
CHECK(!impl_binding_.has_value());
impl_binding_ = binding;
}
private:
std::string name_;
Nonnull<Expression*> type_;
std::optional<Nonnull<const Value*>> static_type_;
std::optional<Nonnull<const Value*>> constant_value_;
std::optional<Nonnull<const ImplBinding*>> impl_binding_;
};
using BindingMap =
std::map<Nonnull<const GenericBinding*>, Nonnull<const Value*>>;
// The run-time counterpart of a `GenericBinding`.
//
// Once a generic binding has been declared, it can be used
// in two different ways: as a compile-time constant with a
// symbolic value (such as a `VariableType`), or as a run-time
// variable with a concrete value that is stored on the stack.
// An `ImplBinding` is used in contexts where the second
// interpretation is intended.
class ImplBinding : public AstNode {
public:
using ImplementsCarbonValueNode = void;
ImplBinding(SourceLocation source_loc,
Nonnull<const GenericBinding*> type_var,
Nonnull<const Value*> iface)
: AstNode(AstNodeKind::ImplBinding, source_loc),
type_var_(type_var),
iface_(iface) {}
static auto classof(const AstNode* node) -> bool {
return InheritsFromImplBinding(node->kind());
}
void Print(llvm::raw_ostream& out) const override;
// The binding for the type variable.
auto type_var() const -> Nonnull<const GenericBinding*> { return type_var_; }
// The interface being implemented.
auto interface() const -> Nonnull<const Value*> { return iface_; }
// Required for the the ValueNode interface
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
return std::nullopt;
}
// The static type of the impl. Cannot be called before typechecking.
auto static_type() const -> const Value& { return **static_type_; }
// Sets the static type of the impl. Can only be called once, during
// typechecking.
void set_static_type(Nonnull<const Value*> type) {
CHECK(!static_type_.has_value());
static_type_ = type;
}
auto value_category() const -> ValueCategory { return ValueCategory::Let; }
private:
Nonnull<const GenericBinding*> type_var_;
Nonnull<const Value*> iface_;
std::optional<Nonnull<const Value*>> static_type_;
};
} // namespace Carbon
#endif // EXECUTABLE_SEMANTICS_AST_GENERIC_BINDING_H_
+6 -8
View File
@@ -54,12 +54,10 @@ class Pattern : public AstNode {
// Sets the static type of this expression. Can only be called once, during
// typechecking.
void set_static_type(Nonnull<const Value*> type) { static_type_ = type; }
// Returns whether the static type has been set. Should only be called
// during typechecking: before typechecking it's guaranteed to be false,
// and after typechecking it's guaranteed to be true.
auto has_static_type() const -> bool { return static_type_.has_value(); }
void set_static_type(Nonnull<const Value*> type) {
CHECK(!static_type_.has_value());
static_type_ = type;
}
// The value of this pattern. Cannot be called before typechecking.
// TODO rename to avoid confusion with BindingPattern::constant_value
@@ -101,7 +99,7 @@ class AutoPattern : public Pattern {
// a name to it.
class BindingPattern : public Pattern {
public:
using ImplementsCarbonNamedEntity = void;
using ImplementsCarbonValueNode = void;
BindingPattern(SourceLocation source_loc, std::string name,
Nonnull<Pattern*> type)
@@ -115,7 +113,7 @@ class BindingPattern : public Pattern {
// The name this pattern binds, if any. If equal to AnonymousName, indicates
// that this BindingPattern does not bind a name, which in turn means it
// should not be used as a NamedEntity.
// should not be used as a ValueNode.
auto name() const -> const std::string& { return name_; }
// The pattern specifying the type of values that this pattern matches.
+4 -6
View File
@@ -65,12 +65,10 @@ class ReturnTerm {
// Sets the value of static_type(). Can only be called once, during
// typechecking.
void set_static_type(Nonnull<const Value*> type) { static_type_ = type; }
// Returns whether static_type() has been set. Should only be called
// during typechecking: before typechecking it's guaranteed to be false,
// and after typechecking it's guaranteed to be true.
auto has_static_type() const -> bool { return static_type_.has_value(); }
void set_static_type(Nonnull<const Value*> type) {
CHECK(!static_type_.has_value());
static_type_ = type;
}
auto source_loc() const -> SourceLocation { return source_loc_; }
+5 -7
View File
@@ -314,7 +314,7 @@ class Match : public Statement {
// }
class Continuation : public Statement {
public:
using ImplementsCarbonNamedEntity = void;
using ImplementsCarbonValueNode = void;
Continuation(SourceLocation source_loc, std::string name,
Nonnull<Block*> body)
@@ -338,12 +338,10 @@ class Continuation : public Statement {
// Sets the static type of the continuation. Can only be called once,
// during typechecking.
void set_static_type(Nonnull<const Value*> type) { static_type_ = type; }
// Returns whether the static type has been set. Should only be called
// during typechecking: before typechecking it's guaranteed to be false,
// and after typechecking it's guaranteed to be true.
auto has_static_type() const -> bool { return static_type_.has_value(); }
void set_static_type(Nonnull<const Value*> type) {
CHECK(!static_type_.has_value());
static_type_ = type;
}
auto value_category() const -> ValueCategory { return ValueCategory::Var; }
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
+5 -5
View File
@@ -8,7 +8,7 @@
namespace Carbon {
void StaticScope::Add(std::string name, NamedEntityView entity) {
void StaticScope::Add(std::string name, ValueNodeView entity) {
auto [it, success] = declared_names_.insert({name, entity});
if (!success && it->second != entity) {
FATAL_COMPILATION_ERROR(entity.base().source_loc())
@@ -18,8 +18,8 @@ void StaticScope::Add(std::string name, NamedEntityView entity) {
}
auto StaticScope::Resolve(const std::string& name,
SourceLocation source_loc) const -> NamedEntityView {
std::optional<NamedEntityView> result = TryResolve(name, source_loc);
SourceLocation source_loc) const -> ValueNodeView {
std::optional<ValueNodeView> result = TryResolve(name, source_loc);
if (!result.has_value()) {
FATAL_COMPILATION_ERROR(source_loc) << "could not resolve '" << name << "'";
}
@@ -28,12 +28,12 @@ auto StaticScope::Resolve(const std::string& name,
auto StaticScope::TryResolve(const std::string& name,
SourceLocation source_loc) const
-> std::optional<NamedEntityView> {
-> std::optional<ValueNodeView> {
auto it = declared_names_.find(name);
if (it != declared_names_.end()) {
return it->second;
}
std::optional<NamedEntityView> result;
std::optional<ValueNodeView> result;
for (Nonnull<const StaticScope*> parent : parent_scopes_) {
auto parent_result = parent->TryResolve(name, source_loc);
if (parent_result.has_value() && result.has_value() &&
+47 -52
View File
@@ -21,78 +21,78 @@ namespace Carbon {
class Value;
// The placeholder name exposed by anonymous NamedEntities.
// The placeholder name exposed by anonymous ValueNodes.
static constexpr std::string_view AnonymousName = "_";
// True if NodeType::ImplementsCarbonNamedEntity is valid and names a type,
// indicating that NodeType implements the NamedEntity interface, which means
// it must define the following methods, with contracts as documented.
// ImplementsValueNode is true if NodeType::ImplementsCarbonValueNode
// is valid and names a type, indicating that NodeType implements the
// ValueNode interface, defined below.
template <typename NodeType, typename = void>
static constexpr bool ImplementsValueNode = false;
/*
ValueNode is an interface implemented by AstNodes that can be associated
with a value, such as declarations and bindings. The interface consists of
the following methods:
// Returns the static type of an IdentifierExpression that names *this.
auto static_type() const -> const Value&;
// Returns the value category of an IdentifierExpression that names *this.
auto value_category() const -> ValueCategory;
// Returns the name of an IdentifierExpression that names *this. If *this
// is anonymous, returns AnonymousName.
auto name() const -> std::string_view;
// Print the node for diagnostic or tracing purposes.
void Print(llvm::raw_ostream& out) const;
// If *this names a compile-time constant whose value is known, returns that
// value. Otherwise returns std::nullopt.
auto constant_value() const -> std::optional<Nonnull<const Value*>>;
*/
// NodeType must be derived from AstNode.
//
// TODO: consider turning the above documentation into real code, as sketched
// at https://godbolt.org/z/186oEozhc
template <typename T, typename = void>
static constexpr bool ImplementsNamedEntity = false;
template <typename T>
static constexpr bool
ImplementsNamedEntity<T, typename T::ImplementsCarbonNamedEntity> = true;
ImplementsValueNode<T, typename T::ImplementsCarbonValueNode> = true;
// Non-owning type-erased wrapper around a const NodeType* `node`, where
// NodeType implements the NamedEntity interface.
class NamedEntityView {
class ValueNodeView {
public:
// REQUIRES: node->name() != AnonymousName
template <typename NodeType,
typename = std::enable_if_t<ImplementsNamedEntity<NodeType>>>
typename = std::enable_if_t<ImplementsValueNode<NodeType>>>
// NOLINTNEXTLINE(google-explicit-constructor)
NamedEntityView(Nonnull<const NodeType*> node)
ValueNodeView(Nonnull<const NodeType*> node)
// Type-erase NodeType, retaining a pointer to the base class AstNode
// and using std::function to encapsulate the ability to call
// the derived class's methods.
: base_(node),
name_([](const AstNode& base) -> std::string_view {
return llvm::cast<NodeType>(base).name();
constant_value_(
[](const AstNode& base) -> std::optional<Nonnull<const Value*>> {
return llvm::cast<NodeType>(base).constant_value();
}),
print_([](const AstNode& base, llvm::raw_ostream& out) -> void {
// TODO: change this to print a summary of the node
return llvm::cast<NodeType>(base).Print(out);
}),
static_type_([](const AstNode& base) -> const Value& {
return llvm::cast<NodeType>(base).static_type();
}),
value_category_([](const AstNode& base) -> ValueCategory {
return llvm::cast<NodeType>(base).value_category();
}),
constant_value_(
[](const AstNode& base) -> std::optional<Nonnull<const Value*>> {
return llvm::cast<NodeType>(base).constant_value();
}) {
CHECK(node->name() != AnonymousName)
<< "Entity with no name used as NamedEntity: " << *node;
}
}) {}
NamedEntityView(const NamedEntityView&) = default;
NamedEntityView(NamedEntityView&&) = default;
auto operator=(const NamedEntityView&) -> NamedEntityView& = default;
auto operator=(NamedEntityView&&) -> NamedEntityView& = default;
ValueNodeView(const ValueNodeView&) = default;
ValueNodeView(ValueNodeView&&) = default;
auto operator=(const ValueNodeView&) -> ValueNodeView& = default;
auto operator=(ValueNodeView&&) -> ValueNodeView& = default;
// Returns `node` as an instance of the base class AstNode.
auto base() const -> const AstNode& { return *base_; }
// Returns node->name()
auto name() const -> std::string_view { return name_(*base_); }
// Returns node->constant_value()
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
return constant_value_(*base_);
}
void Print(llvm::raw_ostream& out) const { print_(*base_, out); }
// Returns node->static_type()
auto static_type() const -> const Value& { return static_type_(*base_); }
@@ -102,33 +102,28 @@ class NamedEntityView {
return value_category_(*base_);
}
// Returns node->constant_value()
auto constant_value() const -> std::optional<Nonnull<const Value*>> {
return constant_value_(*base_);
}
friend auto operator==(const NamedEntityView& lhs, const NamedEntityView& rhs)
friend auto operator==(const ValueNodeView& lhs, const ValueNodeView& rhs)
-> bool {
return lhs.base_ == rhs.base_;
}
friend auto operator!=(const NamedEntityView& lhs, const NamedEntityView& rhs)
friend auto operator!=(const ValueNodeView& lhs, const ValueNodeView& rhs)
-> bool {
return lhs.base_ != rhs.base_;
}
friend auto operator<(const NamedEntityView& lhs, const NamedEntityView& rhs)
friend auto operator<(const ValueNodeView& lhs, const ValueNodeView& rhs)
-> bool {
return std::less<>()(lhs.base_, rhs.base_);
}
private:
Nonnull<const AstNode*> base_;
std::function<std::string_view(const AstNode&)> name_;
std::function<const Value&(const AstNode&)> static_type_;
std::function<ValueCategory(const AstNode&)> value_category_;
std::function<std::optional<Nonnull<const Value*>>(const AstNode&)>
constant_value_;
std::function<void(const AstNode&, llvm::raw_ostream&)> print_;
std::function<const Value&(const AstNode&)> static_type_;
std::function<ValueCategory(const AstNode&)> value_category_;
};
// Maps the names visible in a given scope to the entities they name.
@@ -138,7 +133,7 @@ class StaticScope {
public:
// Defines `name` to be `entity` in this scope, or reports a compilation error
// if `name` is already defined to be a different entity in this scope.
void Add(std::string name, NamedEntityView entity);
void Add(std::string name, ValueNodeView entity);
// Make `parent` a parent of this scope.
// REQUIRES: `parent` is not already a parent of this scope.
@@ -150,17 +145,17 @@ class StaticScope {
// scope, or reports a compilation error at `source_loc` there isn't exactly
// one such definition.
auto Resolve(const std::string& name, SourceLocation source_loc) const
-> NamedEntityView;
-> ValueNodeView;
private:
// Equivalent to Resolve, but returns `nullopt` instead of raising an error
// if no definition can be found. Still raises a compilation error if more
// than one definition is found.
auto TryResolve(const std::string& name, SourceLocation source_loc) const
-> std::optional<NamedEntityView>;
-> std::optional<ValueNodeView>;
// Maps locally declared names to their entities.
std::unordered_map<std::string, NamedEntityView> declared_names_;
std::unordered_map<std::string, ValueNodeView> declared_names_;
// A list of scopes used for name lookup within this scope.
std::vector<Nonnull<StaticScope*>> parent_scopes_;