Replace int lines with file-associated SourceLocations (#779)

Most interesting changes should be ast/source_location.h and syntax/parse_and_lex_context.h
This commit is contained in:
Jon Meow
2021-08-26 10:07:16 -07:00
committed by GitHub
parent 33daf64329
commit 3ec550a85f
46 changed files with 607 additions and 518 deletions
+9 -9
View File
@@ -21,21 +21,21 @@ auto Heap::AllocateValue(const Value* v) -> Address {
return a;
}
auto Heap::Read(const Address& a, int line_num) -> const Value* {
this->CheckAlive(a, line_num);
return values_[a.index]->GetField(a.field_path, line_num);
auto Heap::Read(const Address& a, SourceLocation loc) -> const Value* {
this->CheckAlive(a, loc);
return values_[a.index]->GetField(a.field_path, loc);
}
void Heap::Write(const Address& a, const Value* v, int line_num) {
void Heap::Write(const Address& a, const Value* v, SourceLocation loc) {
CHECK(v != nullptr);
this->CheckAlive(a, line_num);
values_[a.index] = values_[a.index]->SetField(a.field_path, v, line_num);
this->CheckAlive(a, loc);
values_[a.index] = values_[a.index]->SetField(a.field_path, v, loc);
}
void Heap::CheckAlive(const Address& address, int line_num) {
void Heap::CheckAlive(const Address& address, SourceLocation loc) {
if (!alive_[address.index]) {
FATAL_RUNTIME_ERROR(line_num) << "undefined behavior: access to dead value "
<< *values_[address.index];
FATAL_RUNTIME_ERROR(loc) << "undefined behavior: access to dead value "
<< *values_[address.index];
}
}
+3 -3
View File
@@ -25,11 +25,11 @@ class Heap {
// Returns the value at the given address in the heap after
// checking that it is alive.
auto Read(const Address& a, int line_num) -> const Value*;
auto Read(const Address& a, SourceLocation loc) -> const Value*;
// Writes the given value at the address in the heap after
// checking that the address is alive.
void Write(const Address& a, const Value* v, int line_num);
void Write(const Address& a, const Value* v, SourceLocation loc);
// Put the given value on the heap and mark it as alive.
auto AllocateValue(const Value* v) -> Address;
@@ -47,7 +47,7 @@ class Heap {
private:
// Signal an error if the address is no longer alive.
void CheckAlive(const Address& address, int line_num);
void CheckAlive(const Address& address, SourceLocation loc);
std::vector<const Value*> values_;
std::vector<bool> alive_;
@@ -62,10 +62,10 @@ auto CurrentEnv(State* state) -> Env {
}
// Returns the given name from the environment, printing an error if not found.
static auto GetFromEnv(int line_num, const std::string& name) -> Address {
static auto GetFromEnv(SourceLocation loc, const std::string& name) -> Address {
std::optional<Address> pointer = CurrentEnv(state).Get(name);
if (!pointer) {
FATAL_RUNTIME_ERROR(line_num) << "could not find `" << name << "`";
FATAL_RUNTIME_ERROR(loc) << "could not find `" << name << "`";
}
return *pointer;
}
@@ -81,8 +81,8 @@ void PrintState(llvm::raw_ostream& out) {
out << "\n}\n";
}
auto EvalPrim(Operator op, const std::vector<const Value*>& args, int line_num)
-> const Value* {
auto EvalPrim(Operator op, const std::vector<const Value*>& args,
SourceLocation loc) -> const Value* {
switch (op) {
case Operator::Neg:
return global_arena->RawNew<IntValue>(-cast<IntValue>(*args[0]).Val());
@@ -104,8 +104,7 @@ auto EvalPrim(Operator op, const std::vector<const Value*>& args, int line_num)
return global_arena->RawNew<BoolValue>(cast<BoolValue>(*args[0]).Val() ||
cast<BoolValue>(*args[1]).Val());
case Operator::Eq:
return global_arena->RawNew<BoolValue>(
ValueEqual(args[0], args[1], line_num));
return global_arena->RawNew<BoolValue>(ValueEqual(args[0], args[1], loc));
case Operator::Ptr:
return global_arena->RawNew<PointerType>(args[0]);
case Operator::Deref:
@@ -220,14 +219,14 @@ const Value* CreateTuple(Ptr<Action> act, const Expression* exp) {
return global_arena->RawNew<TupleValue>(std::move(elements));
}
auto PatternMatch(const Value* p, const Value* v, int line_num)
auto PatternMatch(const Value* p, const Value* v, SourceLocation loc)
-> std::optional<Env> {
switch (p->Tag()) {
case Value::Kind::BindingPlaceholderValue: {
const auto& placeholder = cast<BindingPlaceholderValue>(*p);
Env values;
if (placeholder.Name().has_value()) {
Address a = state->heap.AllocateValue(CopyVal(v, line_num));
Address a = state->heap.AllocateValue(CopyVal(v, loc));
values.Set(*placeholder.Name(), a);
}
return values;
@@ -238,20 +237,20 @@ auto PatternMatch(const Value* p, const Value* v, int line_num)
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(line_num)
FATAL_PROGRAM_ERROR(loc)
<< "arity mismatch in tuple pattern match:\n pattern: "
<< p_tup << "\n value: " << v_tup;
}
Env values;
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(line_num)
FATAL_PROGRAM_ERROR(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, line_num);
p_tup.Elements()[i].value, v_tup.Elements()[i].value, loc);
if (!matches) {
return std::nullopt;
}
@@ -273,7 +272,7 @@ auto PatternMatch(const Value* p, const Value* v, int line_num)
p_alt.AltName() != v_alt.AltName()) {
return std::nullopt;
}
return PatternMatch(p_alt.Argument(), v_alt.Argument(), line_num);
return PatternMatch(p_alt.Argument(), v_alt.Argument(), loc);
}
default:
FATAL() << "expected a choice alternative in pattern, not " << *v;
@@ -284,12 +283,12 @@ auto PatternMatch(const Value* p, const Value* v, int line_num)
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(), line_num);
PatternMatch(p_fn.Param(), v_fn.Param(), loc);
if (!param_matches) {
return std::nullopt;
}
std::optional<Env> ret_matches =
PatternMatch(p_fn.Ret(), v_fn.Ret(), line_num);
PatternMatch(p_fn.Ret(), v_fn.Ret(), loc);
if (!ret_matches) {
return std::nullopt;
}
@@ -307,7 +306,7 @@ auto PatternMatch(const Value* p, const Value* v, int line_num)
// on the typechecker to ensure that `v` is a type.
return Env();
default:
if (ValueEqual(p, v, line_num)) {
if (ValueEqual(p, v, loc)) {
return Env();
} else {
return std::nullopt;
@@ -315,11 +314,10 @@ auto PatternMatch(const Value* p, const Value* v, int line_num)
}
}
void PatternAssignment(const Value* pat, const Value* val, int line_num) {
void PatternAssignment(const Value* pat, const Value* val, SourceLocation loc) {
switch (pat->Tag()) {
case Value::Kind::PointerValue:
state->heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(val, line_num),
line_num);
state->heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(val, loc), loc);
break;
case Value::Kind::TupleValue: {
switch (val->Tag()) {
@@ -327,17 +325,17 @@ void PatternAssignment(const Value* pat, const Value* val, int line_num) {
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(line_num)
FATAL_RUNTIME_ERROR(loc)
<< "arity mismatch in tuple pattern assignment:\n pattern: "
<< pat_tup << "\n value: " << val_tup;
}
for (const TupleElement& pattern_element : pat_tup.Elements()) {
const Value* value_field = val_tup.FindField(pattern_element.name);
if (value_field == nullptr) {
FATAL_RUNTIME_ERROR(line_num)
FATAL_RUNTIME_ERROR(loc)
<< "field " << pattern_element.name << "not in " << *val;
}
PatternAssignment(pattern_element.value, value_field, line_num);
PatternAssignment(pattern_element.value, value_field, loc);
}
break;
}
@@ -354,7 +352,7 @@ void PatternAssignment(const Value* pat, const Value* val, int line_num) {
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(), line_num);
PatternAssignment(pat_alt.Argument(), val_alt.Argument(), loc);
break;
}
default:
@@ -363,7 +361,7 @@ void PatternAssignment(const Value* pat, const Value* val, int line_num) {
break;
}
default:
CHECK(ValueEqual(pat, val, line_num))
CHECK(ValueEqual(pat, val, loc))
<< "internal error in pattern assignment";
}
}
@@ -417,7 +415,7 @@ struct UnwindFunctionCall {
struct CallFunction {
const FunctionValue* function;
const Value* args;
int line_num;
SourceLocation loc;
};
// Transition type which does nothing.
@@ -441,8 +439,8 @@ Transition StepLvalue() {
case Expression::Kind::IdentifierExpression: {
// { {x :: C, E, F} :: S, H}
// -> { {E(x) :: C, E, F} :: S, H}
Address pointer = GetFromEnv(exp->LineNumber(),
cast<IdentifierExpression>(*exp).Name());
Address pointer =
GetFromEnv(exp->SourceLoc(), cast<IdentifierExpression>(*exp).Name());
const Value* v = global_arena->RawNew<PointerValue>(pointer);
return Done{v};
}
@@ -586,15 +584,15 @@ Transition StepExp() {
// { { v :: [].f :: C, E, F} :: S, H}
// -> { { v_f :: C, E, F} : S, H}
return Done{act->Results()[0]->GetField(FieldPath(access.Field()),
exp->LineNumber())};
exp->SourceLoc())};
}
}
case Expression::Kind::IdentifierExpression: {
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->LineNumber(), ident.Name());
return Done{state->heap.Read(pointer, exp->LineNumber())};
Address pointer = GetFromEnv(exp->SourceLoc(), ident.Name());
return Done{state->heap.Read(pointer, exp->SourceLoc())};
}
case Expression::Kind::IntLiteral:
CHECK(act->Pos() == 0);
@@ -615,7 +613,7 @@ Transition StepExp() {
} 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->LineNumber())};
return Done{EvalPrim(op.Op(), act->Results(), exp->SourceLoc())};
}
}
case Expression::Kind::CallExpression:
@@ -634,14 +632,14 @@ Transition StepExp() {
// -> { {C',E',F'} :: {C, E, F} :: S, H}
switch (act->Results()[0]->Tag()) {
case Value::Kind::ClassType: {
const Value* arg = CopyVal(act->Results()[1], exp->LineNumber());
const Value* arg = CopyVal(act->Results()[1], exp->SourceLoc());
return Done{
global_arena->RawNew<StructValue>(act->Results()[0], arg)};
}
case Value::Kind::AlternativeConstructorValue: {
const auto& alt =
cast<AlternativeConstructorValue>(*act->Results()[0]);
const Value* arg = CopyVal(act->Results()[1], exp->LineNumber());
const Value* arg = CopyVal(act->Results()[1], exp->SourceLoc());
return Done{global_arena->RawNew<AlternativeValue>(
alt.AltName(), alt.ChoiceName(), arg)};
}
@@ -649,9 +647,9 @@ Transition StepExp() {
return CallFunction{
.function = cast<FunctionValue>(act->Results()[0]),
.args = act->Results()[1],
.line_num = exp->LineNumber()};
.loc = exp->SourceLoc()};
default:
FATAL_RUNTIME_ERROR(exp->LineNumber())
FATAL_RUNTIME_ERROR(exp->SourceLoc())
<< "in call, expected a function, not " << *act->Results()[0];
}
} else {
@@ -662,8 +660,8 @@ Transition StepExp() {
// { {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->LineNumber(), "format_str");
const Value* pointee = state->heap.Read(pointer, exp->LineNumber());
Address pointer = GetFromEnv(exp->SourceLoc(), "format_str");
const Value* pointee = state->heap.Read(pointer, exp->SourceLoc());
CHECK(pointee->Tag() == Value::Kind::StringValue);
// TODO: This could eventually use something like llvm::formatv.
llvm::outs() << cast<StringValue>(*pointee).Val();
@@ -853,7 +851,7 @@ Transition StepStmt() {
} else { // try to match
auto v = act->Results()[0];
auto pat = act->Results()[clause_num + 1];
std::optional<Env> matches = PatternMatch(pat, v, stmt->LineNumber());
std::optional<Env> matches = PatternMatch(pat, v, stmt->SourceLoc());
if (matches) { // we have a match, start the body
Env values = CurrentEnv(state);
std::list<std::string> vars;
@@ -863,7 +861,7 @@ Transition StepStmt() {
}
frame->scopes.Push(global_arena->New<Scope>(values, vars));
const Statement* body_block =
global_arena->RawNew<Block>(stmt->LineNumber(), c->second);
global_arena->RawNew<Block>(stmt->SourceLoc(), c->second);
auto body_act = global_arena->New<StatementAction>(body_block);
body_act->IncrementPos();
frame->todo.Pop(1);
@@ -905,7 +903,7 @@ Transition StepStmt() {
auto it =
std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
if (it == frame->todo.end()) {
FATAL_RUNTIME_ERROR(stmt->LineNumber())
FATAL_RUNTIME_ERROR(stmt->SourceLoc())
<< "`break` not inside `while` statement";
}
++it;
@@ -918,7 +916,7 @@ Transition StepStmt() {
auto it =
std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
if (it == frame->todo.end()) {
FATAL_RUNTIME_ERROR(stmt->LineNumber())
FATAL_RUNTIME_ERROR(stmt->SourceLoc())
<< "`continue` not inside `while` statement";
}
return UnwindTo{*it};
@@ -954,9 +952,9 @@ Transition StepStmt() {
const Value* v = act->Results()[0];
const Value* p = act->Results()[1];
std::optional<Env> matches = PatternMatch(p, v, stmt->LineNumber());
std::optional<Env> matches = PatternMatch(p, v, stmt->SourceLoc());
CHECK(matches)
<< stmt->LineNumber()
<< stmt->SourceLoc()
<< ": internal error in variable definition, match failed";
for (const auto& [name, value] : *matches) {
frame->scopes.Top()->values.Set(name, value);
@@ -988,7 +986,7 @@ Transition StepStmt() {
// -> { { C, E, F} :: S, H(a := v)}
auto pat = act->Results()[0];
auto val = act->Results()[1];
PatternAssignment(pat, val, stmt->LineNumber());
PatternAssignment(pat, val, stmt->SourceLoc());
return Done{};
}
case Statement::Kind::If:
@@ -1021,7 +1019,7 @@ Transition StepStmt() {
} else {
// { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
// -> { {v :: C', E', F'} :: S, H}
const Value* ret_val = CopyVal(act->Results()[0], stmt->LineNumber());
const Value* ret_val = CopyVal(act->Results()[0], stmt->SourceLoc());
return UnwindFunctionCall{ret_val};
}
case Statement::Kind::Sequence: {
@@ -1047,7 +1045,7 @@ Transition StepStmt() {
Stack<Ptr<Scope>>(global_arena->New<Scope>(CurrentEnv(state)));
Stack<Ptr<Action>> todo;
todo.Push(global_arena->New<StatementAction>(
global_arena->RawNew<Return>(stmt->LineNumber(), nullptr,
global_arena->RawNew<Return>(stmt->SourceLoc(), nullptr,
/*is_omitted_exp=*/true)));
todo.Push(
global_arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
@@ -1077,8 +1075,8 @@ Transition StepStmt() {
// value from the continuation.
auto ignore_result = global_arena->New<StatementAction>(
global_arena->RawNew<ExpressionStatement>(
stmt->LineNumber(),
global_arena->RawNew<TupleLiteral>(stmt->LineNumber())));
stmt->SourceLoc(),
global_arena->RawNew<TupleLiteral>(stmt->SourceLoc())));
frame->todo.Push(ignore_result);
// Push the continuation onto the current stack.
const std::vector<Ptr<Frame>>& continuation_vector =
@@ -1100,7 +1098,7 @@ Transition StepStmt() {
// Update the continuation with the paused stack.
state->heap.Write(*paused.back()->continuation,
global_arena->RawNew<ContinuationValue>(paused),
stmt->LineNumber());
stmt->SourceLoc());
return ManualTransition{};
}
}
@@ -1164,7 +1162,7 @@ struct DoTransition {
void operator()(const CallFunction& call) {
state->stack.Top()->todo.Pop();
std::optional<Env> matches =
PatternMatch(call.function->Param(), call.args, call.line_num);
PatternMatch(call.function->Param(), call.args, call.loc);
CHECK(matches.has_value())
<< "internal error in call_function, pattern match failed";
// Create the new frame and push it on the stack
@@ -1217,9 +1215,11 @@ auto InterpProgram(const std::list<Ptr<const Declaration>>& fs) -> int {
}
InitGlobals(fs);
const Expression* arg = global_arena->RawNew<TupleLiteral>(0);
SourceLocation loc("<InterpProgram()>", 0);
const Expression* arg = global_arena->RawNew<TupleLiteral>(loc);
const Expression* call_main = global_arena->RawNew<CallExpression>(
0, global_arena->RawNew<IdentifierExpression>(0, "main"), arg);
loc, global_arena->RawNew<IdentifierExpression>(loc, "main"), arg);
auto todo =
Stack<Ptr<Action>>(global_arena->New<ExpressionAction>(call_main));
auto scopes = Stack<Ptr<Scope>>(global_arena->New<Scope>(globals));
@@ -39,7 +39,7 @@ void PrintEnv(Env values, llvm::raw_ostream& out);
// Attempts to match `v` against the pattern `p`. If matching succeeds, returns
// the bindings of pattern variables to their matched values.
auto PatternMatch(const Value* p, const Value* v, int line_num)
auto PatternMatch(const Value* p, const Value* v, SourceLocation loc)
-> std::optional<Env>;
auto InterpProgram(const std::list<Ptr<const Declaration>>& fs) -> int;
+137 -135
View File
@@ -32,66 +32,71 @@ void PrintTypeEnv(TypeEnv types, llvm::raw_ostream& out) {
}
}
static void ExpectType(int line_num, const std::string& context,
static void ExpectType(SourceLocation loc, const std::string& context,
const Value* expected, const Value* actual) {
if (!TypeEqual(expected, actual)) {
FATAL_COMPILATION_ERROR(line_num) << "type error in " << context << "\n"
<< "expected: " << *expected << "\n"
<< "actual: " << *actual;
FATAL_COMPILATION_ERROR(loc) << "type error in " << context << "\n"
<< "expected: " << *expected << "\n"
<< "actual: " << *actual;
}
}
static void ExpectPointerType(int line_num, const std::string& context,
static void ExpectPointerType(SourceLocation loc, const std::string& context,
const Value* actual) {
if (actual->Tag() != Value::Kind::PointerType) {
FATAL_COMPILATION_ERROR(line_num) << "type error in " << context << "\n"
<< "expected a pointer type\n"
<< "actual: " << *actual;
FATAL_COMPILATION_ERROR(loc) << "type error in " << context << "\n"
<< "expected a pointer type\n"
<< "actual: " << *actual;
}
}
static SourceLocation ReifyFakeSourceLoc() {
return SourceLocation("<reify>", 0);
}
// Reify type to type expression.
static auto ReifyType(const Value* t, int line_num) -> const Expression* {
static auto ReifyType(const Value* t, SourceLocation loc) -> const Expression* {
switch (t->Tag()) {
case Value::Kind::IntType:
return global_arena->RawNew<IntTypeLiteral>(0);
return global_arena->RawNew<IntTypeLiteral>(ReifyFakeSourceLoc());
case Value::Kind::BoolType:
return global_arena->RawNew<BoolTypeLiteral>(0);
return global_arena->RawNew<BoolTypeLiteral>(ReifyFakeSourceLoc());
case Value::Kind::TypeType:
return global_arena->RawNew<TypeTypeLiteral>(0);
return global_arena->RawNew<TypeTypeLiteral>(ReifyFakeSourceLoc());
case Value::Kind::ContinuationType:
return global_arena->RawNew<ContinuationTypeLiteral>(0);
return global_arena->RawNew<ContinuationTypeLiteral>(
ReifyFakeSourceLoc());
case Value::Kind::FunctionType: {
const auto& fn_type = cast<FunctionType>(*t);
return global_arena->RawNew<FunctionTypeLiteral>(
0, ReifyType(fn_type.Param(), line_num),
ReifyType(fn_type.Ret(), line_num),
ReifyFakeSourceLoc(), ReifyType(fn_type.Param(), loc),
ReifyType(fn_type.Ret(), 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, line_num)));
FieldInitializer(field.name, ReifyType(field.value, loc)));
}
return global_arena->RawNew<TupleLiteral>(0, args);
return global_arena->RawNew<TupleLiteral>(ReifyFakeSourceLoc(), args);
}
case Value::Kind::ClassType:
return global_arena->RawNew<IdentifierExpression>(
0, cast<ClassType>(*t).Name());
ReifyFakeSourceLoc(), cast<ClassType>(*t).Name());
case Value::Kind::ChoiceType:
return global_arena->RawNew<IdentifierExpression>(
0, cast<ChoiceType>(*t).Name());
ReifyFakeSourceLoc(), cast<ChoiceType>(*t).Name());
case Value::Kind::PointerType:
return global_arena->RawNew<PrimitiveOperatorExpression>(
0, Operator::Ptr,
ReifyFakeSourceLoc(), Operator::Ptr,
std::vector<const Expression*>(
{ReifyType(cast<PointerType>(*t).Type(), line_num)}));
{ReifyType(cast<PointerType>(*t).Type(), loc)}));
case Value::Kind::VariableType:
return global_arena->RawNew<IdentifierExpression>(
0, cast<VariableType>(*t).Name());
ReifyFakeSourceLoc(), cast<VariableType>(*t).Name());
case Value::Kind::StringType:
return global_arena->RawNew<StringTypeLiteral>(0);
return global_arena->RawNew<StringTypeLiteral>(ReifyFakeSourceLoc());
case Value::Kind::AlternativeConstructorValue:
case Value::Kind::AlternativeValue:
case Value::Kind::AutoType:
@@ -113,8 +118,8 @@ static auto ReifyType(const Value* t, int line_num) -> const Expression* {
// inside the argument type.
// The `deduced` parameter is an accumulator, that is, it holds the
// results so-far.
static auto ArgumentDeduction(int line_num, TypeEnv deduced, const Value* param,
const Value* arg) -> TypeEnv {
static auto ArgumentDeduction(SourceLocation loc, TypeEnv deduced,
const Value* param, const Value* arg) -> TypeEnv {
switch (param->Tag()) {
case Value::Kind::VariableType: {
const auto& var_type = cast<VariableType>(*param);
@@ -122,50 +127,47 @@ static auto ArgumentDeduction(int line_num, TypeEnv deduced, const Value* param,
if (!d) {
deduced.Set(var_type.Name(), arg);
} else {
ExpectType(line_num, "argument deduction", *d, arg);
ExpectType(loc, "argument deduction", *d, arg);
}
return deduced;
}
case Value::Kind::TupleValue: {
if (arg->Tag() != Value::Kind::TupleValue) {
ExpectType(line_num, "argument deduction", param, arg);
ExpectType(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(line_num, "argument deduction", param, arg);
ExpectType(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(line_num)
FATAL_COMPILATION_ERROR(loc)
<< "mismatch in tuple names, " << param_tup.Elements()[i].name
<< " != " << arg_tup.Elements()[i].name;
}
deduced =
ArgumentDeduction(line_num, deduced, param_tup.Elements()[i].value,
arg_tup.Elements()[i].value);
deduced = ArgumentDeduction(loc, deduced, param_tup.Elements()[i].value,
arg_tup.Elements()[i].value);
}
return deduced;
}
case Value::Kind::FunctionType: {
if (arg->Tag() != Value::Kind::FunctionType) {
ExpectType(line_num, "argument deduction", param, arg);
ExpectType(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(line_num, deduced, param_fn.Param(),
arg_fn.Param());
deduced =
ArgumentDeduction(line_num, deduced, param_fn.Ret(), arg_fn.Ret());
ArgumentDeduction(loc, deduced, param_fn.Param(), arg_fn.Param());
deduced = ArgumentDeduction(loc, deduced, param_fn.Ret(), arg_fn.Ret());
return deduced;
}
case Value::Kind::PointerType: {
if (arg->Tag() != Value::Kind::PointerType) {
ExpectType(line_num, "argument deduction", param, arg);
ExpectType(loc, "argument deduction", param, arg);
}
return ArgumentDeduction(line_num, deduced,
cast<PointerType>(*param).Type(),
return ArgumentDeduction(loc, deduced, cast<PointerType>(*param).Type(),
cast<PointerType>(*arg).Type());
}
// Nothing to do in the case for `auto`.
@@ -180,7 +182,7 @@ static auto ArgumentDeduction(int line_num, TypeEnv deduced, const Value* param,
case Value::Kind::BoolType:
case Value::Kind::TypeType:
case Value::Kind::StringType:
ExpectType(line_num, "argument deduction", param, arg);
ExpectType(loc, "argument deduction", param, arg);
return deduced;
// The rest of these cases should never happen.
case Value::Kind::IntValue:
@@ -284,16 +286,16 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
std::string f = std::to_string(i);
const Value* field_t = cast<TupleValue>(*t).FindField(f);
if (field_t == nullptr) {
FATAL_COMPILATION_ERROR(e->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "field " << f << " is not in the tuple " << *t;
}
auto new_e = global_arena->RawNew<IndexExpression>(
e->LineNumber(), res.exp,
global_arena->RawNew<IntLiteral>(e->LineNumber(), i));
e->SourceLoc(), res.exp,
global_arena->RawNew<IntLiteral>(e->SourceLoc(), i));
return TCExpression(new_e, field_t, res.types);
}
default:
FATAL_COMPILATION_ERROR(e->LineNumber()) << "expected a tuple";
FATAL_COMPILATION_ERROR(e->SourceLoc()) << "expected a tuple";
}
}
case Expression::Kind::TupleLiteral: {
@@ -307,7 +309,7 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
arg_types.push_back({.name = arg.name, .value = arg_res.type});
}
auto tuple_e =
global_arena->RawNew<TupleLiteral>(e->LineNumber(), new_args);
global_arena->RawNew<TupleLiteral>(e->SourceLoc(), new_args);
auto tuple_t = global_arena->RawNew<TupleValue>(std::move(arg_types));
return TCExpression(tuple_e, tuple_t, new_types);
}
@@ -323,7 +325,7 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
if (access.Field() == field.first) {
const Expression* new_e =
global_arena->RawNew<FieldAccessExpression>(
e->LineNumber(), res.exp, access.Field());
e->SourceLoc(), res.exp, access.Field());
return TCExpression(new_e, field.second, res.types);
}
}
@@ -332,11 +334,11 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
if (access.Field() == method.first) {
const Expression* new_e =
global_arena->RawNew<FieldAccessExpression>(
e->LineNumber(), res.exp, access.Field());
e->SourceLoc(), res.exp, access.Field());
return TCExpression(new_e, method.second, res.types);
}
}
FATAL_COMPILATION_ERROR(e->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "class " << t_class.Name() << " does not have a field named "
<< access.Field();
}
@@ -345,11 +347,11 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
for (const TupleElement& field : tup.Elements()) {
if (access.Field() == field.name) {
auto new_e = global_arena->RawNew<FieldAccessExpression>(
e->LineNumber(), res.exp, access.Field());
e->SourceLoc(), res.exp, access.Field());
return TCExpression(new_e, field.value, res.types);
}
}
FATAL_COMPILATION_ERROR(e->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "tuple " << tup << " does not have a field named "
<< access.Field();
}
@@ -359,18 +361,18 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
if (access.Field() == vt.first) {
const Expression* new_e =
global_arena->RawNew<FieldAccessExpression>(
e->LineNumber(), res.exp, access.Field());
e->SourceLoc(), res.exp, access.Field());
auto fun_ty = global_arena->RawNew<FunctionType>(
std::vector<GenericBinding>(), vt.second, t);
return TCExpression(new_e, fun_ty, res.types);
}
}
FATAL_COMPILATION_ERROR(e->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "choice " << choice.Name() << " does not have a field named "
<< access.Field();
}
default:
FATAL_COMPILATION_ERROR(e->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "field access, expected a struct\n"
<< *e;
}
@@ -381,7 +383,7 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
if (type) {
return TCExpression(e, *type, types);
} else {
FATAL_COMPILATION_ERROR(e->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "could not find `" << ident.Name() << "`";
}
}
@@ -401,63 +403,63 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
ts.push_back(res.type);
}
auto new_e = global_arena->RawNew<PrimitiveOperatorExpression>(
e->LineNumber(), op.Op(), es);
e->SourceLoc(), op.Op(), es);
switch (op.Op()) {
case Operator::Neg:
ExpectType(e->LineNumber(), "negation",
ExpectType(e->SourceLoc(), "negation",
global_arena->RawNew<IntType>(), ts[0]);
return TCExpression(new_e, global_arena->RawNew<IntType>(),
new_types);
case Operator::Add:
ExpectType(e->LineNumber(), "addition(1)",
ExpectType(e->SourceLoc(), "addition(1)",
global_arena->RawNew<IntType>(), ts[0]);
ExpectType(e->LineNumber(), "addition(2)",
ExpectType(e->SourceLoc(), "addition(2)",
global_arena->RawNew<IntType>(), ts[1]);
return TCExpression(new_e, global_arena->RawNew<IntType>(),
new_types);
case Operator::Sub:
ExpectType(e->LineNumber(), "subtraction(1)",
ExpectType(e->SourceLoc(), "subtraction(1)",
global_arena->RawNew<IntType>(), ts[0]);
ExpectType(e->LineNumber(), "subtraction(2)",
ExpectType(e->SourceLoc(), "subtraction(2)",
global_arena->RawNew<IntType>(), ts[1]);
return TCExpression(new_e, global_arena->RawNew<IntType>(),
new_types);
case Operator::Mul:
ExpectType(e->LineNumber(), "multiplication(1)",
ExpectType(e->SourceLoc(), "multiplication(1)",
global_arena->RawNew<IntType>(), ts[0]);
ExpectType(e->LineNumber(), "multiplication(2)",
ExpectType(e->SourceLoc(), "multiplication(2)",
global_arena->RawNew<IntType>(), ts[1]);
return TCExpression(new_e, global_arena->RawNew<IntType>(),
new_types);
case Operator::And:
ExpectType(e->LineNumber(), "&&(1)", global_arena->RawNew<BoolType>(),
ExpectType(e->SourceLoc(), "&&(1)", global_arena->RawNew<BoolType>(),
ts[0]);
ExpectType(e->LineNumber(), "&&(2)", global_arena->RawNew<BoolType>(),
ExpectType(e->SourceLoc(), "&&(2)", global_arena->RawNew<BoolType>(),
ts[1]);
return TCExpression(new_e, global_arena->RawNew<BoolType>(),
new_types);
case Operator::Or:
ExpectType(e->LineNumber(), "||(1)", global_arena->RawNew<BoolType>(),
ExpectType(e->SourceLoc(), "||(1)", global_arena->RawNew<BoolType>(),
ts[0]);
ExpectType(e->LineNumber(), "||(2)", global_arena->RawNew<BoolType>(),
ExpectType(e->SourceLoc(), "||(2)", global_arena->RawNew<BoolType>(),
ts[1]);
return TCExpression(new_e, global_arena->RawNew<BoolType>(),
new_types);
case Operator::Not:
ExpectType(e->LineNumber(), "!", global_arena->RawNew<BoolType>(),
ExpectType(e->SourceLoc(), "!", global_arena->RawNew<BoolType>(),
ts[0]);
return TCExpression(new_e, global_arena->RawNew<BoolType>(),
new_types);
case Operator::Eq:
ExpectType(e->LineNumber(), "==", ts[0], ts[1]);
ExpectType(e->SourceLoc(), "==", ts[0], ts[1]);
return TCExpression(new_e, global_arena->RawNew<BoolType>(),
new_types);
case Operator::Deref:
ExpectPointerType(e->LineNumber(), "*", ts[0]);
ExpectPointerType(e->SourceLoc(), "*", ts[0]);
return TCExpression(new_e, cast<PointerType>(*ts[0]).Type(),
new_types);
case Operator::Ptr:
ExpectType(e->LineNumber(), "*", global_arena->RawNew<TypeType>(),
ExpectType(e->SourceLoc(), "*", global_arena->RawNew<TypeType>(),
ts[0]);
return TCExpression(new_e, global_arena->RawNew<TypeType>(),
new_types);
@@ -474,13 +476,13 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
auto parameter_type = fun_t.Param();
auto return_type = fun_t.Ret();
if (!fun_t.Deduced().empty()) {
auto deduced_args = ArgumentDeduction(e->LineNumber(), TypeEnv(),
auto deduced_args = ArgumentDeduction(e->SourceLoc(), TypeEnv(),
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->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "could not deduce type argument for type parameter "
<< deduced_param.name;
}
@@ -488,14 +490,14 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
parameter_type = Substitute(deduced_args, parameter_type);
return_type = Substitute(deduced_args, return_type);
} else {
ExpectType(e->LineNumber(), "call", parameter_type, arg_res.type);
ExpectType(e->SourceLoc(), "call", parameter_type, arg_res.type);
}
auto new_e = global_arena->RawNew<CallExpression>(
e->LineNumber(), fun_res.exp, arg_res.exp);
e->SourceLoc(), fun_res.exp, arg_res.exp);
return TCExpression(new_e, return_type, arg_res.types);
}
default: {
FATAL_COMPILATION_ERROR(e->LineNumber())
FATAL_COMPILATION_ERROR(e->SourceLoc())
<< "in call, expected a function\n"
<< *e;
}
@@ -507,8 +509,8 @@ auto TypeCheckExp(const Expression* e, TypeEnv types, Env values)
auto pt = InterpExp(values, fn.Parameter());
auto rt = InterpExp(values, fn.ReturnType());
auto new_e = global_arena->RawNew<FunctionTypeLiteral>(
e->LineNumber(), ReifyType(pt, e->LineNumber()),
ReifyType(rt, e->LineNumber()),
e->SourceLoc(), ReifyType(pt, e->SourceLoc()),
ReifyType(rt, e->SourceLoc()),
/*is_omitted_return_type=*/false);
return TCExpression(new_e, global_arena->RawNew<TypeType>(), types);
}
@@ -557,9 +559,9 @@ auto TypeCheckPattern(const Pattern* p, TypeEnv types, Env values,
const Value* type = InterpPattern(values, binding_type_result.pattern);
if (expected != nullptr) {
std::optional<Env> values =
PatternMatch(type, expected, binding.Type()->LineNumber());
PatternMatch(type, expected, binding.Type()->SourceLoc());
if (values == std::nullopt) {
FATAL_COMPILATION_ERROR(binding.Type()->LineNumber())
FATAL_COMPILATION_ERROR(binding.Type()->SourceLoc())
<< "Type pattern '" << *type << "' does not match actual type '"
<< *expected << "'";
}
@@ -568,9 +570,9 @@ auto TypeCheckPattern(const Pattern* p, TypeEnv types, Env values,
type = expected;
}
auto new_p = global_arena->RawNew<BindingPattern>(
binding.LineNumber(), binding.Name(),
binding.SourceLoc(), binding.Name(),
global_arena->RawNew<ExpressionPattern>(
ReifyType(type, binding.LineNumber())));
ReifyType(type, binding.SourceLoc())));
if (binding.Name().has_value()) {
types.Set(*binding.Name(), type);
}
@@ -582,11 +584,11 @@ auto TypeCheckPattern(const Pattern* p, TypeEnv types, Env values,
std::vector<TupleElement> field_types;
auto new_types = types;
if (expected && expected->Tag() != Value::Kind::TupleValue) {
FATAL_COMPILATION_ERROR(p->LineNumber()) << "didn't expect a tuple";
FATAL_COMPILATION_ERROR(p->SourceLoc()) << "didn't expect a tuple";
}
if (expected && tuple.Fields().size() !=
cast<TupleValue>(*expected).Elements().size()) {
FATAL_COMPILATION_ERROR(tuple.LineNumber())
FATAL_COMPILATION_ERROR(tuple.SourceLoc())
<< "tuples of different length";
}
for (size_t i = 0; i < tuple.Fields().size(); ++i) {
@@ -596,7 +598,7 @@ auto TypeCheckPattern(const Pattern* p, TypeEnv types, Env values,
const TupleElement& expected_element =
cast<TupleValue>(*expected).Elements()[i];
if (expected_element.name != field.name) {
FATAL_COMPILATION_ERROR(tuple.LineNumber())
FATAL_COMPILATION_ERROR(tuple.SourceLoc())
<< "field names do not match, expected "
<< expected_element.name << " but got " << field.name;
}
@@ -610,7 +612,7 @@ auto TypeCheckPattern(const Pattern* p, TypeEnv types, Env values,
field_types.push_back({.name = field.name, .value = field_result.type});
}
auto new_tuple =
global_arena->RawNew<TuplePattern>(tuple.LineNumber(), new_fields);
global_arena->RawNew<TuplePattern>(tuple.SourceLoc(), new_fields);
auto tuple_t = global_arena->RawNew<TupleValue>(std::move(field_types));
return {.pattern = new_tuple, .type = tuple_t, .types = new_types};
}
@@ -618,26 +620,26 @@ auto TypeCheckPattern(const Pattern* p, TypeEnv types, Env values,
const auto& alternative = cast<AlternativePattern>(*p);
const Value* choice_type = InterpExp(values, alternative.ChoiceType());
if (choice_type->Tag() != Value::Kind::ChoiceType) {
FATAL_COMPILATION_ERROR(alternative.LineNumber())
FATAL_COMPILATION_ERROR(alternative.SourceLoc())
<< "alternative pattern does not name a choice type.";
}
if (expected != nullptr) {
ExpectType(alternative.LineNumber(), "alternative pattern", expected,
ExpectType(alternative.SourceLoc(), "alternative pattern", expected,
choice_type);
}
const Value* parameter_types =
FindInVarValues(alternative.AlternativeName(),
cast<ChoiceType>(*choice_type).Alternatives());
if (parameter_types == nullptr) {
FATAL_COMPILATION_ERROR(alternative.LineNumber())
FATAL_COMPILATION_ERROR(alternative.SourceLoc())
<< "'" << alternative.AlternativeName()
<< "' is not an alternative of " << choice_type;
}
TCPattern arg_results = TypeCheckPattern(alternative.Arguments(), types,
values, parameter_types);
return {.pattern = global_arena->RawNew<AlternativePattern>(
alternative.LineNumber(),
ReifyType(choice_type, alternative.LineNumber()),
alternative.SourceLoc(),
ReifyType(choice_type, alternative.SourceLoc()),
alternative.AlternativeName(),
cast<TuplePattern>(arg_results.pattern)),
.type = choice_type,
@@ -689,17 +691,17 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
ret_type, is_omitted_ret_type));
}
const Statement* new_s =
global_arena->RawNew<Match>(s->LineNumber(), res.exp, new_clauses);
global_arena->RawNew<Match>(s->SourceLoc(), res.exp, new_clauses);
return TCStatement(new_s, types);
}
case Statement::Kind::While: {
const auto& while_stmt = cast<While>(*s);
auto cnd_res = TypeCheckExp(while_stmt.Cond(), types, values);
ExpectType(s->LineNumber(), "condition of `while`",
ExpectType(s->SourceLoc(), "condition of `while`",
global_arena->RawNew<BoolType>(), cnd_res.type);
auto body_res = TypeCheckStmt(while_stmt.Body(), types, values, ret_type,
is_omitted_ret_type);
auto new_s = global_arena->RawNew<While>(s->LineNumber(), cnd_res.exp,
auto new_s = global_arena->RawNew<While>(s->SourceLoc(), cnd_res.exp,
body_res.stmt);
return TCStatement(new_s, types);
}
@@ -710,7 +712,7 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
auto stmt_res = TypeCheckStmt(cast<Block>(*s).Stmt(), types, values,
ret_type, is_omitted_ret_type);
return TCStatement(
global_arena->RawNew<Block>(s->LineNumber(), stmt_res.stmt), types);
global_arena->RawNew<Block>(s->SourceLoc(), stmt_res.stmt), types);
}
case Statement::Kind::VariableDefinition: {
const auto& var = cast<VariableDefinition>(*s);
@@ -718,7 +720,7 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
const Value* rhs_ty = res.type;
auto lhs_res = TypeCheckPattern(var.Pat(), types, values, rhs_ty);
const Statement* new_s = global_arena->RawNew<VariableDefinition>(
s->LineNumber(), var.Pat(), res.exp);
s->SourceLoc(), var.Pat(), res.exp);
return TCStatement(new_s, lhs_res.types);
}
case Statement::Kind::Sequence: {
@@ -730,7 +732,7 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
is_omitted_ret_type);
auto types3 = next_res.types;
return TCStatement(global_arena->RawNew<Sequence>(
s->LineNumber(), stmt_res.stmt, next_res.stmt),
s->SourceLoc(), stmt_res.stmt, next_res.stmt),
types3);
}
case Statement::Kind::Assign: {
@@ -739,8 +741,8 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
auto rhs_t = rhs_res.type;
auto lhs_res = TypeCheckExp(assign.Lhs(), types, values);
auto lhs_t = lhs_res.type;
ExpectType(s->LineNumber(), "assign", lhs_t, rhs_t);
auto new_s = global_arena->RawNew<Assign>(s->LineNumber(), lhs_res.exp,
ExpectType(s->SourceLoc(), "assign", lhs_t, rhs_t);
auto new_s = global_arena->RawNew<Assign>(s->SourceLoc(), lhs_res.exp,
rhs_res.exp);
return TCStatement(new_s, lhs_res.types);
}
@@ -748,19 +750,19 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
auto res =
TypeCheckExp(cast<ExpressionStatement>(*s).Exp(), types, values);
auto new_s =
global_arena->RawNew<ExpressionStatement>(s->LineNumber(), res.exp);
global_arena->RawNew<ExpressionStatement>(s->SourceLoc(), res.exp);
return TCStatement(new_s, types);
}
case Statement::Kind::If: {
const auto& if_stmt = cast<If>(*s);
auto cnd_res = TypeCheckExp(if_stmt.Cond(), types, values);
ExpectType(s->LineNumber(), "condition of `if`",
ExpectType(s->SourceLoc(), "condition of `if`",
global_arena->RawNew<BoolType>(), cnd_res.type);
auto then_res = TypeCheckStmt(if_stmt.ThenStmt(), types, values, ret_type,
is_omitted_ret_type);
auto else_res = TypeCheckStmt(if_stmt.ElseStmt(), types, values, ret_type,
is_omitted_ret_type);
auto new_s = global_arena->RawNew<If>(s->LineNumber(), cnd_res.exp,
auto new_s = global_arena->RawNew<If>(s->SourceLoc(), cnd_res.exp,
then_res.stmt, else_res.stmt);
return TCStatement(new_s, types);
}
@@ -773,14 +775,14 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
// should infer the least-upper bound of all the 'return' statements.
ret_type = res.type;
} else {
ExpectType(s->LineNumber(), "return", ret_type, res.type);
ExpectType(s->SourceLoc(), "return", ret_type, res.type);
}
if (ret.IsOmittedExp() != is_omitted_ret_type) {
FATAL_COMPILATION_ERROR(s->LineNumber())
FATAL_COMPILATION_ERROR(s->SourceLoc())
<< *s << " should" << (is_omitted_ret_type ? " not" : "")
<< " provide a return value, to match the function's signature.";
}
return TCStatement(global_arena->RawNew<Return>(s->LineNumber(), res.exp,
return TCStatement(global_arena->RawNew<Return>(s->SourceLoc(), res.exp,
ret.IsOmittedExp()),
types);
}
@@ -789,7 +791,7 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
TCStatement body_result = TypeCheckStmt(cont.Body(), types, values,
ret_type, is_omitted_ret_type);
const Statement* new_continuation = global_arena->RawNew<Continuation>(
s->LineNumber(), cont.ContinuationVariable(), body_result.stmt);
s->SourceLoc(), cont.ContinuationVariable(), body_result.stmt);
types.Set(cont.ContinuationVariable(),
global_arena->RawNew<ContinuationType>());
return TCStatement(new_continuation, types);
@@ -797,11 +799,11 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
case Statement::Kind::Run: {
TCExpression argument_result =
TypeCheckExp(cast<Run>(*s).Argument(), types, values);
ExpectType(s->LineNumber(), "argument of `run`",
ExpectType(s->SourceLoc(), "argument of `run`",
global_arena->RawNew<ContinuationType>(),
argument_result.type);
const Statement* new_run =
global_arena->RawNew<Run>(s->LineNumber(), argument_result.exp);
global_arena->RawNew<Run>(s->SourceLoc(), argument_result.exp);
return TCStatement(new_run, types);
}
case Statement::Kind::Await: {
@@ -812,13 +814,13 @@ auto TypeCheckStmt(const Statement* s, TypeEnv types, Env values,
}
static auto CheckOrEnsureReturn(const Statement* stmt, bool omitted_ret_type,
int line_num) -> const Statement* {
SourceLocation loc) -> const Statement* {
if (!stmt) {
if (omitted_ret_type) {
return global_arena->RawNew<Return>(line_num, nullptr,
return global_arena->RawNew<Return>(loc, nullptr,
/*is_omitted_exp=*/true);
} else {
FATAL_COMPILATION_ERROR(line_num)
FATAL_COMPILATION_ERROR(loc)
<< "control-flow reaches end of function that provides a `->` return "
"type without reaching a return statement";
}
@@ -830,25 +832,25 @@ static auto CheckOrEnsureReturn(const Statement* stmt, bool omitted_ret_type,
std::list<std::pair<const Pattern*, const Statement*>>>();
for (const auto& clause : *match.Clauses()) {
auto s = CheckOrEnsureReturn(clause.second, omitted_ret_type,
stmt->LineNumber());
stmt->SourceLoc());
new_clauses->push_back(std::make_pair(clause.first, s));
}
return global_arena->RawNew<Match>(stmt->LineNumber(), match.Exp(),
return global_arena->RawNew<Match>(stmt->SourceLoc(), match.Exp(),
new_clauses);
}
case Statement::Kind::Block:
return global_arena->RawNew<Block>(
stmt->LineNumber(),
stmt->SourceLoc(),
CheckOrEnsureReturn(cast<Block>(*stmt).Stmt(), omitted_ret_type,
stmt->LineNumber()));
stmt->SourceLoc()));
case Statement::Kind::If: {
const auto& if_stmt = cast<If>(*stmt);
return global_arena->RawNew<If>(
stmt->LineNumber(), if_stmt.Cond(),
stmt->SourceLoc(), if_stmt.Cond(),
CheckOrEnsureReturn(if_stmt.ThenStmt(), omitted_ret_type,
stmt->LineNumber()),
stmt->SourceLoc()),
CheckOrEnsureReturn(if_stmt.ElseStmt(), omitted_ret_type,
stmt->LineNumber()));
stmt->SourceLoc()));
}
case Statement::Kind::Return:
return stmt;
@@ -856,12 +858,12 @@ static auto CheckOrEnsureReturn(const Statement* stmt, bool omitted_ret_type,
const auto& seq = cast<Sequence>(*stmt);
if (seq.Next()) {
return global_arena->RawNew<Sequence>(
stmt->LineNumber(), seq.Stmt(),
stmt->SourceLoc(), seq.Stmt(),
CheckOrEnsureReturn(seq.Next(), omitted_ret_type,
stmt->LineNumber()));
stmt->SourceLoc()));
} else {
return CheckOrEnsureReturn(seq.Stmt(), omitted_ret_type,
stmt->LineNumber());
stmt->SourceLoc());
}
}
case Statement::Kind::Continuation:
@@ -876,11 +878,11 @@ static auto CheckOrEnsureReturn(const Statement* stmt, bool omitted_ret_type,
case Statement::Kind::VariableDefinition:
if (omitted_ret_type) {
return global_arena->RawNew<Sequence>(
stmt->LineNumber(), stmt,
global_arena->RawNew<Return>(line_num, nullptr,
stmt->SourceLoc(), stmt,
global_arena->RawNew<Return>(loc, nullptr,
/*is_omitted_exp=*/true));
} else {
FATAL_COMPILATION_ERROR(stmt->LineNumber())
FATAL_COMPILATION_ERROR(stmt->SourceLoc())
<< "control-flow reaches end of function that provides a `->` "
"return type without reaching a return statement";
}
@@ -905,18 +907,18 @@ static auto TypeCheckFunDef(const FunctionDefinition* f, TypeEnv types,
// Evaluate the return type expression
auto return_type = InterpPattern(values, f->return_type);
if (f->name == "main") {
ExpectType(f->line_num, "return type of `main`",
ExpectType(f->source_location, "return type of `main`",
global_arena->RawNew<IntType>(), return_type);
// TODO: Check that main doesn't have any parameters.
}
auto res = TypeCheckStmt(f->body, param_res.types, values, return_type,
f->is_omitted_return_type);
auto body =
CheckOrEnsureReturn(res.stmt, f->is_omitted_return_type, f->line_num);
auto body = CheckOrEnsureReturn(res.stmt, f->is_omitted_return_type,
f->source_location);
return global_arena->New<FunctionDefinition>(
f->line_num, f->name, f->deduced_parameters, f->param_pattern,
f->source_location, f->name, f->deduced_parameters, f->param_pattern,
global_arena->RawNew<ExpressionPattern>(
ReifyType(return_type, f->line_num)),
ReifyType(return_type, f->source_location)),
/*is_omitted_return_type=*/false, body);
}
@@ -951,13 +953,13 @@ static auto TypeOfClassDef(const ClassDefinition* sd, TypeEnv /*types*/,
case Member::Kind::FieldMember: {
const BindingPattern* binding = cast<FieldMember>(*m).Binding();
if (!binding->Name().has_value()) {
FATAL_COMPILATION_ERROR(binding->LineNumber())
FATAL_COMPILATION_ERROR(binding->SourceLoc())
<< "Struct members must have names";
}
const Expression* type_expression =
dyn_cast<ExpressionPattern>(binding->Type())->Expression();
if (type_expression == nullptr) {
FATAL_COMPILATION_ERROR(binding->LineNumber())
FATAL_COMPILATION_ERROR(binding->SourceLoc())
<< "Struct members must have explicit types";
}
auto type = InterpExp(ct_top, type_expression);
@@ -981,7 +983,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->LineNumber())
FATAL_COMPILATION_ERROR(binding->SourceLoc())
<< "Top-level variable declarations must have names";
}
return *binding->Name();
@@ -1008,8 +1010,8 @@ auto MakeTypeChecked(const Ptr<const Declaration> d, const TypeEnv& types,
break;
}
}
return global_arena->New<ClassDeclaration>(
class_def.line_num, class_def.name, std::move(fields));
return global_arena->New<ClassDeclaration>(class_def.loc, class_def.name,
std::move(fields));
}
case Declaration::Kind::ChoiceDeclaration:
@@ -1027,11 +1029,11 @@ auto MakeTypeChecked(const Ptr<const Declaration> d, const TypeEnv& types,
dyn_cast<ExpressionPattern>(var.Binding()->Type())->Expression();
if (type == nullptr) {
// TODO: consider adding support for `auto`
FATAL_COMPILATION_ERROR(var.LineNumber())
FATAL_COMPILATION_ERROR(var.SourceLoc())
<< "Type of a top-level variable must be an expression.";
}
const Value* declared_type = InterpExp(values, type);
ExpectType(var.LineNumber(), "initializer of variable", declared_type,
ExpectType(var.SourceLoc(), "initializer of variable", declared_type,
type_checked_initializer.type);
return d;
}
+27 -27
View File
@@ -54,29 +54,28 @@ auto TupleValue::FindField(const std::string& name) const -> const Value* {
namespace {
auto GetMember(const Value* v, const std::string& f, int line_num)
auto GetMember(const Value* v, const std::string& f, SourceLocation loc)
-> const Value* {
switch (v->Tag()) {
case Value::Kind::StructValue: {
const Value* field =
cast<TupleValue>(*cast<StructValue>(*v).Inits()).FindField(f);
if (field == nullptr) {
FATAL_RUNTIME_ERROR(line_num) << "member " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(loc) << "member " << f << " not in " << *v;
}
return field;
}
case Value::Kind::TupleValue: {
const Value* field = cast<TupleValue>(*v).FindField(f);
if (field == nullptr) {
FATAL_RUNTIME_ERROR(line_num) << "field " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(loc) << "field " << f << " not in " << *v;
}
return field;
}
case Value::Kind::ChoiceType: {
const auto& choice = cast<ChoiceType>(*v);
if (FindInVarValues(f, choice.Alternatives()) == nullptr) {
FATAL_RUNTIME_ERROR(line_num)
<< "alternative " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(loc) << "alternative " << f << " not in " << *v;
}
return global_arena->RawNew<AlternativeConstructorValue>(f,
choice.Name());
@@ -88,11 +87,11 @@ auto GetMember(const Value* v, const std::string& f, int line_num)
} // namespace
auto Value::GetField(const FieldPath& path, int line_num) const
auto Value::GetField(const FieldPath& path, SourceLocation loc) const
-> const Value* {
const Value* value = this;
for (const std::string& field : path.components) {
value = GetMember(value, field, line_num);
value = GetMember(value, field, loc);
}
return value;
}
@@ -102,14 +101,15 @@ namespace {
auto SetFieldImpl(const Value* value,
std::vector<std::string>::const_iterator path_begin,
std::vector<std::string>::const_iterator path_end,
const Value* field_value, int line_num) -> const Value* {
const Value* field_value, SourceLocation loc)
-> const Value* {
if (path_begin == path_end) {
return field_value;
}
switch (value->Tag()) {
case Value::Kind::StructValue: {
return SetFieldImpl(cast<StructValue>(*value).Inits(), path_begin,
path_end, field_value, line_num);
path_end, field_value, loc);
}
case Value::Kind::TupleValue: {
std::vector<TupleElement> elements = cast<TupleValue>(*value).Elements();
@@ -118,11 +118,11 @@ auto SetFieldImpl(const Value* value,
return element.name == *path_begin;
});
if (it == elements.end()) {
FATAL_RUNTIME_ERROR(line_num)
FATAL_RUNTIME_ERROR(loc)
<< "field " << *path_begin << " not in " << *value;
}
it->value = SetFieldImpl(it->value, path_begin + 1, path_end, field_value,
line_num);
it->value =
SetFieldImpl(it->value, path_begin + 1, path_end, field_value, loc);
return global_arena->RawNew<TupleValue>(elements);
}
default:
@@ -133,9 +133,9 @@ auto SetFieldImpl(const Value* value,
} // namespace
auto Value::SetField(const FieldPath& path, const Value* field_value,
int line_num) const -> const Value* {
SourceLocation loc) const -> const Value* {
return SetFieldImpl(this, path.components.begin(), path.components.end(),
field_value, line_num);
field_value, loc);
}
void Value::Print(llvm::raw_ostream& out) const {
@@ -248,25 +248,25 @@ void Value::Print(llvm::raw_ostream& out) const {
}
}
auto CopyVal(const Value* val, int line_num) -> const Value* {
auto CopyVal(const Value* val, SourceLocation loc) -> const Value* {
switch (val->Tag()) {
case Value::Kind::TupleValue: {
std::vector<TupleElement> elements;
for (const TupleElement& element : cast<TupleValue>(*val).Elements()) {
elements.push_back(
{.name = element.name, .value = CopyVal(element.value, line_num)});
{.name = element.name, .value = CopyVal(element.value, loc)});
}
return global_arena->RawNew<TupleValue>(std::move(elements));
}
case Value::Kind::AlternativeValue: {
const auto& alt = cast<AlternativeValue>(*val);
const Value* arg = CopyVal(alt.Argument(), line_num);
const Value* arg = CopyVal(alt.Argument(), loc);
return global_arena->RawNew<AlternativeValue>(alt.AltName(),
alt.ChoiceName(), arg);
}
case Value::Kind::StructValue: {
const auto& s = cast<StructValue>(*val);
const Value* inits = CopyVal(s.Inits(), line_num);
const Value* inits = CopyVal(s.Inits(), loc);
return global_arena->RawNew<StructValue>(s.Type(), inits);
}
case Value::Kind::IntValue:
@@ -285,13 +285,13 @@ auto CopyVal(const Value* val, int line_num) -> const Value* {
return val;
case Value::Kind::FunctionType: {
const auto& fn_type = cast<FunctionType>(*val);
return global_arena->RawNew<FunctionType>(
fn_type.Deduced(), CopyVal(fn_type.Param(), line_num),
CopyVal(fn_type.Ret(), line_num));
return global_arena->RawNew<FunctionType>(fn_type.Deduced(),
CopyVal(fn_type.Param(), loc),
CopyVal(fn_type.Ret(), loc));
}
case Value::Kind::PointerType:
return global_arena->RawNew<PointerType>(
CopyVal(cast<PointerType>(*val).Type(), line_num));
CopyVal(cast<PointerType>(*val).Type(), loc));
case Value::Kind::IntType:
return global_arena->RawNew<IntType>();
case Value::Kind::BoolType:
@@ -366,8 +366,8 @@ auto TypeEqual(const Value* t1, const Value* t2) -> bool {
// Returns true if all the fields of the two tuples contain equal values
// and returns false otherwise.
static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
const std::vector<TupleElement>& ts2, int line_num)
-> bool {
const std::vector<TupleElement>& ts2,
SourceLocation loc) -> bool {
if (ts1.size() != ts2.size()) {
return false;
}
@@ -378,7 +378,7 @@ static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
if (iter == ts2.end()) {
return false;
}
if (!ValueEqual(element.value, iter->value, line_num)) {
if (!ValueEqual(element.value, iter->value, loc)) {
return false;
}
}
@@ -388,7 +388,7 @@ static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
// Returns true if the two values are equal and returns false otherwise.
//
// This function implements the `==` operator of Carbon.
auto ValueEqual(const Value* v1, const Value* v2, int line_num) -> bool {
auto ValueEqual(const Value* v1, const Value* v2, SourceLocation loc) -> bool {
if (v1->Tag() != v2->Tag()) {
return false;
}
@@ -403,7 +403,7 @@ auto ValueEqual(const Value* v1, const Value* v2, int line_num) -> bool {
return cast<FunctionValue>(*v1).Body() == cast<FunctionValue>(*v2).Body();
case Value::Kind::TupleValue:
return FieldsValueEqual(cast<TupleValue>(*v1).Elements(),
cast<TupleValue>(*v2).Elements(), line_num);
cast<TupleValue>(*v2).Elements(), loc);
case Value::Kind::StringValue:
return cast<StringValue>(*v1).Val() == cast<StringValue>(*v2).Val();
case Value::Kind::IntType:
+5 -4
View File
@@ -69,12 +69,13 @@ class Value {
// Returns the sub-Value specified by `path`, which must be a valid field
// path for *this.
auto GetField(const FieldPath& path, int line_num) const -> const Value*;
auto GetField(const FieldPath& path, SourceLocation loc) const
-> 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(const FieldPath& path, const Value* field_value,
int line_num) const -> const Value*;
SourceLocation loc) const -> const Value*;
protected:
// Constructs a Value. `tag` must be the enumerator corresponding to the
@@ -471,10 +472,10 @@ class StringValue : public Value {
std::string val;
};
auto CopyVal(const Value* val, int line_num) -> const Value*;
auto CopyVal(const Value* val, SourceLocation loc) -> const Value*;
auto TypeEqual(const Value* t1, const Value* t2) -> bool;
auto ValueEqual(const Value* v1, const Value* v2, int line_num) -> bool;
auto ValueEqual(const Value* v1, const Value* v2, SourceLocation loc) -> bool;
} // namespace Carbon