Mass rename SourceLoc and Tag (#860)

This does a mass rename of:

-   `SourceLoc()` -> `source_loc()` for property naming
    - `loc` -> `source_loc_` for underscore+consistency
    - Generally changing function args to `source_loc` for consistency
-   `Tag()` -> `kind()` for property naming and `Kind` parity
    - `tag` -> `kind_` for underscore

Also renames `Pos` and `Results` on `Action`. These are a bit of an exception in that most base classes only have `Tag` and maybe `SourceLoc`, whereas `Action` has a little more. I felt okay having `source_loc()` and `kind()` on the base class where children do `Exp()` and the like, but it felt weird to me to mix it on the same class.

The reason for doing this cross-class in one PR is so that I can do it efficiently with a global replace in the codebase, rather than e.g. changing `Expression` but having to read through compiler errors to determine where it's calling `Expression`'s `Tag` versus a different `Tag`. The end result should be equivalent.
This commit is contained in:
Jon Meow
2021-09-29 16:52:12 -07:00
committed by GitHub
parent c4e40aaa86
commit 70797e8bf8
27 changed files with 779 additions and 734 deletions
+4 -4
View File
@@ -22,7 +22,7 @@ namespace Carbon {
using llvm::cast;
void Action::Print(llvm::raw_ostream& out) const {
switch (Tag()) {
switch (kind()) {
case Action::Kind::LValAction:
out << *cast<LValAction>(*this).Exp();
break;
@@ -36,11 +36,11 @@ void Action::Print(llvm::raw_ostream& out) const {
cast<StatementAction>(*this).Stmt()->PrintDepth(1, out);
break;
}
out << "<" << pos << ">";
if (results.size() > 0) {
out << "<" << pos_ << ">";
if (results_.size() > 0) {
out << "(";
llvm::ListSeparator sep;
for (auto& result : results) {
for (auto& result : results_) {
out << sep << *result;
}
out << ")";
+31 -31
View File
@@ -29,48 +29,48 @@ class Action {
Action(const Value&) = delete;
Action& operator=(const Value&) = delete;
// The position or state of the action. Starts at 0 and goes up to the number
// of subexpressions.
//
// pos indicates how many of the entries in the following `results` vector
// will be filled in the next time this action is active.
// For each i < pos, results[i] contains a pointer to a Value.
auto Pos() const -> int { return pos; }
// Results from a subexpression.
auto Results() const -> const std::vector<Nonnull<const Value*>>& {
return results;
}
void SetPos(int pos) { this->pos = pos; }
void AddResult(Nonnull<const Value*> result) { results.push_back(result); }
void AddResult(Nonnull<const Value*> result) { results_.push_back(result); }
void Clear() {
pos = 0;
results.clear();
pos_ = 0;
results_.clear();
}
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
static void PrintList(const Stack<Nonnull<Action*>>& ls,
llvm::raw_ostream& out);
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto kind() const -> Kind { return kind_; }
// The position or state of the action. Starts at 0 and goes up to the number
// of subexpressions.
//
// pos indicates how many of the entries in the following `results` vector
// will be filled in the next time this action is active.
// For each i < pos, results[i] contains a pointer to a Value.
auto pos() const -> int { return pos_; }
void set_pos(int pos) { this->pos_ = pos; }
// Results from a subexpression.
auto results() const -> const std::vector<Nonnull<const Value*>>& {
return results_;
}
protected:
// Constructs an Action. `tag` must be the enumerator corresponding to the
// Constructs an Action. `kind` must be the enumerator corresponding to the
// most-derived type being constructed.
explicit Action(Kind kind) : kind(kind) {}
explicit Action(Kind kind) : kind_(kind) {}
private:
int pos = 0;
std::vector<Nonnull<const Value*>> results;
int pos_ = 0;
std::vector<Nonnull<const Value*>> results_;
const Kind kind;
const Kind kind_;
};
class LValAction : public Action {
@@ -79,7 +79,7 @@ class LValAction : public Action {
: Action(Kind::LValAction), exp(exp) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::LValAction;
return action->kind() == Kind::LValAction;
}
auto Exp() const -> Nonnull<const Expression*> { return exp; }
@@ -94,7 +94,7 @@ class ExpressionAction : public Action {
: Action(Kind::ExpressionAction), exp(exp) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::ExpressionAction;
return action->kind() == Kind::ExpressionAction;
}
auto Exp() const -> Nonnull<const Expression*> { return exp; }
@@ -109,7 +109,7 @@ class PatternAction : public Action {
: Action(Kind::PatternAction), pat(pat) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::PatternAction;
return action->kind() == Kind::PatternAction;
}
auto Pat() const -> Nonnull<const Pattern*> { return pat; }
@@ -124,7 +124,7 @@ class StatementAction : public Action {
: Action(Kind::StatementAction), stmt(stmt) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::StatementAction;
return action->kind() == Kind::StatementAction;
}
auto Stmt() const -> Nonnull<const Statement*> { return stmt; }
@@ -17,21 +17,21 @@ namespace Carbon {
// standardized, but is made available for printing state in tests.
static void AddIntrinsics(Nonnull<Arena*> arena,
std::vector<Nonnull<Declaration*>>* declarations) {
SourceLocation loc("<intrinsic>", 0);
SourceLocation source_loc("<intrinsic>", 0);
std::vector<TuplePattern::Field> print_fields = {TuplePattern::Field(
"0",
arena->New<BindingPattern>(
loc, "format_str",
arena->New<ExpressionPattern>(arena->New<StringTypeLiteral>(loc))))};
"0", arena->New<BindingPattern>(
source_loc, "format_str",
arena->New<ExpressionPattern>(
arena->New<StringTypeLiteral>(source_loc))))};
auto print_return =
arena->New<Return>(loc,
arena->New<Return>(source_loc,
arena->New<IntrinsicExpression>(
IntrinsicExpression::IntrinsicKind::Print),
false);
auto print = arena->New<FunctionDeclaration>(arena->New<FunctionDefinition>(
loc, "Print", std::vector<GenericBinding>(),
arena->New<TuplePattern>(loc, print_fields),
arena->New<ExpressionPattern>(arena->New<TupleLiteral>(loc)),
source_loc, "Print", std::vector<GenericBinding>(),
arena->New<TuplePattern>(source_loc, print_fields),
arena->New<ExpressionPattern>(arena->New<TupleLiteral>(source_loc)),
/*is_omitted_return_type=*/false, print_return));
declarations->insert(declarations->begin(), print);
}
@@ -62,10 +62,10 @@ void ExecProgram(Nonnull<Arena*> arena, AST ast) {
llvm::outs() << "********** starting execution **********\n";
}
SourceLocation loc("<main()>", 0);
SourceLocation source_loc("<main()>", 0);
Nonnull<Expression*> call_main = arena->New<CallExpression>(
loc, arena->New<IdentifierExpression>(loc, "main"),
arena->New<TupleLiteral>(loc));
source_loc, arena->New<IdentifierExpression>(source_loc, "main"),
arena->New<TupleLiteral>(source_loc));
int result = Interpreter(arena).InterpProgram(new_decls, call_main);
llvm::outs() << "result: " << result << "\n";
}
+12 -9
View File
@@ -20,21 +20,24 @@ auto Heap::AllocateValue(Nonnull<const Value*> v) -> Address {
return a;
}
auto Heap::Read(const Address& a, SourceLocation loc) -> Nonnull<const Value*> {
this->CheckAlive(a, loc);
return values[a.index]->GetField(arena, a.field_path, loc);
auto Heap::Read(const Address& a, SourceLocation source_loc)
-> Nonnull<const Value*> {
this->CheckAlive(a, source_loc);
return values[a.index]->GetField(arena, a.field_path, source_loc);
}
void Heap::Write(const Address& a, Nonnull<const Value*> v,
SourceLocation loc) {
this->CheckAlive(a, loc);
values[a.index] = values[a.index]->SetField(arena, a.field_path, v, loc);
SourceLocation source_loc) {
this->CheckAlive(a, source_loc);
values[a.index] =
values[a.index]->SetField(arena, a.field_path, v, source_loc);
}
void Heap::CheckAlive(const Address& address, SourceLocation loc) {
void Heap::CheckAlive(const Address& address, SourceLocation source_loc) {
if (!alive[address.index]) {
FATAL_RUNTIME_ERROR(loc) << "undefined behavior: access to dead value "
<< *values[address.index];
FATAL_RUNTIME_ERROR(source_loc)
<< "undefined behavior: access to dead value "
<< *values[address.index];
}
}
+5 -3
View File
@@ -25,11 +25,13 @@ class Heap {
// Returns the value at the given address in the heap after
// checking that it is alive.
auto Read(const Address& a, SourceLocation loc) -> Nonnull<const Value*>;
auto Read(const Address& a, SourceLocation source_loc)
-> Nonnull<const Value*>;
// Writes the given value at the address in the heap after
// checking that the address is alive.
void Write(const Address& a, Nonnull<const Value*> v, SourceLocation loc);
void Write(const Address& a, Nonnull<const Value*> v,
SourceLocation source_loc);
// Put the given value on the heap and mark it as alive.
auto AllocateValue(Nonnull<const Value*> v) -> Address;
@@ -47,7 +49,7 @@ class Heap {
private:
// Signal an error if the address is no longer alive.
void CheckAlive(const Address& address, SourceLocation loc);
void CheckAlive(const Address& address, SourceLocation source_loc);
Nonnull<Arena*> arena;
std::vector<Nonnull<const Value*>> values;
+171 -167
View File
@@ -51,11 +51,11 @@ auto Interpreter::CurrentEnv() -> Env {
}
// Returns the given name from the environment, printing an error if not found.
auto Interpreter::GetFromEnv(SourceLocation loc, const std::string& name)
auto Interpreter::GetFromEnv(SourceLocation source_loc, const std::string& name)
-> Address {
std::optional<Address> pointer = CurrentEnv().Get(name);
if (!pointer) {
FATAL_RUNTIME_ERROR(loc) << "could not find `" << name << "`";
FATAL_RUNTIME_ERROR(source_loc) << "could not find `" << name << "`";
}
return *pointer;
}
@@ -76,7 +76,7 @@ void Interpreter::PrintState(llvm::raw_ostream& out) {
auto Interpreter::EvalPrim(Operator op,
const std::vector<Nonnull<const Value*>>& args,
SourceLocation loc) -> Nonnull<const Value*> {
SourceLocation source_loc) -> Nonnull<const Value*> {
switch (op) {
case Operator::Neg:
return arena->New<IntValue>(-cast<IntValue>(*args[0]).Val());
@@ -98,7 +98,7 @@ auto Interpreter::EvalPrim(Operator op,
return arena->New<BoolValue>(cast<BoolValue>(*args[0]).Val() ||
cast<BoolValue>(*args[1]).Val());
case Operator::Eq:
return arena->New<BoolValue>(ValueEqual(args[0], args[1], loc));
return arena->New<BoolValue>(ValueEqual(args[0], args[1], source_loc));
case Operator::Ptr:
return arena->New<PointerType>(args[0]);
case Operator::Deref:
@@ -129,7 +129,7 @@ void Interpreter::InitEnv(const Declaration& d, Env* env) {
VarValues fields;
VarValues methods;
for (Nonnull<const Member*> m : class_def.members()) {
switch (m->Tag()) {
switch (m->kind()) {
case Member::Kind::FieldMember: {
Nonnull<const BindingPattern*> binding =
cast<FieldMember>(*m).Binding();
@@ -201,11 +201,11 @@ auto Interpreter::CreateTuple(Nonnull<Action*> act,
// { { (v1,...,vn) :: C, E, F} :: S, H}
// -> { { `(v1,...,vn) :: C, E, F} :: S, H}
const auto& tup_lit = cast<TupleLiteral>(*exp);
CHECK(act->Results().size() == tup_lit.Fields().size());
CHECK(act->results().size() == tup_lit.Fields().size());
std::vector<TupleElement> elements;
for (size_t i = 0; i < act->Results().size(); ++i) {
for (size_t i = 0; i < act->results().size(); ++i) {
elements.push_back(
{.name = tup_lit.Fields()[i].name, .value = act->Results()[i]});
{.name = tup_lit.Fields()[i].name, .value = act->results()[i]});
}
return arena->New<TupleValue>(std::move(elements));
@@ -224,37 +224,39 @@ auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
}
auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
SourceLocation loc) -> std::optional<Env> {
switch (p->Tag()) {
SourceLocation source_loc)
-> std::optional<Env> {
switch (p->kind()) {
case Value::Kind::BindingPlaceholderValue: {
const auto& placeholder = cast<BindingPlaceholderValue>(*p);
Env values(arena);
if (placeholder.Name().has_value()) {
Address a = heap.AllocateValue(CopyVal(arena, v, loc));
Address a = heap.AllocateValue(CopyVal(arena, v, source_loc));
values.Set(*placeholder.Name(), a);
}
return values;
}
case Value::Kind::TupleValue:
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::TupleValue: {
const auto& p_tup = cast<TupleValue>(*p);
const auto& v_tup = cast<TupleValue>(*v);
if (p_tup.Elements().size() != v_tup.Elements().size()) {
FATAL_PROGRAM_ERROR(loc)
FATAL_PROGRAM_ERROR(source_loc)
<< "arity mismatch in tuple pattern match:\n pattern: "
<< p_tup << "\n value: " << v_tup;
}
Env values(arena);
for (size_t i = 0; i < p_tup.Elements().size(); ++i) {
if (p_tup.Elements()[i].name != v_tup.Elements()[i].name) {
FATAL_PROGRAM_ERROR(loc)
FATAL_PROGRAM_ERROR(source_loc)
<< "Tuple field name '" << v_tup.Elements()[i].name
<< "' does not match pattern field name '"
<< p_tup.Elements()[i].name << "'";
}
std::optional<Env> matches = PatternMatch(
p_tup.Elements()[i].value, v_tup.Elements()[i].value, loc);
std::optional<Env> matches =
PatternMatch(p_tup.Elements()[i].value,
v_tup.Elements()[i].value, source_loc);
if (!matches) {
return std::nullopt;
}
@@ -274,8 +276,9 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
Env values(arena);
for (size_t i = 0; i < p_struct.elements().size(); ++i) {
CHECK(p_struct.elements()[i].name == v_struct.elements()[i].name);
std::optional<Env> matches = PatternMatch(
p_struct.elements()[i].value, v_struct.elements()[i].value, loc);
std::optional<Env> matches =
PatternMatch(p_struct.elements()[i].value,
v_struct.elements()[i].value, source_loc);
if (!matches) {
return std::nullopt;
}
@@ -286,7 +289,7 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
return values;
}
case Value::Kind::AlternativeValue:
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::AlternativeValue: {
const auto& p_alt = cast<AlternativeValue>(*p);
const auto& v_alt = cast<AlternativeValue>(*v);
@@ -294,23 +297,23 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
p_alt.AltName() != v_alt.AltName()) {
return std::nullopt;
}
return PatternMatch(p_alt.Argument(), v_alt.Argument(), loc);
return PatternMatch(p_alt.Argument(), v_alt.Argument(), source_loc);
}
default:
FATAL() << "expected a choice alternative in pattern, not " << *v;
}
case Value::Kind::FunctionType:
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::FunctionType: {
const auto& p_fn = cast<FunctionType>(*p);
const auto& v_fn = cast<FunctionType>(*v);
std::optional<Env> param_matches =
PatternMatch(p_fn.Param(), v_fn.Param(), loc);
PatternMatch(p_fn.Param(), v_fn.Param(), source_loc);
if (!param_matches) {
return std::nullopt;
}
std::optional<Env> ret_matches =
PatternMatch(p_fn.Ret(), v_fn.Ret(), loc);
PatternMatch(p_fn.Ret(), v_fn.Ret(), source_loc);
if (!ret_matches) {
return std::nullopt;
}
@@ -328,7 +331,7 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
// on the typechecker to ensure that `v` is a type.
return Env(arena);
default:
if (ValueEqual(p, v, loc)) {
if (ValueEqual(p, v, source_loc)) {
return Env(arena);
} else {
return std::nullopt;
@@ -338,18 +341,19 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
Nonnull<const Value*> val,
SourceLocation loc) {
switch (pat->Tag()) {
SourceLocation source_loc) {
switch (pat->kind()) {
case Value::Kind::PointerValue:
heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(arena, val, loc), loc);
heap.Write(cast<PointerValue>(*pat).Val(),
CopyVal(arena, val, source_loc), source_loc);
break;
case Value::Kind::TupleValue: {
switch (val->Tag()) {
switch (val->kind()) {
case Value::Kind::TupleValue: {
const auto& pat_tup = cast<TupleValue>(*pat);
const auto& val_tup = cast<TupleValue>(*val);
if (pat_tup.Elements().size() != val_tup.Elements().size()) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "arity mismatch in tuple pattern assignment:\n pattern: "
<< pat_tup << "\n value: " << val_tup;
}
@@ -357,10 +361,10 @@ void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
std::optional<Nonnull<const Value*>> value_field =
val_tup.FindField(pattern_element.name);
if (!value_field) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "field " << pattern_element.name << "not in " << *val;
}
PatternAssignment(pattern_element.value, *value_field, loc);
PatternAssignment(pattern_element.value, *value_field, source_loc);
}
break;
}
@@ -370,14 +374,14 @@ void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
break;
}
case Value::Kind::AlternativeValue: {
switch (val->Tag()) {
switch (val->kind()) {
case Value::Kind::AlternativeValue: {
const auto& pat_alt = cast<AlternativeValue>(*pat);
const auto& val_alt = cast<AlternativeValue>(*val);
CHECK(val_alt.ChoiceName() == pat_alt.ChoiceName() &&
val_alt.AltName() == pat_alt.AltName())
<< "internal error in pattern assignment";
PatternAssignment(pat_alt.Argument(), val_alt.Argument(), loc);
PatternAssignment(pat_alt.Argument(), val_alt.Argument(), source_loc);
break;
}
default:
@@ -386,7 +390,7 @@ void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
break;
}
default:
CHECK(ValueEqual(pat, val, loc))
CHECK(ValueEqual(pat, val, source_loc))
<< "internal error in pattern assignment";
}
}
@@ -395,20 +399,20 @@ auto Interpreter::StepLvalue() -> Transition {
Nonnull<Action*> act = stack.Top()->todo.Top();
Nonnull<const Expression*> exp = cast<LValAction>(*act).Exp();
if (tracing_output) {
llvm::outs() << "--- step lvalue " << *exp << " (" << exp->SourceLoc()
llvm::outs() << "--- step lvalue " << *exp << " (" << exp->source_loc()
<< ") --->\n";
}
switch (exp->Tag()) {
switch (exp->kind()) {
case Expression::Kind::IdentifierExpression: {
// { {x :: C, E, F} :: S, H}
// -> { {E(x) :: C, E, F} :: S, H}
Address pointer =
GetFromEnv(exp->SourceLoc(), cast<IdentifierExpression>(*exp).Name());
Address pointer = GetFromEnv(exp->source_loc(),
cast<IdentifierExpression>(*exp).Name());
Nonnull<const Value*> v = arena->New<PointerValue>(pointer);
return Done{v};
}
case Expression::Kind::FieldAccessExpression: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e.f :: C, E, F} :: S, H}
// -> { e :: [].f :: C, E, F} :: S, H}
return Spawn{arena->New<LValAction>(
@@ -416,41 +420,41 @@ auto Interpreter::StepLvalue() -> Transition {
} else {
// { v :: [].f :: C, E, F} :: S, H}
// -> { { &v.f :: C, E, F} :: S, H }
Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
Address aggregate = cast<PointerValue>(*act->results()[0]).Val();
Address field = aggregate.SubobjectAddress(
cast<FieldAccessExpression>(*exp).Field());
return Done{arena->New<PointerValue>(field)};
}
}
case Expression::Kind::IndexExpression: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e[i] :: C, E, F} :: S, H}
// -> { e :: [][i] :: C, E, F} :: S, H}
return Spawn{
arena->New<LValAction>(cast<IndexExpression>(*exp).Aggregate())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{
arena->New<ExpressionAction>(cast<IndexExpression>(*exp).Offset())};
} else {
// { v :: [][i] :: C, E, F} :: S, H}
// -> { { &v[i] :: C, E, F} :: S, H }
Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
Address aggregate = cast<PointerValue>(*act->results()[0]).Val();
std::string f =
std::to_string(cast<IntValue>(*act->Results()[1]).Val());
std::to_string(cast<IntValue>(*act->results()[1]).Val());
Address field = aggregate.SubobjectAddress(f);
return Done{arena->New<PointerValue>(field)};
}
}
case Expression::Kind::TupleLiteral: {
if (act->Pos() <
if (act->pos() <
static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
// { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
// H}
// -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
// H}
Nonnull<const Expression*> elt =
cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
cast<TupleLiteral>(*exp).Fields()[act->pos()].expression;
return Spawn{arena->New<LValAction>(elt)};
} else {
return Done{CreateTuple(act, exp)};
@@ -479,29 +483,29 @@ auto Interpreter::StepExp() -> Transition {
Nonnull<Action*> act = stack.Top()->todo.Top();
Nonnull<const Expression*> exp = cast<ExpressionAction>(*act).Exp();
if (tracing_output) {
llvm::outs() << "--- step exp " << *exp << " (" << exp->SourceLoc()
llvm::outs() << "--- step exp " << *exp << " (" << exp->source_loc()
<< ") --->\n";
}
switch (exp->Tag()) {
switch (exp->kind()) {
case Expression::Kind::IndexExpression: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { { e[i] :: C, E, F} :: S, H}
// -> { { e :: [][i] :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<IndexExpression>(*exp).Aggregate())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{
arena->New<ExpressionAction>(cast<IndexExpression>(*exp).Offset())};
} else {
// { { v :: [][i] :: C, E, F} :: S, H}
// -> { { v_i :: C, E, F} : S, H}
auto* tuple = dyn_cast<TupleValue>(act->Results()[0]);
auto* tuple = dyn_cast<TupleValue>(act->results()[0]);
if (tuple == nullptr) {
FATAL_RUNTIME_ERROR_NO_LINE()
<< "expected a tuple in field access, not " << *act->Results()[0];
<< "expected a tuple in field access, not " << *act->results()[0];
}
std::string f =
std::to_string(cast<IntValue>(*act->Results()[1]).Val());
std::to_string(cast<IntValue>(*act->results()[1]).Val());
std::optional<Nonnull<const Value*>> field = tuple->FindField(f);
if (!field) {
FATAL_RUNTIME_ERROR_NO_LINE()
@@ -511,14 +515,14 @@ auto Interpreter::StepExp() -> Transition {
}
}
case Expression::Kind::TupleLiteral: {
if (act->Pos() <
if (act->pos() <
static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
// { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
// H}
// -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
// H}
Nonnull<const Expression*> elt =
cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
cast<TupleLiteral>(*exp).Fields()[act->pos()].expression;
return Spawn{arena->New<ExpressionAction>(elt)};
} else {
return Done{CreateTuple(act, exp)};
@@ -526,93 +530,93 @@ auto Interpreter::StepExp() -> Transition {
}
case Expression::Kind::StructLiteral: {
const auto& literal = cast<StructLiteral>(*exp);
if (act->Pos() < static_cast<int>(literal.fields().size())) {
if (act->pos() < static_cast<int>(literal.fields().size())) {
Nonnull<const Expression*> elt =
literal.fields()[act->Pos()].expression;
literal.fields()[act->pos()].expression;
return Spawn{arena->New<ExpressionAction>(elt)};
} else {
return Done{CreateStruct(literal.fields(), act->Results())};
return Done{CreateStruct(literal.fields(), act->results())};
}
}
case Expression::Kind::StructTypeLiteral: {
const auto& struct_type = cast<StructTypeLiteral>(*exp);
if (act->Pos() < static_cast<int>(struct_type.fields().size())) {
if (act->pos() < static_cast<int>(struct_type.fields().size())) {
return Spawn{arena->New<ExpressionAction>(
struct_type.fields()[act->Pos()].expression)};
struct_type.fields()[act->pos()].expression)};
} else {
VarValues fields;
for (size_t i = 0; i < struct_type.fields().size(); ++i) {
fields.push_back({struct_type.fields()[i].name, act->Results()[i]});
fields.push_back({struct_type.fields()[i].name, act->results()[i]});
}
return Done{arena->New<StructType>(std::move(fields))};
}
}
case Expression::Kind::FieldAccessExpression: {
const auto& access = cast<FieldAccessExpression>(*exp);
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { { e.f :: C, E, F} :: S, H}
// -> { { e :: [].f :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(access.Aggregate())};
} else {
// { { v :: [].f :: C, E, F} :: S, H}
// -> { { v_f :: C, E, F} : S, H}
return Done{act->Results()[0]->GetField(
arena, FieldPath(access.Field()), exp->SourceLoc())};
return Done{act->results()[0]->GetField(
arena, FieldPath(access.Field()), exp->source_loc())};
}
}
case Expression::Kind::IdentifierExpression: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
const auto& ident = cast<IdentifierExpression>(*exp);
// { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
Address pointer = GetFromEnv(exp->SourceLoc(), ident.Name());
return Done{heap.Read(pointer, exp->SourceLoc())};
Address pointer = GetFromEnv(exp->source_loc(), ident.Name());
return Done{heap.Read(pointer, exp->source_loc())};
}
case Expression::Kind::IntLiteral:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
return Done{arena->New<IntValue>(cast<IntLiteral>(*exp).Val())};
case Expression::Kind::BoolLiteral:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
return Done{arena->New<BoolValue>(cast<BoolLiteral>(*exp).Val())};
case Expression::Kind::PrimitiveOperatorExpression: {
const auto& op = cast<PrimitiveOperatorExpression>(*exp);
if (act->Pos() != static_cast<int>(op.Arguments().size())) {
if (act->pos() != static_cast<int>(op.Arguments().size())) {
// { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
// -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
Nonnull<const Expression*> arg = op.Arguments()[act->Pos()];
Nonnull<const Expression*> arg = op.Arguments()[act->pos()];
return Spawn{arena->New<ExpressionAction>(arg)};
} else {
// { {v :: op(vs,[]) :: C, E, F} :: S, H}
// -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
return Done{EvalPrim(op.Op(), act->Results(), exp->SourceLoc())};
return Done{EvalPrim(op.Op(), act->results(), exp->source_loc())};
}
}
case Expression::Kind::CallExpression:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e1(e2) :: C, E, F} :: S, H}
// -> { {e1 :: [](e2) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<CallExpression>(*exp).Function())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
// { { v :: [](e) :: C, E, F} :: S, H}
// -> { { e :: v([]) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<CallExpression>(*exp).Argument())};
} else if (act->Pos() == 2) {
} else if (act->pos() == 2) {
// { { v2 :: v1([]) :: C, E, F} :: S, H}
// -> { {C',E',F'} :: {C, E, F} :: S, H}
switch (act->Results()[0]->Tag()) {
switch (act->results()[0]->kind()) {
case Value::Kind::NominalClassType: {
Nonnull<const Value*> arg =
CopyVal(arena, act->Results()[1], exp->SourceLoc());
return Done{arena->New<NominalClassValue>(act->Results()[0], arg)};
CopyVal(arena, act->results()[1], exp->source_loc());
return Done{arena->New<NominalClassValue>(act->results()[0], arg)};
}
case Value::Kind::AlternativeConstructorValue: {
const auto& alt =
cast<AlternativeConstructorValue>(*act->Results()[0]);
cast<AlternativeConstructorValue>(*act->results()[0]);
Nonnull<const Value*> arg =
CopyVal(arena, act->Results()[1], exp->SourceLoc());
CopyVal(arena, act->results()[1], exp->source_loc());
return Done{arena->New<AlternativeValue>(alt.AltName(),
alt.ChoiceName(), arg)};
}
@@ -621,46 +625,46 @@ auto Interpreter::StepExp() -> Transition {
// TODO: Think about a cleaner way to cast between Ptr types.
// (multiple TODOs)
.function = Nonnull<const FunctionValue*>(
cast<FunctionValue>(act->Results()[0])),
.args = act->Results()[1],
.loc = exp->SourceLoc()};
cast<FunctionValue>(act->results()[0])),
.args = act->results()[1],
.source_loc = exp->source_loc()};
default:
FATAL_RUNTIME_ERROR(exp->SourceLoc())
<< "in call, expected a function, not " << *act->Results()[0];
FATAL_RUNTIME_ERROR(exp->source_loc())
<< "in call, expected a function, not " << *act->results()[0];
}
} else {
FATAL() << "in handle_value with Call pos " << act->Pos();
FATAL() << "in handle_value with Call pos " << act->pos();
}
case Expression::Kind::IntrinsicExpression:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
switch (cast<IntrinsicExpression>(*exp).Intrinsic()) {
case IntrinsicExpression::IntrinsicKind::Print:
Address pointer = GetFromEnv(exp->SourceLoc(), "format_str");
Nonnull<const Value*> pointee = heap.Read(pointer, exp->SourceLoc());
CHECK(pointee->Tag() == Value::Kind::StringValue);
Address pointer = GetFromEnv(exp->source_loc(), "format_str");
Nonnull<const Value*> pointee = heap.Read(pointer, exp->source_loc());
CHECK(pointee->kind() == Value::Kind::StringValue);
// TODO: This could eventually use something like llvm::formatv.
llvm::outs() << cast<StringValue>(*pointee).Val();
return Done{TupleValue::Empty()};
}
case Expression::Kind::IntTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<IntType>()};
}
case Expression::Kind::BoolTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<BoolType>()};
}
case Expression::Kind::TypeTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<TypeType>()};
}
case Expression::Kind::FunctionTypeLiteral: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<ExpressionAction>(
cast<FunctionTypeLiteral>(*exp).Parameter())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
// { { pt :: fn [] -> e :: C, E, F} :: S, H}
// -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
@@ -669,23 +673,23 @@ auto Interpreter::StepExp() -> Transition {
// { { rt :: fn pt -> [] :: C, E, F} :: S, H}
// -> { fn pt -> rt :: {C, E, F} :: S, H}
return Done{arena->New<FunctionType>(std::vector<GenericBinding>(),
act->Results()[0],
act->Results()[1])};
act->results()[0],
act->results()[1])};
}
}
case Expression::Kind::ContinuationTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<ContinuationType>()};
}
case Expression::Kind::StringLiteral:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
return Done{arena->New<StringValue>(cast<StringLiteral>(*exp).Val())};
case Expression::Kind::StringTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<StringType>()};
}
} // switch (exp->Tag)
} // switch (exp->kind)
}
auto Interpreter::StepPattern() -> Transition {
@@ -693,52 +697,52 @@ auto Interpreter::StepPattern() -> Transition {
Nonnull<const Pattern*> pattern = cast<PatternAction>(*act).Pat();
if (tracing_output) {
llvm::outs() << "--- step pattern " << *pattern << " ("
<< pattern->SourceLoc() << ") --->\n";
<< pattern->source_loc() << ") --->\n";
}
switch (pattern->Tag()) {
switch (pattern->kind()) {
case Pattern::Kind::AutoPattern: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<AutoType>()};
}
case Pattern::Kind::BindingPattern: {
const auto& binding = cast<BindingPattern>(*pattern);
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<PatternAction>(binding.Type())};
} else {
return Done{arena->New<BindingPlaceholderValue>(binding.Name(),
act->Results()[0])};
act->results()[0])};
}
}
case Pattern::Kind::TuplePattern: {
const auto& tuple = cast<TuplePattern>(*pattern);
if (act->Pos() < static_cast<int>(tuple.Fields().size())) {
if (act->pos() < static_cast<int>(tuple.Fields().size())) {
// { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
// H}
// -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
// H}
Nonnull<const Pattern*> elt = tuple.Fields()[act->Pos()].pattern;
Nonnull<const Pattern*> elt = tuple.Fields()[act->pos()].pattern;
return Spawn{arena->New<PatternAction>(elt)};
} else {
std::vector<TupleElement> elements;
for (size_t i = 0; i < tuple.Fields().size(); ++i) {
elements.push_back(
{.name = tuple.Fields()[i].name, .value = act->Results()[i]});
{.name = tuple.Fields()[i].name, .value = act->results()[i]});
}
return Done{arena->New<TupleValue>(std::move(elements))};
}
}
case Pattern::Kind::AlternativePattern: {
const auto& alternative = cast<AlternativePattern>(*pattern);
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<ExpressionAction>(alternative.ChoiceType())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{arena->New<PatternAction>(alternative.Arguments())};
} else {
CHECK(act->Pos() == 2);
const auto& choice_type = cast<ChoiceType>(*act->Results()[0]);
CHECK(act->pos() == 2);
const auto& choice_type = cast<ChoiceType>(*act->results()[0]);
return Done{arena->New<AlternativeValue>(alternative.AlternativeName(),
choice_type.Name(),
act->Results()[1])};
act->results()[1])};
}
}
case Pattern::Kind::ExpressionPattern:
@@ -748,9 +752,9 @@ auto Interpreter::StepPattern() -> Transition {
}
static auto IsWhileAct(Nonnull<Action*> act) -> bool {
switch (act->Tag()) {
switch (act->kind()) {
case Action::Kind::StatementAction:
switch (cast<StatementAction>(*act).Stmt()->Tag()) {
switch (cast<StatementAction>(*act).Stmt()->kind()) {
case Statement::Kind::While:
return true;
default:
@@ -762,9 +766,9 @@ static auto IsWhileAct(Nonnull<Action*> act) -> bool {
}
static auto HasLocalScope(Nonnull<Action*> act) -> bool {
switch (act->Tag()) {
switch (act->kind()) {
case Action::Kind::StatementAction:
switch (cast<StatementAction>(*act).Stmt()->Tag()) {
switch (cast<StatementAction>(*act).Stmt()->kind()) {
case Statement::Kind::Block:
case Statement::Kind::Match:
return true;
@@ -783,27 +787,27 @@ auto Interpreter::StepStmt() -> Transition {
if (tracing_output) {
llvm::outs() << "--- step stmt ";
stmt->PrintDepth(1, llvm::outs());
llvm::outs() << " (" << stmt->SourceLoc() << ") --->\n";
llvm::outs() << " (" << stmt->source_loc() << ") --->\n";
}
switch (stmt->Tag()) {
switch (stmt->kind()) {
case Statement::Kind::Match: {
const auto& match_stmt = cast<Match>(*stmt);
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { { (match (e) ...) :: C, E, F} :: S, H}
// -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
frame->scopes.Push(arena->New<Scope>(CurrentEnv()));
return Spawn{arena->New<ExpressionAction>(&match_stmt.expression())};
} else {
// Regarding act->Pos():
// Regarding act->pos():
// * odd: start interpreting the pattern of a clause
// * even: finished interpreting the pattern, now try to match
//
// Regarding act->Results():
// Regarding act->results():
// * 0: the value that we're matching
// * 1: the pattern for clause 0
// * 2: the pattern for clause 1
// * ...
auto clause_num = (act->Pos() - 1) / 2;
auto clause_num = (act->pos() - 1) / 2;
if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
DeallocateScope(frame->scopes.Top());
frame->scopes.Pop();
@@ -811,18 +815,18 @@ auto Interpreter::StepStmt() -> Transition {
}
auto c = match_stmt.clauses()[clause_num];
if (act->Pos() % 2 == 1) {
if (act->pos() % 2 == 1) {
// start interpreting the pattern of the clause
// { {v :: (match ([]) ...) :: C, E, F} :: S, H}
// -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
return Spawn{arena->New<PatternAction>(&c.pattern())};
} else { // try to match
auto v = act->Results()[0];
auto pat = act->Results()[clause_num + 1];
std::optional<Env> matches = PatternMatch(pat, v, stmt->SourceLoc());
auto v = act->results()[0];
auto pat = act->results()[clause_num + 1];
std::optional<Env> matches = PatternMatch(pat, v, stmt->source_loc());
if (matches) { // we have a match, start the body
// Ensure we don't process any more clauses.
act->SetPos(2 * match_stmt.clauses().size() + 1);
act->set_pos(2 * match_stmt.clauses().size() + 1);
for (const auto& [name, value] : *matches) {
frame->scopes.Top()->values.Set(name, value);
@@ -836,12 +840,12 @@ auto Interpreter::StepStmt() -> Transition {
}
}
case Statement::Kind::While:
if (act->Pos() % 2 == 0) {
if (act->pos() % 2 == 0) {
// { { (while (e) s) :: C, E, F} :: S, H}
// -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
act->Clear();
return Spawn{arena->New<ExpressionAction>(cast<While>(*stmt).Cond())};
} else if (cast<BoolValue>(*act->Results().back()).Val()) {
} else if (cast<BoolValue>(*act->results().back()).Val()) {
// { {true :: (while ([]) s) :: C, E, F} :: S, H}
// -> { { s :: (while (e) s) :: C, E, F } :: S, H}
return Spawn{arena->New<StatementAction>(cast<While>(*stmt).Body())};
@@ -851,32 +855,32 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::Break: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
// -> { { C, E', F} :: S, H}
auto it =
std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
if (it == frame->todo.end()) {
FATAL_RUNTIME_ERROR(stmt->SourceLoc())
FATAL_RUNTIME_ERROR(stmt->source_loc())
<< "`break` not inside `while` statement";
}
++it;
return UnwindTo{*it};
}
case Statement::Kind::Continue: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
// -> { { (while (e) s) :: C, E', F} :: S, H}
auto it =
std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
if (it == frame->todo.end()) {
FATAL_RUNTIME_ERROR(stmt->SourceLoc())
FATAL_RUNTIME_ERROR(stmt->source_loc())
<< "`continue` not inside `while` statement";
}
return UnwindTo{*it};
}
case Statement::Kind::Block: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
const Block& block = cast<Block>(*stmt);
if (block.Stmt()) {
frame->scopes.Push(arena->New<Scope>(CurrentEnv()));
@@ -892,23 +896,23 @@ auto Interpreter::StepStmt() -> Transition {
}
}
case Statement::Kind::VariableDefinition:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {(var x = e) :: C, E, F} :: S, H}
// -> { {e :: (var x = []) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<VariableDefinition>(*stmt).Init())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{
arena->New<PatternAction>(cast<VariableDefinition>(*stmt).Pat())};
} else {
// { { v :: (x = []) :: C, E, F} :: S, H}
// -> { { C, E(x := a), F} :: S, H(a := copy(v))}
Nonnull<const Value*> v = act->Results()[0];
Nonnull<const Value*> p = act->Results()[1];
Nonnull<const Value*> v = act->results()[0];
Nonnull<const Value*> p = act->results()[1];
std::optional<Env> matches = PatternMatch(p, v, stmt->SourceLoc());
std::optional<Env> matches = PatternMatch(p, v, stmt->source_loc());
CHECK(matches)
<< stmt->SourceLoc()
<< stmt->source_loc()
<< ": internal error in variable definition, match failed";
for (const auto& [name, value] : *matches) {
frame->scopes.Top()->values.Set(name, value);
@@ -917,7 +921,7 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::ExpressionStatement:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e :: C, E, F} :: S, H}
// -> { {e :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
@@ -926,28 +930,28 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::Assign:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {(lv = e) :: C, E, F} :: S, H}
// -> { {lv :: ([] = e) :: C, E, F} :: S, H}
return Spawn{arena->New<LValAction>(cast<Assign>(*stmt).Lhs())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
// { { a :: ([] = e) :: C, E, F} :: S, H}
// -> { { e :: (a = []) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs())};
} else {
// { { v :: (a = []) :: C, E, F} :: S, H}
// -> { { C, E, F} :: S, H(a := v)}
auto pat = act->Results()[0];
auto val = act->Results()[1];
PatternAssignment(pat, val, stmt->SourceLoc());
auto pat = act->results()[0];
auto val = act->results()[1];
PatternAssignment(pat, val, stmt->source_loc());
return Done{};
}
case Statement::Kind::If:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
// -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(cast<If>(*stmt).Cond())};
} else if (cast<BoolValue>(*act->Results()[0]).Val()) {
} else if (cast<BoolValue>(*act->results()[0]).Val()) {
// { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
// S, H}
// -> { { then_stmt :: C, E, F } :: S, H}
@@ -963,7 +967,7 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::Return:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {return e :: C, E, F} :: S, H}
// -> { {e :: return [] :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(cast<Return>(*stmt).Exp())};
@@ -971,14 +975,14 @@ auto Interpreter::StepStmt() -> Transition {
// { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
// -> { {v :: C', E', F'} :: S, H}
Nonnull<const Value*> ret_val =
CopyVal(arena, act->Results()[0], stmt->SourceLoc());
CopyVal(arena, act->results()[0], stmt->source_loc());
return UnwindFunctionCall{ret_val};
}
case Statement::Kind::Sequence: {
// { { (s1,s2) :: C, E, F} :: S, H}
// -> { { s1 :: s2 :: C, E, F} :: S, H}
const Sequence& seq = cast<Sequence>(*stmt);
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<StatementAction>(seq.Stmt())};
} else {
if (seq.Next()) {
@@ -990,13 +994,13 @@ auto Interpreter::StepStmt() -> Transition {
}
}
case Statement::Kind::Continuation: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// Create a continuation object by creating a frame similar the
// way one is created in a function call.
auto scopes = Stack<Nonnull<Scope*>>(arena->New<Scope>(CurrentEnv()));
Stack<Nonnull<Action*>> todo;
todo.Push(arena->New<StatementAction>(
arena->New<Return>(arena, stmt->SourceLoc())));
arena->New<Return>(arena, stmt->source_loc())));
todo.Push(arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
auto continuation_frame =
arena->New<Frame>("__continuation", scopes, todo);
@@ -1014,7 +1018,7 @@ auto Interpreter::StepStmt() -> Transition {
return ManualTransition{};
}
case Statement::Kind::Run:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// Evaluate the argument of the run statement.
return Spawn{arena->New<ExpressionAction>(cast<Run>(*stmt).Argument())};
} else {
@@ -1023,12 +1027,12 @@ auto Interpreter::StepStmt() -> Transition {
// value from the continuation.
auto ignore_result =
arena->New<StatementAction>(arena->New<ExpressionStatement>(
stmt->SourceLoc(),
arena->New<TupleLiteral>(stmt->SourceLoc())));
stmt->source_loc(),
arena->New<TupleLiteral>(stmt->source_loc())));
frame->todo.Push(ignore_result);
// Push the continuation onto the current stack.
const std::vector<Nonnull<Frame*>>& continuation_vector =
cast<ContinuationValue>(*act->Results()[0]).Stack();
cast<ContinuationValue>(*act->results()[0]).Stack();
for (auto frame_iter = continuation_vector.rbegin();
frame_iter != continuation_vector.rend(); ++frame_iter) {
stack.Push(*frame_iter);
@@ -1036,7 +1040,7 @@ auto Interpreter::StepStmt() -> Transition {
return ManualTransition{};
}
case Statement::Kind::Await:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// Pause the current continuation
frame->todo.Pop();
std::vector<Nonnull<Frame*>> paused;
@@ -1045,7 +1049,7 @@ auto Interpreter::StepStmt() -> Transition {
} while (paused.back()->continuation == std::nullopt);
// Update the continuation with the paused stack.
heap.Write(*paused.back()->continuation,
arena->New<ContinuationValue>(paused), stmt->SourceLoc());
arena->New<ContinuationValue>(paused), stmt->source_loc());
return ManualTransition{};
}
}
@@ -1057,7 +1061,7 @@ class Interpreter::DoTransition {
void operator()(const Done& done) {
Nonnull<Frame*> frame = interpreter->stack.Top();
if (frame->todo.Top()->Tag() != Action::Kind::StatementAction) {
if (frame->todo.Top()->kind() != Action::Kind::StatementAction) {
CHECK(done.result);
frame->todo.Pop();
if (frame->todo.IsEmpty()) {
@@ -1074,7 +1078,7 @@ class Interpreter::DoTransition {
void operator()(const Spawn& spawn) {
Nonnull<Frame*> frame = interpreter->stack.Top();
Nonnull<Action*> action = frame->todo.Top();
action->SetPos(action->Pos() + 1);
action->set_pos(action->pos() + 1);
frame->todo.Push(spawn.child);
}
@@ -1086,7 +1090,7 @@ class Interpreter::DoTransition {
void operator()(const RunAgain&) {
Nonnull<Action*> action = interpreter->stack.Top()->todo.Top();
action->SetPos(action->Pos() + 1);
action->set_pos(action->pos() + 1);
}
void operator()(const UnwindTo& unwind_to) {
@@ -1112,8 +1116,8 @@ class Interpreter::DoTransition {
void operator()(const CallFunction& call) {
interpreter->stack.Top()->todo.Pop();
std::optional<Env> matches =
interpreter->PatternMatch(call.function->Param(), call.args, call.loc);
std::optional<Env> matches = interpreter->PatternMatch(
call.function->Param(), call.args, call.source_loc);
CHECK(matches.has_value())
<< "internal error in call_function, pattern match failed";
// Create the new frame and push it on the stack
@@ -1148,7 +1152,7 @@ void Interpreter::Step() {
}
Nonnull<Action*> act = frame->todo.Top();
switch (act->Tag()) {
switch (act->kind()) {
case Action::Kind::LValAction:
std::visit(DoTransition(this), StepLvalue());
break;
@@ -42,7 +42,7 @@ class Interpreter {
// Attempts to match `v` against the pattern `p`. If matching succeeds,
// returns the bindings of pattern variables to their matched values.
auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
SourceLocation loc) -> std::optional<Env>;
SourceLocation source_loc) -> std::optional<Env>;
// Support TypeChecker allocating values on the heap.
auto AllocateValue(Nonnull<const Value*> v) -> Address {
@@ -102,7 +102,7 @@ class Interpreter {
struct CallFunction {
Nonnull<const FunctionValue*> function;
Nonnull<const Value*> args;
SourceLocation loc;
SourceLocation source_loc;
};
// Transition type which does nothing.
@@ -131,7 +131,8 @@ class Interpreter {
void InitGlobals(const std::vector<Nonnull<const Declaration*>>& fs);
auto CurrentEnv() -> Env;
auto GetFromEnv(SourceLocation loc, const std::string& name) -> Address;
auto GetFromEnv(SourceLocation source_loc, const std::string& name)
-> Address;
void DeallocateScope(Nonnull<Scope*> scope);
void DeallocateLocals(Nonnull<Frame*> frame);
@@ -143,10 +144,10 @@ class Interpreter {
-> Nonnull<const Value*>;
auto EvalPrim(Operator op, const std::vector<Nonnull<const Value*>>& args,
SourceLocation loc) -> Nonnull<const Value*>;
SourceLocation source_loc) -> Nonnull<const Value*>;
void PatternAssignment(Nonnull<const Value*> pat, Nonnull<const Value*> val,
SourceLocation loc);
SourceLocation source_loc);
void PrintState(llvm::raw_ostream& out);
+165 -158
View File
@@ -40,72 +40,75 @@ void PrintTypeEnv(TypeEnv types, llvm::raw_ostream& out) {
}
}
static void ExpectType(SourceLocation loc, const std::string& context,
static void ExpectType(SourceLocation source_loc, const std::string& context,
Nonnull<const Value*> expected,
Nonnull<const Value*> actual) {
if (!TypeEqual(expected, actual)) {
FATAL_COMPILATION_ERROR(loc) << "type error in " << context << "\n"
<< "expected: " << *expected << "\n"
<< "actual: " << *actual;
FATAL_COMPILATION_ERROR(source_loc) << "type error in " << context << "\n"
<< "expected: " << *expected << "\n"
<< "actual: " << *actual;
}
}
static void ExpectPointerType(SourceLocation loc, const std::string& context,
static void ExpectPointerType(SourceLocation source_loc,
const std::string& context,
Nonnull<const Value*> actual) {
if (actual->Tag() != Value::Kind::PointerType) {
FATAL_COMPILATION_ERROR(loc) << "type error in " << context << "\n"
<< "expected a pointer type\n"
<< "actual: " << *actual;
if (actual->kind() != Value::Kind::PointerType) {
FATAL_COMPILATION_ERROR(source_loc) << "type error in " << context << "\n"
<< "expected a pointer type\n"
<< "actual: " << *actual;
}
}
auto TypeChecker::ReifyType(Nonnull<const Value*> t, SourceLocation loc)
auto TypeChecker::ReifyType(Nonnull<const Value*> t, SourceLocation source_loc)
-> Nonnull<Expression*> {
switch (t->Tag()) {
switch (t->kind()) {
case Value::Kind::IntType:
return arena->New<IntTypeLiteral>(loc);
return arena->New<IntTypeLiteral>(source_loc);
case Value::Kind::BoolType:
return arena->New<BoolTypeLiteral>(loc);
return arena->New<BoolTypeLiteral>(source_loc);
case Value::Kind::TypeType:
return arena->New<TypeTypeLiteral>(loc);
return arena->New<TypeTypeLiteral>(source_loc);
case Value::Kind::ContinuationType:
return arena->New<ContinuationTypeLiteral>(loc);
return arena->New<ContinuationTypeLiteral>(source_loc);
case Value::Kind::FunctionType: {
const auto& fn_type = cast<FunctionType>(*t);
return arena->New<FunctionTypeLiteral>(
loc, ReifyType(fn_type.Param(), loc), ReifyType(fn_type.Ret(), loc),
source_loc, ReifyType(fn_type.Param(), source_loc),
ReifyType(fn_type.Ret(), source_loc),
/*is_omitted_return_type=*/false);
}
case Value::Kind::TupleValue: {
std::vector<FieldInitializer> args;
for (const TupleElement& field : cast<TupleValue>(*t).Elements()) {
args.push_back(
FieldInitializer(field.name, ReifyType(field.value, loc)));
FieldInitializer(field.name, ReifyType(field.value, source_loc)));
}
return arena->New<TupleLiteral>(loc, args);
return arena->New<TupleLiteral>(source_loc, args);
}
case Value::Kind::StructType: {
std::vector<FieldInitializer> args;
for (const auto& [name, type] : cast<StructType>(*t).fields()) {
args.push_back(FieldInitializer(name, ReifyType(type, loc)));
args.push_back(FieldInitializer(name, ReifyType(type, source_loc)));
}
return arena->New<StructTypeLiteral>(loc, args);
return arena->New<StructTypeLiteral>(source_loc, args);
}
case Value::Kind::NominalClassType:
return arena->New<IdentifierExpression>(
loc, cast<NominalClassType>(*t).Name());
source_loc, cast<NominalClassType>(*t).Name());
case Value::Kind::ChoiceType:
return arena->New<IdentifierExpression>(loc, cast<ChoiceType>(*t).Name());
return arena->New<IdentifierExpression>(source_loc,
cast<ChoiceType>(*t).Name());
case Value::Kind::PointerType:
return arena->New<PrimitiveOperatorExpression>(
loc, Operator::Ptr,
source_loc, Operator::Ptr,
std::vector<Nonnull<Expression*>>(
{ReifyType(cast<PointerType>(*t).Type(), loc)}));
{ReifyType(cast<PointerType>(*t).Type(), source_loc)}));
case Value::Kind::VariableType:
return arena->New<IdentifierExpression>(loc,
return arena->New<IdentifierExpression>(source_loc,
cast<VariableType>(*t).Name());
case Value::Kind::StringType:
return arena->New<StringTypeLiteral>(loc);
return arena->New<StringTypeLiteral>(source_loc);
case Value::Kind::AlternativeConstructorValue:
case Value::Kind::AlternativeValue:
case Value::Kind::AutoType:
@@ -128,78 +131,81 @@ auto TypeChecker::ReifyType(Nonnull<const Value*> t, SourceLocation loc)
// inside the argument type.
// The `deduced` parameter is an accumulator, that is, it holds the
// results so-far.
static auto ArgumentDeduction(SourceLocation loc, TypeEnv deduced,
static auto ArgumentDeduction(SourceLocation source_loc, TypeEnv deduced,
Nonnull<const Value*> param,
Nonnull<const Value*> arg) -> TypeEnv {
switch (param->Tag()) {
switch (param->kind()) {
case Value::Kind::VariableType: {
const auto& var_type = cast<VariableType>(*param);
std::optional<Nonnull<const Value*>> d = deduced.Get(var_type.Name());
if (!d) {
deduced.Set(var_type.Name(), arg);
} else {
ExpectType(loc, "argument deduction", *d, arg);
ExpectType(source_loc, "argument deduction", *d, arg);
}
return deduced;
}
case Value::Kind::TupleValue: {
if (arg->Tag() != Value::Kind::TupleValue) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::TupleValue) {
ExpectType(source_loc, "argument deduction", param, arg);
}
const auto& param_tup = cast<TupleValue>(*param);
const auto& arg_tup = cast<TupleValue>(*arg);
if (param_tup.Elements().size() != arg_tup.Elements().size()) {
ExpectType(loc, "argument deduction", param, arg);
ExpectType(source_loc, "argument deduction", param, arg);
}
for (size_t i = 0; i < param_tup.Elements().size(); ++i) {
if (param_tup.Elements()[i].name != arg_tup.Elements()[i].name) {
FATAL_COMPILATION_ERROR(loc)
FATAL_COMPILATION_ERROR(source_loc)
<< "mismatch in tuple names, " << param_tup.Elements()[i].name
<< " != " << arg_tup.Elements()[i].name;
}
deduced = ArgumentDeduction(loc, deduced, param_tup.Elements()[i].value,
deduced = ArgumentDeduction(source_loc, deduced,
param_tup.Elements()[i].value,
arg_tup.Elements()[i].value);
}
return deduced;
}
case Value::Kind::StructType: {
if (arg->Tag() != Value::Kind::StructType) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::StructType) {
ExpectType(source_loc, "argument deduction", param, arg);
}
const auto& param_struct = cast<StructType>(*param);
const auto& arg_struct = cast<StructType>(*arg);
if (param_struct.fields().size() != arg_struct.fields().size()) {
ExpectType(loc, "argument deduction", param, arg);
ExpectType(source_loc, "argument deduction", param, arg);
}
for (size_t i = 0; i < param_struct.fields().size(); ++i) {
if (param_struct.fields()[i].first != arg_struct.fields()[i].first) {
FATAL_COMPILATION_ERROR(loc)
FATAL_COMPILATION_ERROR(source_loc)
<< "mismatch in field names, " << param_struct.fields()[i].first
<< " != " << arg_struct.fields()[i].first;
}
deduced =
ArgumentDeduction(loc, deduced, param_struct.fields()[i].second,
arg_struct.fields()[i].second);
deduced = ArgumentDeduction(source_loc, deduced,
param_struct.fields()[i].second,
arg_struct.fields()[i].second);
}
return deduced;
}
case Value::Kind::FunctionType: {
if (arg->Tag() != Value::Kind::FunctionType) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::FunctionType) {
ExpectType(source_loc, "argument deduction", param, arg);
}
const auto& param_fn = cast<FunctionType>(*param);
const auto& arg_fn = cast<FunctionType>(*arg);
// TODO: handle situation when arg has deduced parameters.
deduced = ArgumentDeduction(source_loc, deduced, param_fn.Param(),
arg_fn.Param());
deduced =
ArgumentDeduction(loc, deduced, param_fn.Param(), arg_fn.Param());
deduced = ArgumentDeduction(loc, deduced, param_fn.Ret(), arg_fn.Ret());
ArgumentDeduction(source_loc, deduced, param_fn.Ret(), arg_fn.Ret());
return deduced;
}
case Value::Kind::PointerType: {
if (arg->Tag() != Value::Kind::PointerType) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::PointerType) {
ExpectType(source_loc, "argument deduction", param, arg);
}
return ArgumentDeduction(loc, deduced, cast<PointerType>(*param).Type(),
return ArgumentDeduction(source_loc, deduced,
cast<PointerType>(*param).Type(),
cast<PointerType>(*arg).Type());
}
// Nothing to do in the case for `auto`.
@@ -214,7 +220,7 @@ static auto ArgumentDeduction(SourceLocation loc, TypeEnv deduced,
case Value::Kind::BoolType:
case Value::Kind::TypeType:
case Value::Kind::StringType:
ExpectType(loc, "argument deduction", param, arg);
ExpectType(source_loc, "argument deduction", param, arg);
return deduced;
// The rest of these cases should never happen.
case Value::Kind::IntValue:
@@ -234,7 +240,7 @@ static auto ArgumentDeduction(SourceLocation loc, TypeEnv deduced,
auto TypeChecker::Substitute(TypeEnv dict, Nonnull<const Value*> type)
-> Nonnull<const Value*> {
switch (type->Tag()) {
switch (type->kind()) {
case Value::Kind::VariableType: {
std::optional<Nonnull<const Value*>> t =
dict.Get(cast<VariableType>(*type).Name());
@@ -305,12 +311,12 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
interpreter.PrintEnv(values, llvm::outs());
llvm::outs() << "\n";
}
switch (e->Tag()) {
switch (e->kind()) {
case Expression::Kind::IndexExpression: {
auto& index = cast<IndexExpression>(*e);
auto res = TypeCheckExp(index.Aggregate(), types, values);
auto t = res.type;
switch (t->Tag()) {
switch (t->kind()) {
case Value::Kind::TupleValue: {
auto i =
cast<IntValue>(*interpreter.InterpExp(values, index.Offset()))
@@ -319,16 +325,16 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
std::optional<Nonnull<const Value*>> field_t =
cast<TupleValue>(*t).FindField(f);
if (!field_t) {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "field " << f << " is not in the tuple " << *t;
}
auto new_e = arena->New<IndexExpression>(
e->SourceLoc(), res.exp,
arena->New<IntLiteral>(e->SourceLoc(), i));
e->source_loc(), res.exp,
arena->New<IntLiteral>(e->source_loc(), i));
return TCExpression(new_e, *field_t, res.types);
}
default:
FATAL_COMPILATION_ERROR(e->SourceLoc()) << "expected a tuple";
FATAL_COMPILATION_ERROR(e->source_loc()) << "expected a tuple";
}
}
case Expression::Kind::TupleLiteral: {
@@ -341,7 +347,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
new_args.push_back(FieldInitializer(arg.name, arg_res.exp));
arg_types.push_back({.name = arg.name, .value = arg_res.type});
}
auto tuple_e = arena->New<TupleLiteral>(e->SourceLoc(), new_args);
auto tuple_e = arena->New<TupleLiteral>(e->source_loc(), new_args);
auto tuple_t = arena->New<TupleValue>(std::move(arg_types));
return TCExpression(tuple_e, tuple_t, new_types);
}
@@ -355,7 +361,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
new_args.push_back(FieldInitializer(arg.name, arg_res.exp));
arg_types.push_back({arg.name, arg_res.type});
}
auto new_e = arena->New<StructLiteral>(e->SourceLoc(), new_args);
auto new_e = arena->New<StructLiteral>(e->source_loc(), new_args);
auto type = arena->New<StructType>(std::move(arg_types));
return TCExpression(new_e, type, new_types);
}
@@ -368,9 +374,9 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
new_types = arg_res.types;
Nonnull<const Value*> type = interpreter.InterpExp(values, arg_res.exp);
new_args.push_back(
FieldInitializer(arg.name, ReifyType(type, e->SourceLoc())));
FieldInitializer(arg.name, ReifyType(type, e->source_loc())));
}
auto new_e = arena->New<StructTypeLiteral>(e->SourceLoc(), new_args);
auto new_e = arena->New<StructTypeLiteral>(e->source_loc(), new_args);
Nonnull<const Value*> type;
if (struct_type.fields().empty()) {
// `{}` is the type of `{}`, just as `()` is the type of `()`.
@@ -387,17 +393,17 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
auto& access = cast<FieldAccessExpression>(*e);
auto res = TypeCheckExp(access.Aggregate(), types, values);
auto t = res.type;
switch (t->Tag()) {
switch (t->kind()) {
case Value::Kind::StructType: {
const auto& struct_type = cast<StructType>(*t);
for (const auto& [field_name, field_type] : struct_type.fields()) {
if (access.Field() == field_name) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
access.SourceLoc(), res.exp, access.Field());
access.source_loc(), res.exp, access.Field());
return TCExpression(new_e, field_type, res.types);
}
}
FATAL_COMPILATION_ERROR(access.SourceLoc())
FATAL_COMPILATION_ERROR(access.source_loc())
<< "struct " << struct_type << " does not have a field named "
<< access.Field();
}
@@ -407,7 +413,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (auto& field : t_class.Fields()) {
if (access.Field() == field.first) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
return TCExpression(new_e, field.second, res.types);
}
}
@@ -415,11 +421,11 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (auto& method : t_class.Methods()) {
if (access.Field() == method.first) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
return TCExpression(new_e, method.second, res.types);
}
}
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "class " << t_class.Name() << " does not have a field named "
<< access.Field();
}
@@ -428,11 +434,11 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (const TupleElement& field : tup.Elements()) {
if (access.Field() == field.name) {
auto new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
return TCExpression(new_e, field.value, res.types);
}
}
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "tuple " << tup << " does not have a field named "
<< access.Field();
}
@@ -441,18 +447,18 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (const auto& vt : choice.Alternatives()) {
if (access.Field() == vt.first) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
auto fun_ty = arena->New<FunctionType>(
std::vector<GenericBinding>(), vt.second, t);
return TCExpression(new_e, fun_ty, res.types);
}
}
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "choice " << choice.Name() << " does not have a field named "
<< access.Field();
}
default:
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "field access, expected a struct\n"
<< *e;
}
@@ -463,7 +469,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
if (type) {
return TCExpression(e, *type, types);
} else {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "could not find `" << ident.Name() << "`";
}
}
@@ -483,49 +489,49 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
ts.push_back(res.type);
}
auto new_e =
arena->New<PrimitiveOperatorExpression>(e->SourceLoc(), op.Op(), es);
arena->New<PrimitiveOperatorExpression>(e->source_loc(), op.Op(), es);
switch (op.Op()) {
case Operator::Neg:
ExpectType(e->SourceLoc(), "negation", arena->New<IntType>(), ts[0]);
ExpectType(e->source_loc(), "negation", arena->New<IntType>(), ts[0]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::Add:
ExpectType(e->SourceLoc(), "addition(1)", arena->New<IntType>(),
ExpectType(e->source_loc(), "addition(1)", arena->New<IntType>(),
ts[0]);
ExpectType(e->SourceLoc(), "addition(2)", arena->New<IntType>(),
ExpectType(e->source_loc(), "addition(2)", arena->New<IntType>(),
ts[1]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::Sub:
ExpectType(e->SourceLoc(), "subtraction(1)", arena->New<IntType>(),
ExpectType(e->source_loc(), "subtraction(1)", arena->New<IntType>(),
ts[0]);
ExpectType(e->SourceLoc(), "subtraction(2)", arena->New<IntType>(),
ExpectType(e->source_loc(), "subtraction(2)", arena->New<IntType>(),
ts[1]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::Mul:
ExpectType(e->SourceLoc(), "multiplication(1)", arena->New<IntType>(),
ts[0]);
ExpectType(e->SourceLoc(), "multiplication(2)", arena->New<IntType>(),
ts[1]);
ExpectType(e->source_loc(), "multiplication(1)",
arena->New<IntType>(), ts[0]);
ExpectType(e->source_loc(), "multiplication(2)",
arena->New<IntType>(), ts[1]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::And:
ExpectType(e->SourceLoc(), "&&(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->SourceLoc(), "&&(2)", arena->New<BoolType>(), ts[1]);
ExpectType(e->source_loc(), "&&(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->source_loc(), "&&(2)", arena->New<BoolType>(), ts[1]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Or:
ExpectType(e->SourceLoc(), "||(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->SourceLoc(), "||(2)", arena->New<BoolType>(), ts[1]);
ExpectType(e->source_loc(), "||(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->source_loc(), "||(2)", arena->New<BoolType>(), ts[1]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Not:
ExpectType(e->SourceLoc(), "!", arena->New<BoolType>(), ts[0]);
ExpectType(e->source_loc(), "!", arena->New<BoolType>(), ts[0]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Eq:
ExpectType(e->SourceLoc(), "==", ts[0], ts[1]);
ExpectType(e->source_loc(), "==", ts[0], ts[1]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Deref:
ExpectPointerType(e->SourceLoc(), "*", ts[0]);
ExpectPointerType(e->source_loc(), "*", ts[0]);
return TCExpression(new_e, cast<PointerType>(*ts[0]).Type(),
new_types);
case Operator::Ptr:
ExpectType(e->SourceLoc(), "*", arena->New<TypeType>(), ts[0]);
ExpectType(e->source_loc(), "*", arena->New<TypeType>(), ts[0]);
return TCExpression(new_e, arena->New<TypeType>(), new_types);
}
break;
@@ -533,7 +539,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
case Expression::Kind::CallExpression: {
auto& call = cast<CallExpression>(*e);
auto fun_res = TypeCheckExp(call.Function(), types, values);
switch (fun_res.type->Tag()) {
switch (fun_res.type->kind()) {
case Value::Kind::FunctionType: {
const auto& fun_t = cast<FunctionType>(*fun_res.type);
auto arg_res = TypeCheckExp(call.Argument(), fun_res.types, values);
@@ -541,12 +547,12 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
auto return_type = fun_t.Ret();
if (!fun_t.Deduced().empty()) {
auto deduced_args = ArgumentDeduction(
e->SourceLoc(), TypeEnv(arena), parameter_type, arg_res.type);
e->source_loc(), TypeEnv(arena), parameter_type, arg_res.type);
for (auto& deduced_param : fun_t.Deduced()) {
// TODO: change the following to a CHECK once the real checking
// has been added to the type checking of function signatures.
if (!deduced_args.Get(deduced_param.name)) {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "could not deduce type argument for type parameter "
<< deduced_param.name;
}
@@ -554,14 +560,14 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
parameter_type = Substitute(deduced_args, parameter_type);
return_type = Substitute(deduced_args, return_type);
} else {
ExpectType(e->SourceLoc(), "call", parameter_type, arg_res.type);
ExpectType(e->source_loc(), "call", parameter_type, arg_res.type);
}
auto new_e = arena->New<CallExpression>(e->SourceLoc(), fun_res.exp,
auto new_e = arena->New<CallExpression>(e->source_loc(), fun_res.exp,
arg_res.exp);
return TCExpression(new_e, return_type, arg_res.types);
}
default: {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "in call, expected a function\n"
<< *e;
}
@@ -573,8 +579,8 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
auto pt = interpreter.InterpExp(values, fn.Parameter());
auto rt = interpreter.InterpExp(values, fn.ReturnType());
auto new_e = arena->New<FunctionTypeLiteral>(
e->SourceLoc(), ReifyType(pt, e->SourceLoc()),
ReifyType(rt, e->SourceLoc()),
e->source_loc(), ReifyType(pt, e->source_loc()),
ReifyType(rt, e->source_loc()),
/*is_omitted_return_type=*/false);
return TCExpression(new_e, arena->New<TypeType>(), types);
}
@@ -608,7 +614,7 @@ auto TypeChecker::TypeCheckPattern(
interpreter.PrintEnv(values, llvm::outs());
llvm::outs() << "\n";
}
switch (p->Tag()) {
switch (p->kind()) {
case Pattern::Kind::AutoPattern: {
return {.pattern = p, .type = arena->New<TypeType>(), .types = types};
}
@@ -620,9 +626,9 @@ auto TypeChecker::TypeCheckPattern(
interpreter.InterpPattern(values, binding_type_result.pattern);
if (expected) {
std::optional<Env> values = interpreter.PatternMatch(
type, *expected, binding.Type()->SourceLoc());
type, *expected, binding.Type()->source_loc());
if (values == std::nullopt) {
FATAL_COMPILATION_ERROR(binding.Type()->SourceLoc())
FATAL_COMPILATION_ERROR(binding.Type()->source_loc())
<< "Type pattern '" << *type << "' does not match actual type '"
<< **expected << "'";
}
@@ -631,8 +637,8 @@ auto TypeChecker::TypeCheckPattern(
type = *expected;
}
auto new_p = arena->New<BindingPattern>(
binding.SourceLoc(), binding.Name(),
arena->New<ExpressionPattern>(ReifyType(type, binding.SourceLoc())));
binding.source_loc(), binding.Name(),
arena->New<ExpressionPattern>(ReifyType(type, binding.source_loc())));
if (binding.Name().has_value()) {
types.Set(*binding.Name(), type);
}
@@ -643,12 +649,12 @@ auto TypeChecker::TypeCheckPattern(
std::vector<TuplePattern::Field> new_fields;
std::vector<TupleElement> field_types;
auto new_types = types;
if (expected && (*expected)->Tag() != Value::Kind::TupleValue) {
FATAL_COMPILATION_ERROR(p->SourceLoc()) << "didn't expect a tuple";
if (expected && (*expected)->kind() != Value::Kind::TupleValue) {
FATAL_COMPILATION_ERROR(p->source_loc()) << "didn't expect a tuple";
}
if (expected && tuple.Fields().size() !=
cast<TupleValue>(**expected).Elements().size()) {
FATAL_COMPILATION_ERROR(tuple.SourceLoc())
FATAL_COMPILATION_ERROR(tuple.source_loc())
<< "tuples of different length";
}
for (size_t i = 0; i < tuple.Fields().size(); ++i) {
@@ -658,7 +664,7 @@ auto TypeChecker::TypeCheckPattern(
const TupleElement& expected_element =
cast<TupleValue>(**expected).Elements()[i];
if (expected_element.name != field.name) {
FATAL_COMPILATION_ERROR(tuple.SourceLoc())
FATAL_COMPILATION_ERROR(tuple.source_loc())
<< "field names do not match, expected "
<< expected_element.name << " but got " << field.name;
}
@@ -671,7 +677,7 @@ auto TypeChecker::TypeCheckPattern(
TuplePattern::Field(field.name, field_result.pattern));
field_types.push_back({.name = field.name, .value = field_result.type});
}
auto new_tuple = arena->New<TuplePattern>(tuple.SourceLoc(), new_fields);
auto new_tuple = arena->New<TuplePattern>(tuple.source_loc(), new_fields);
auto tuple_t = arena->New<TupleValue>(std::move(field_types));
return {.pattern = new_tuple, .type = tuple_t, .types = new_types};
}
@@ -679,19 +685,19 @@ auto TypeChecker::TypeCheckPattern(
auto& alternative = cast<AlternativePattern>(*p);
Nonnull<const Value*> choice_type =
interpreter.InterpExp(values, alternative.ChoiceType());
if (choice_type->Tag() != Value::Kind::ChoiceType) {
FATAL_COMPILATION_ERROR(alternative.SourceLoc())
if (choice_type->kind() != Value::Kind::ChoiceType) {
FATAL_COMPILATION_ERROR(alternative.source_loc())
<< "alternative pattern does not name a choice type.";
}
if (expected) {
ExpectType(alternative.SourceLoc(), "alternative pattern", *expected,
ExpectType(alternative.source_loc(), "alternative pattern", *expected,
choice_type);
}
std::optional<Nonnull<const Value*>> parameter_types =
FindInVarValues(alternative.AlternativeName(),
cast<ChoiceType>(*choice_type).Alternatives());
if (parameter_types == std::nullopt) {
FATAL_COMPILATION_ERROR(alternative.SourceLoc())
FATAL_COMPILATION_ERROR(alternative.source_loc())
<< "'" << alternative.AlternativeName()
<< "' is not an alternative of " << *choice_type;
}
@@ -702,8 +708,8 @@ auto TypeChecker::TypeCheckPattern(
auto arguments =
Nonnull<TuplePattern*>(cast<const TuplePattern>(arg_results.pattern));
return {.pattern = arena->New<AlternativePattern>(
alternative.SourceLoc(),
ReifyType(choice_type, alternative.SourceLoc()),
alternative.source_loc(),
ReifyType(choice_type, alternative.source_loc()),
alternative.AlternativeName(), arguments),
.type = choice_type,
.types = arg_results.types};
@@ -732,7 +738,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
Env values,
Nonnull<ReturnTypeContext*> return_type_context)
-> TCStatement {
switch (s->Tag()) {
switch (s->kind()) {
case Statement::Kind::Match: {
auto& match = cast<Match>(*s);
auto res = TypeCheckExp(&match.expression(), types, values);
@@ -743,18 +749,18 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
&clause.statement(), types, values,
return_type_context));
}
auto new_s = arena->New<Match>(s->SourceLoc(), res.exp, new_clauses);
auto new_s = arena->New<Match>(s->source_loc(), res.exp, new_clauses);
return TCStatement(new_s, types);
}
case Statement::Kind::While: {
auto& while_stmt = cast<While>(*s);
auto cnd_res = TypeCheckExp(while_stmt.Cond(), types, values);
ExpectType(s->SourceLoc(), "condition of `while`", arena->New<BoolType>(),
cnd_res.type);
ExpectType(s->source_loc(), "condition of `while`",
arena->New<BoolType>(), cnd_res.type);
auto body_res =
TypeCheckStmt(while_stmt.Body(), types, values, return_type_context);
auto new_s =
arena->New<While>(s->SourceLoc(), cnd_res.exp, body_res.stmt);
arena->New<While>(s->source_loc(), cnd_res.exp, body_res.stmt);
return TCStatement(new_s, types);
}
case Statement::Kind::Break:
@@ -765,7 +771,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
if (block.Stmt()) {
auto stmt_res =
TypeCheckStmt(*block.Stmt(), types, values, return_type_context);
return TCStatement(arena->New<Block>(s->SourceLoc(), stmt_res.stmt),
return TCStatement(arena->New<Block>(s->source_loc(), stmt_res.stmt),
types);
} else {
return TCStatement(s, types);
@@ -777,7 +783,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
Nonnull<const Value*> rhs_ty = res.type;
auto lhs_res = TypeCheckPattern(var.Pat(), types, values, rhs_ty);
auto new_s =
arena->New<VariableDefinition>(s->SourceLoc(), var.Pat(), res.exp);
arena->New<VariableDefinition>(s->source_loc(), var.Pat(), res.exp);
return TCStatement(new_s, lhs_res.types);
}
case Statement::Kind::Sequence: {
@@ -793,7 +799,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
checked_types = next_res.types;
}
return TCStatement(
arena->New<Sequence>(s->SourceLoc(), stmt_res.stmt, next_stmt),
arena->New<Sequence>(s->source_loc(), stmt_res.stmt, next_stmt),
checked_types);
}
case Statement::Kind::Assign: {
@@ -802,20 +808,21 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
auto rhs_t = rhs_res.type;
auto lhs_res = TypeCheckExp(assign.Lhs(), types, values);
auto lhs_t = lhs_res.type;
ExpectType(s->SourceLoc(), "assign", lhs_t, rhs_t);
auto new_s = arena->New<Assign>(s->SourceLoc(), lhs_res.exp, rhs_res.exp);
ExpectType(s->source_loc(), "assign", lhs_t, rhs_t);
auto new_s =
arena->New<Assign>(s->source_loc(), lhs_res.exp, rhs_res.exp);
return TCStatement(new_s, lhs_res.types);
}
case Statement::Kind::ExpressionStatement: {
auto res =
TypeCheckExp(cast<ExpressionStatement>(*s).Exp(), types, values);
auto new_s = arena->New<ExpressionStatement>(s->SourceLoc(), res.exp);
auto new_s = arena->New<ExpressionStatement>(s->source_loc(), res.exp);
return TCStatement(new_s, types);
}
case Statement::Kind::If: {
auto& if_stmt = cast<If>(*s);
auto cnd_res = TypeCheckExp(if_stmt.Cond(), types, values);
ExpectType(s->SourceLoc(), "condition of `if`", arena->New<BoolType>(),
ExpectType(s->source_loc(), "condition of `if`", arena->New<BoolType>(),
cnd_res.type);
auto then_res =
TypeCheckStmt(if_stmt.ThenStmt(), types, values, return_type_context);
@@ -825,8 +832,8 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
return_type_context);
else_stmt = else_res.stmt;
}
auto new_s =
arena->New<If>(s->SourceLoc(), cnd_res.exp, then_res.stmt, else_stmt);
auto new_s = arena->New<If>(s->source_loc(), cnd_res.exp, then_res.stmt,
else_stmt);
return TCStatement(new_s, types);
}
case Statement::Kind::Return: {
@@ -835,7 +842,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
if (return_type_context->is_auto()) {
if (return_type_context->deduced_return_type()) {
// Only one return is allowed when the return type is `auto`.
FATAL_COMPILATION_ERROR(s->SourceLoc())
FATAL_COMPILATION_ERROR(s->source_loc())
<< "Only one return is allowed in a function with an `auto` "
"return type.";
} else {
@@ -843,17 +850,17 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
return_type_context->set_deduced_return_type(res.type);
}
} else {
ExpectType(s->SourceLoc(), "return",
ExpectType(s->source_loc(), "return",
*return_type_context->deduced_return_type(), res.type);
}
if (ret.IsOmittedExp() != return_type_context->is_omitted()) {
FATAL_COMPILATION_ERROR(s->SourceLoc())
FATAL_COMPILATION_ERROR(s->source_loc())
<< *s << " should"
<< (return_type_context->is_omitted() ? " not" : "")
<< " provide a return value, to match the function's signature.";
}
return TCStatement(
arena->New<Return>(s->SourceLoc(), res.exp, ret.IsOmittedExp()),
arena->New<Return>(s->source_loc(), res.exp, ret.IsOmittedExp()),
types);
}
case Statement::Kind::Continuation: {
@@ -861,16 +868,16 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
TCStatement body_result =
TypeCheckStmt(cont.Body(), types, values, return_type_context);
auto new_continuation = arena->New<Continuation>(
s->SourceLoc(), cont.ContinuationVariable(), body_result.stmt);
s->source_loc(), cont.ContinuationVariable(), body_result.stmt);
types.Set(cont.ContinuationVariable(), arena->New<ContinuationType>());
return TCStatement(new_continuation, types);
}
case Statement::Kind::Run: {
TCExpression argument_result =
TypeCheckExp(cast<Run>(*s).Argument(), types, values);
ExpectType(s->SourceLoc(), "argument of `run`",
ExpectType(s->source_loc(), "argument of `run`",
arena->New<ContinuationType>(), argument_result.type);
auto new_run = arena->New<Run>(s->SourceLoc(), argument_result.exp);
auto new_run = arena->New<Run>(s->source_loc(), argument_result.exp);
return TCStatement(new_run, types);
}
case Statement::Kind::Await: {
@@ -882,42 +889,42 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
auto TypeChecker::CheckOrEnsureReturn(
std::optional<Nonnull<Statement*>> opt_stmt, bool omitted_ret_type,
SourceLocation loc) -> Nonnull<Statement*> {
SourceLocation source_loc) -> Nonnull<Statement*> {
if (!opt_stmt) {
if (omitted_ret_type) {
return arena->New<Return>(arena, loc);
return arena->New<Return>(arena, source_loc);
} else {
FATAL_COMPILATION_ERROR(loc)
FATAL_COMPILATION_ERROR(source_loc)
<< "control-flow reaches end of function that provides a `->` return "
"type without reaching a return statement";
}
}
Nonnull<Statement*> stmt = *opt_stmt;
switch (stmt->Tag()) {
switch (stmt->kind()) {
case Statement::Kind::Match: {
auto& match = cast<Match>(*stmt);
std::vector<Match::Clause> new_clauses;
for (auto& clause : match.clauses()) {
auto s = CheckOrEnsureReturn(&clause.statement(), omitted_ret_type,
stmt->SourceLoc());
stmt->source_loc());
new_clauses.push_back(Match::Clause(&clause.pattern(), s));
}
return arena->New<Match>(stmt->SourceLoc(), &match.expression(),
return arena->New<Match>(stmt->source_loc(), &match.expression(),
new_clauses);
}
case Statement::Kind::Block:
return arena->New<Block>(
stmt->SourceLoc(),
stmt->source_loc(),
CheckOrEnsureReturn(cast<Block>(*stmt).Stmt(), omitted_ret_type,
stmt->SourceLoc()));
stmt->source_loc()));
case Statement::Kind::If: {
auto& if_stmt = cast<If>(*stmt);
return arena->New<If>(
stmt->SourceLoc(), if_stmt.Cond(),
stmt->source_loc(), if_stmt.Cond(),
CheckOrEnsureReturn(if_stmt.ThenStmt(), omitted_ret_type,
stmt->SourceLoc()),
stmt->source_loc()),
CheckOrEnsureReturn(if_stmt.ElseStmt(), omitted_ret_type,
stmt->SourceLoc()));
stmt->source_loc()));
}
case Statement::Kind::Return:
return stmt;
@@ -925,12 +932,12 @@ auto TypeChecker::CheckOrEnsureReturn(
auto& seq = cast<Sequence>(*stmt);
if (seq.Next()) {
return arena->New<Sequence>(
stmt->SourceLoc(), seq.Stmt(),
stmt->source_loc(), seq.Stmt(),
CheckOrEnsureReturn(seq.Next(), omitted_ret_type,
stmt->SourceLoc()));
stmt->source_loc()));
} else {
return CheckOrEnsureReturn(seq.Stmt(), omitted_ret_type,
stmt->SourceLoc());
stmt->source_loc());
}
}
case Statement::Kind::Continuation:
@@ -944,10 +951,10 @@ auto TypeChecker::CheckOrEnsureReturn(
case Statement::Kind::Continue:
case Statement::Kind::VariableDefinition:
if (omitted_ret_type) {
return arena->New<Sequence>(stmt->SourceLoc(), stmt,
arena->New<Return>(arena, loc));
return arena->New<Sequence>(stmt->source_loc(), stmt,
arena->New<Return>(arena, source_loc));
} else {
FATAL_COMPILATION_ERROR(stmt->SourceLoc())
FATAL_COMPILATION_ERROR(stmt->source_loc())
<< "control-flow reaches end of function that provides a `->` "
"return type without reaching a return statement";
}
@@ -1010,7 +1017,7 @@ auto TypeChecker::TypeOfFunDef(TypeEnv types, Env values,
TypeCheckPattern(&fun_def->param_pattern(), types, values, std::nullopt);
// Evaluate the return type expression
auto ret = interpreter.InterpPattern(values, &fun_def->return_type());
if (ret->Tag() == Value::Kind::AutoType) {
if (ret->kind() == Value::Kind::AutoType) {
auto f = TypeCheckFunDef(fun_def, types, values);
ret = interpreter.InterpPattern(values, &f->return_type());
}
@@ -1023,17 +1030,17 @@ auto TypeChecker::TypeOfClassDef(const ClassDefinition* sd, TypeEnv /*types*/,
VarValues fields;
VarValues methods;
for (Nonnull<const Member*> m : sd->members()) {
switch (m->Tag()) {
switch (m->kind()) {
case Member::Kind::FieldMember: {
Nonnull<const BindingPattern*> binding =
cast<FieldMember>(*m).Binding();
if (!binding->Name().has_value()) {
FATAL_COMPILATION_ERROR(binding->SourceLoc())
FATAL_COMPILATION_ERROR(binding->source_loc())
<< "Struct members must have names";
}
const auto* binding_type = dyn_cast<ExpressionPattern>(binding->Type());
if (binding_type == nullptr) {
FATAL_COMPILATION_ERROR(binding->SourceLoc())
FATAL_COMPILATION_ERROR(binding->source_loc())
<< "Struct members must have explicit types";
}
auto type = interpreter.InterpExp(ct_top, binding_type->Expression());
@@ -1057,7 +1064,7 @@ static auto GetName(const Declaration& d) -> const std::string& {
case Declaration::Kind::VariableDeclaration: {
const BindingPattern& binding = cast<VariableDeclaration>(d).binding();
if (!binding.Name().has_value()) {
FATAL_COMPILATION_ERROR(binding.SourceLoc())
FATAL_COMPILATION_ERROR(binding.source_loc())
<< "Top-level variable declarations must have names";
}
return *binding.Name();
@@ -1077,7 +1084,7 @@ auto TypeChecker::MakeTypeChecked(Nonnull<Declaration*> d, const TypeEnv& types,
cast<ClassDeclaration>(*d).definition();
std::vector<Nonnull<Member*>> fields;
for (Nonnull<Member*> m : class_def.members()) {
switch (m->Tag()) {
switch (m->kind()) {
case Member::Kind::FieldMember:
// TODO: Interpret the type expression and store the result.
fields.push_back(m);
@@ -140,11 +140,11 @@ class TypeChecker {
void TopLevel(Nonnull<Declaration*> d, TypeCheckContext* tops);
auto CheckOrEnsureReturn(std::optional<Nonnull<Statement*>> opt_stmt,
bool omitted_ret_type, SourceLocation loc)
bool omitted_ret_type, SourceLocation source_loc)
-> Nonnull<Statement*>;
// Reify type to type expression.
auto ReifyType(Nonnull<const Value*> t, SourceLocation loc)
auto ReifyType(Nonnull<const Value*> t, SourceLocation source_loc)
-> Nonnull<Expression*>;
auto Substitute(TypeEnv dict, Nonnull<const Value*> type)
+43 -40
View File
@@ -67,14 +67,14 @@ auto TupleValue::FindField(const std::string& name) const
namespace {
auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
const std::string& f, SourceLocation loc)
const std::string& f, SourceLocation source_loc)
-> Nonnull<const Value*> {
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::StructValue: {
std::optional<Nonnull<const Value*>> field =
cast<StructValue>(*v).FindField(f);
if (field == std::nullopt) {
FATAL_RUNTIME_ERROR(loc) << "member " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc) << "member " << f << " not in " << *v;
}
return *field;
}
@@ -82,7 +82,7 @@ auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
std::optional<Nonnull<const Value*>> field =
cast<TupleValue>(*cast<NominalClassValue>(*v).Inits()).FindField(f);
if (field == std::nullopt) {
FATAL_RUNTIME_ERROR(loc) << "member " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc) << "member " << f << " not in " << *v;
}
return *field;
}
@@ -90,14 +90,15 @@ auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
std::optional<Nonnull<const Value*>> field =
cast<TupleValue>(*v).FindField(f);
if (!field) {
FATAL_RUNTIME_ERROR(loc) << "field " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc) << "field " << f << " not in " << *v;
}
return *field;
}
case Value::Kind::ChoiceType: {
const auto& choice = cast<ChoiceType>(*v);
if (!FindInVarValues(f, choice.Alternatives())) {
FATAL_RUNTIME_ERROR(loc) << "alternative " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc)
<< "alternative " << f << " not in " << *v;
}
return arena->New<AlternativeConstructorValue>(f, choice.Name());
}
@@ -109,10 +110,10 @@ auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
} // namespace
auto Value::GetField(Nonnull<Arena*> arena, const FieldPath& path,
SourceLocation loc) const -> Nonnull<const Value*> {
SourceLocation source_loc) const -> Nonnull<const Value*> {
Nonnull<const Value*> value(this);
for (const std::string& field : path.components) {
value = GetMember(arena, value, field, loc);
value = GetMember(arena, value, field, source_loc);
}
return value;
}
@@ -122,12 +123,12 @@ namespace {
auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
std::vector<std::string>::const_iterator path_begin,
std::vector<std::string>::const_iterator path_end,
Nonnull<const Value*> field_value, SourceLocation loc)
Nonnull<const Value*> field_value, SourceLocation source_loc)
-> Nonnull<const Value*> {
if (path_begin == path_end) {
return field_value;
}
switch (value->Tag()) {
switch (value->kind()) {
case Value::Kind::StructValue: {
std::vector<TupleElement> elements = cast<StructValue>(*value).elements();
auto it = std::find_if(elements.begin(), elements.end(),
@@ -135,16 +136,16 @@ auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
return element.name == *path_begin;
});
if (it == elements.end()) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "field " << *path_begin << " not in " << *value;
}
it->value = SetFieldImpl(arena, it->value, path_begin + 1, path_end,
field_value, loc);
field_value, source_loc);
return arena->New<StructValue>(elements);
}
case Value::Kind::NominalClassValue: {
return SetFieldImpl(arena, cast<NominalClassValue>(*value).Inits(),
path_begin, path_end, field_value, loc);
path_begin, path_end, field_value, source_loc);
}
case Value::Kind::TupleValue: {
std::vector<TupleElement> elements = cast<TupleValue>(*value).Elements();
@@ -153,11 +154,11 @@ auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
return element.name == *path_begin;
});
if (it == elements.end()) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "field " << *path_begin << " not in " << *value;
}
it->value = SetFieldImpl(arena, it->value, path_begin + 1, path_end,
field_value, loc);
field_value, source_loc);
return arena->New<TupleValue>(elements);
}
default:
@@ -169,14 +170,14 @@ auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
auto Value::SetField(Nonnull<Arena*> arena, const FieldPath& path,
Nonnull<const Value*> field_value,
SourceLocation loc) const -> Nonnull<const Value*> {
SourceLocation source_loc) const -> Nonnull<const Value*> {
return SetFieldImpl(arena, Nonnull<const Value*>(this),
path.components.begin(), path.components.end(),
field_value, loc);
field_value, source_loc);
}
void Value::Print(llvm::raw_ostream& out) const {
switch (Tag()) {
switch (kind()) {
case Value::Kind::AlternativeConstructorValue: {
const auto& alt = cast<AlternativeConstructorValue>(*this);
out << alt.ChoiceName() << "." << alt.AltName();
@@ -309,32 +310,34 @@ void Value::Print(llvm::raw_ostream& out) const {
}
auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
SourceLocation loc) -> Nonnull<const Value*> {
switch (val->Tag()) {
SourceLocation source_loc) -> Nonnull<const Value*> {
switch (val->kind()) {
case Value::Kind::TupleValue: {
std::vector<TupleElement> elements;
for (const TupleElement& element : cast<TupleValue>(*val).Elements()) {
elements.push_back({.name = element.name,
.value = CopyVal(arena, element.value, loc)});
elements.push_back(
{.name = element.name,
.value = CopyVal(arena, element.value, source_loc)});
}
return arena->New<TupleValue>(std::move(elements));
}
case Value::Kind::AlternativeValue: {
const auto& alt = cast<AlternativeValue>(*val);
Nonnull<const Value*> arg = CopyVal(arena, alt.Argument(), loc);
Nonnull<const Value*> arg = CopyVal(arena, alt.Argument(), source_loc);
return arena->New<AlternativeValue>(alt.AltName(), alt.ChoiceName(), arg);
}
case Value::Kind::StructValue: {
std::vector<TupleElement> elements;
for (const TupleElement& element : cast<StructValue>(*val).elements()) {
elements.push_back({.name = element.name,
.value = CopyVal(arena, element.value, loc)});
elements.push_back(
{.name = element.name,
.value = CopyVal(arena, element.value, source_loc)});
}
return arena->New<StructValue>(std::move(elements));
}
case Value::Kind::NominalClassValue: {
const auto& s = cast<NominalClassValue>(*val);
Nonnull<const Value*> inits = CopyVal(arena, s.Inits(), loc);
Nonnull<const Value*> inits = CopyVal(arena, s.Inits(), source_loc);
return arena->New<NominalClassValue>(s.Type(), inits);
}
case Value::Kind::IntValue:
@@ -353,13 +356,13 @@ auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
return val;
case Value::Kind::FunctionType: {
const auto& fn_type = cast<FunctionType>(*val);
return arena->New<FunctionType>(fn_type.Deduced(),
CopyVal(arena, fn_type.Param(), loc),
CopyVal(arena, fn_type.Ret(), loc));
return arena->New<FunctionType>(
fn_type.Deduced(), CopyVal(arena, fn_type.Param(), source_loc),
CopyVal(arena, fn_type.Ret(), source_loc));
}
case Value::Kind::PointerType:
return arena->New<PointerType>(
CopyVal(arena, cast<PointerType>(*val).Type(), loc));
CopyVal(arena, cast<PointerType>(*val).Type(), source_loc));
case Value::Kind::IntType:
return arena->New<IntType>();
case Value::Kind::BoolType:
@@ -377,7 +380,7 @@ auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
case Value::Kind::StructType: {
VarValues fields;
for (const auto& [name, type] : cast<StructType>(*val).fields()) {
fields.push_back({name, CopyVal(arena, type, loc)});
fields.push_back({name, CopyVal(arena, type, source_loc)});
}
return arena->New<StructType>(fields);
}
@@ -392,10 +395,10 @@ auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
}
auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool {
if (t1->Tag() != t2->Tag()) {
if (t1->kind() != t2->kind()) {
return false;
}
switch (t1->Tag()) {
switch (t1->kind()) {
case Value::Kind::PointerType:
return TypeEqual(cast<PointerType>(*t1).Type(),
cast<PointerType>(*t2).Type());
@@ -458,7 +461,7 @@ auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool {
// and returns false otherwise.
static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
const std::vector<TupleElement>& ts2,
SourceLocation loc) -> bool {
SourceLocation source_loc) -> bool {
if (ts1.size() != ts2.size()) {
return false;
}
@@ -469,7 +472,7 @@ static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
if (iter == ts2.end()) {
return false;
}
if (!ValueEqual(element.value, iter->value, loc)) {
if (!ValueEqual(element.value, iter->value, source_loc)) {
return false;
}
}
@@ -480,11 +483,11 @@ static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
//
// This function implements the `==` operator of Carbon.
auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2,
SourceLocation loc) -> bool {
if (v1->Tag() != v2->Tag()) {
SourceLocation source_loc) -> bool {
if (v1->kind() != v2->kind()) {
return false;
}
switch (v1->Tag()) {
switch (v1->kind()) {
case Value::Kind::IntValue:
return cast<IntValue>(*v1).Val() == cast<IntValue>(*v2).Val();
case Value::Kind::BoolValue:
@@ -501,10 +504,10 @@ auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2,
}
case Value::Kind::TupleValue:
return FieldsValueEqual(cast<TupleValue>(*v1).Elements(),
cast<TupleValue>(*v2).Elements(), loc);
cast<TupleValue>(*v2).Elements(), source_loc);
case Value::Kind::StructValue:
return FieldsValueEqual(cast<StructValue>(*v1).elements(),
cast<StructValue>(*v2).elements(), loc);
cast<StructValue>(*v2).elements(), source_loc);
case Value::Kind::StringValue:
return cast<StringValue>(*v1).Val() == cast<StringValue>(*v2).Val();
case Value::Kind::IntType:
+36 -36
View File
@@ -61,31 +61,31 @@ class Value {
Value(const Value&) = delete;
Value& operator=(const Value&) = delete;
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the sub-Value specified by `path`, which must be a valid field
// path for *this.
auto GetField(Nonnull<Arena*> arena, const FieldPath& path,
SourceLocation loc) const -> Nonnull<const Value*>;
SourceLocation source_loc) const -> Nonnull<const Value*>;
// Returns a copy of *this, but with the sub-Value specified by `path`
// set to `field_value`. `path` must be a valid field path for *this.
auto SetField(Nonnull<Arena*> arena, const FieldPath& path,
Nonnull<const Value*> field_value, SourceLocation loc) const
-> Nonnull<const Value*>;
Nonnull<const Value*> field_value,
SourceLocation source_loc) const -> Nonnull<const Value*>;
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto kind() const -> Kind { return kind_; }
protected:
// Constructs a Value. `tag` must be the enumerator corresponding to the
// Constructs a Value. `kind` must be the enumerator corresponding to the
// most-derived type being constructed.
explicit Value(Kind kind) : kind(kind) {}
explicit Value(Kind kind) : kind_(kind) {}
private:
const Kind kind;
const Kind kind_;
};
using VarValues = std::vector<std::pair<std::string, Nonnull<const Value*>>>;
@@ -115,7 +115,7 @@ class IntValue : public Value {
explicit IntValue(int val) : Value(Kind::IntValue), val(val) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::IntValue;
return value->kind() == Kind::IntValue;
}
auto Val() const -> int { return val; }
@@ -135,7 +135,7 @@ class FunctionValue : public Value {
body(body) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::FunctionValue;
return value->kind() == Kind::FunctionValue;
}
auto Name() const -> const std::string& { return name; }
@@ -155,7 +155,7 @@ class PointerValue : public Value {
: Value(Kind::PointerValue), val(std::move(val)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::PointerValue;
return value->kind() == Kind::PointerValue;
}
auto Val() const -> const Address& { return val; }
@@ -170,7 +170,7 @@ class BoolValue : public Value {
explicit BoolValue(bool val) : Value(Kind::BoolValue), val(val) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::BoolValue;
return value->kind() == Kind::BoolValue;
}
auto Val() const -> bool { return val; }
@@ -195,7 +195,7 @@ class StructValue : public Value {
}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StructValue;
return value->kind() == Kind::StructValue;
}
auto elements() const -> const std::vector<TupleElement>& {
@@ -218,7 +218,7 @@ class NominalClassValue : public Value {
: Value(Kind::NominalClassValue), type(type), inits(inits) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::NominalClassValue;
return value->kind() == Kind::NominalClassValue;
}
auto Type() const -> Nonnull<const Value*> { return type; }
@@ -238,7 +238,7 @@ class AlternativeConstructorValue : public Value {
choice_name(std::move(choice_name)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::AlternativeConstructorValue;
return value->kind() == Kind::AlternativeConstructorValue;
}
auto AltName() const -> const std::string& { return alt_name; }
@@ -260,7 +260,7 @@ class AlternativeValue : public Value {
argument(argument) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::AlternativeValue;
return value->kind() == Kind::AlternativeValue;
}
auto AltName() const -> const std::string& { return alt_name; }
@@ -286,7 +286,7 @@ class TupleValue : public Value {
: Value(Kind::TupleValue), elements(std::move(elements)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::TupleValue;
return value->kind() == Kind::TupleValue;
}
auto Elements() const -> const std::vector<TupleElement>& { return elements; }
@@ -311,7 +311,7 @@ class BindingPlaceholderValue : public Value {
type(type) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::BindingPlaceholderValue;
return value->kind() == Kind::BindingPlaceholderValue;
}
auto Name() const -> const std::optional<std::string>& { return name; }
@@ -328,7 +328,7 @@ class IntType : public Value {
IntType() : Value(Kind::IntType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::IntType;
return value->kind() == Kind::IntType;
}
};
@@ -338,7 +338,7 @@ class BoolType : public Value {
BoolType() : Value(Kind::BoolType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::BoolType;
return value->kind() == Kind::BoolType;
}
};
@@ -348,7 +348,7 @@ class TypeType : public Value {
TypeType() : Value(Kind::TypeType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::TypeType;
return value->kind() == Kind::TypeType;
}
};
@@ -363,7 +363,7 @@ class FunctionType : public Value {
ret(ret) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::FunctionType;
return value->kind() == Kind::FunctionType;
}
auto Deduced() const -> const std::vector<GenericBinding>& { return deduced; }
@@ -383,7 +383,7 @@ class PointerType : public Value {
: Value(Kind::PointerType), type(type) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::PointerType;
return value->kind() == Kind::PointerType;
}
auto Type() const -> Nonnull<const Value*> { return type; }
@@ -398,7 +398,7 @@ class AutoType : public Value {
AutoType() : Value(Kind::AutoType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::AutoType;
return value->kind() == Kind::AutoType;
}
};
@@ -414,7 +414,7 @@ class StructType : public Value {
: Value(Kind::StructType), fields_(std::move(fields)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StructType;
return value->kind() == Kind::StructType;
}
auto fields() const -> const VarValues& { return fields_; }
@@ -433,7 +433,7 @@ class NominalClassType : public Value {
methods(std::move(methods)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::NominalClassType;
return value->kind() == Kind::NominalClassType;
}
auto Name() const -> const std::string& { return name; }
@@ -455,7 +455,7 @@ class ChoiceType : public Value {
alternatives(std::move(alternatives)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::ChoiceType;
return value->kind() == Kind::ChoiceType;
}
auto Name() const -> const std::string& { return name; }
@@ -472,7 +472,7 @@ class ContinuationType : public Value {
ContinuationType() : Value(Kind::ContinuationType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::ContinuationType;
return value->kind() == Kind::ContinuationType;
}
};
@@ -483,7 +483,7 @@ class VariableType : public Value {
: Value(Kind::VariableType), name(std::move(name)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::VariableType;
return value->kind() == Kind::VariableType;
}
auto Name() const -> const std::string& { return name; }
@@ -499,7 +499,7 @@ class ContinuationValue : public Value {
: Value(Kind::ContinuationValue), stack(std::move(stack)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::ContinuationValue;
return value->kind() == Kind::ContinuationValue;
}
auto Stack() const -> const std::vector<Nonnull<Frame*>>& { return stack; }
@@ -514,7 +514,7 @@ class StringType : public Value {
StringType() : Value(Kind::StringType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StringType;
return value->kind() == Kind::StringType;
}
};
@@ -525,7 +525,7 @@ class StringValue : public Value {
: Value(Kind::StringValue), val(std::move(val)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StringValue;
return value->kind() == Kind::StringValue;
}
auto Val() const -> const std::string& { return val; }
@@ -535,11 +535,11 @@ class StringValue : public Value {
};
auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
SourceLocation loc) -> Nonnull<const Value*>;
SourceLocation source_loc) -> Nonnull<const Value*>;
auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool;
auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2,
SourceLocation loc) -> bool;
SourceLocation source_loc) -> bool;
} // namespace Carbon