diff --git a/executable_semantics/ast/declaration.h b/executable_semantics/ast/declaration.h index 9909533257d4..e0403c51deed 100644 --- a/executable_semantics/ast/declaration.h +++ b/executable_semantics/ast/declaration.h @@ -50,6 +50,19 @@ class Declaration { auto source_loc() const -> SourceLocation { return source_loc_; } + // The static type of the declared entity. Cannot be called before + // typechecking. + auto static_type() const -> const Value& { return **static_type_; } + + // Sets the static type of the declared entity. Can only be called once, + // during typechecking. + void set_static_type(Nonnull type) { static_type_ = type; } + + // Returns whether the static type has been set. Should only be called + // during typechecking: before typechecking it's guaranteed to be false, + // and after typechecking it's guaranteed to be true. + auto has_static_type() const -> bool { return static_type_.has_value(); } + protected: // Constructs a Declaration representing syntax at the given line number. // `kind` must be the enumerator corresponding to the most-derived type being @@ -60,6 +73,7 @@ class Declaration { private: const Kind kind_; SourceLocation source_loc_; + std::optional> static_type_; }; // TODO: expand the kinds of things that can be deduced parameters. @@ -107,18 +121,6 @@ class FunctionDeclaration : public Declaration { } auto body() -> std::optional> { return body_; } - // The static type of this function. Cannot be called before typechecking. - auto static_type() const -> const Value& { return **static_type_; } - - // Sets the static type of this expression. Can only be called once, during - // typechecking. - void set_static_type(Nonnull type) { static_type_ = type; } - - // Returns whether the static type has been set. Should only be called - // during typechecking: before typechecking it's guaranteed to be false, - // and after typechecking it's guaranteed to be true. - auto has_static_type() const -> bool { return static_type_.has_value(); } - private: std::string name_; std::vector deduced_parameters_; @@ -126,8 +128,6 @@ class FunctionDeclaration : public Declaration { Nonnull return_type_; bool is_omitted_return_type_; std::optional> body_; - - std::optional> static_type_; }; class ClassDeclaration : public Declaration { diff --git a/executable_semantics/interpreter/interpreter.cpp b/executable_semantics/interpreter/interpreter.cpp index 22fa52f9d631..d8d7027cdcda 100644 --- a/executable_semantics/interpreter/interpreter.cpp +++ b/executable_semantics/interpreter/interpreter.cpp @@ -161,7 +161,8 @@ void Interpreter::InitEnv(const Declaration& d, Env* env) { const auto& var = cast(d); // Adds an entry in `globals` mapping the variable's name to the // result of evaluating the initializer. - auto v = InterpExp(*env, &var.initializer()); + Nonnull v = + Convert(InterpExp(*env, &var.initializer()), &var.static_type()); Address a = heap_.AllocateValue(v); env->Set(*var.binding().name(), a); break; @@ -455,6 +456,73 @@ auto Interpreter::StepLvalue() -> Transition { } } +auto Interpreter::Convert(Nonnull value, + Nonnull destination_type) const + -> Nonnull { + switch (value->kind()) { + case Value::Kind::IntValue: + case Value::Kind::FunctionValue: + case Value::Kind::PointerValue: + case Value::Kind::BoolValue: + case Value::Kind::NominalClassValue: + case Value::Kind::AlternativeValue: + case Value::Kind::IntType: + case Value::Kind::BoolType: + case Value::Kind::TypeType: + case Value::Kind::FunctionType: + case Value::Kind::PointerType: + case Value::Kind::AutoType: + case Value::Kind::StructType: + case Value::Kind::NominalClassType: + case Value::Kind::ChoiceType: + case Value::Kind::ContinuationType: + case Value::Kind::VariableType: + case Value::Kind::BindingPlaceholderValue: + case Value::Kind::AlternativeConstructorValue: + case Value::Kind::ContinuationValue: + case Value::Kind::StringType: + case Value::Kind::StringValue: + // TODO: add `CHECK(TypeEqual(type, value->dynamic_type()))`, once we + // have Value::dynamic_type. + return value; + case Value::Kind::StructValue: { + const auto& struct_val = cast(*value); + switch (destination_type->kind()) { + case Value::Kind::StructType: { + const auto& destination_struct_type = + cast(*destination_type); + std::vector new_elements; + for (const auto& [field_name, field_type] : + destination_struct_type.fields()) { + std::optional> old_value = + struct_val.FindField(field_name); + new_elements.push_back( + {.name = field_name, .value = Convert(*old_value, field_type)}); + } + return arena_->New(std::move(new_elements)); + } + case Value::Kind::NominalClassType: + return arena_->New(destination_type, value); + default: + FATAL() << "Can't convert value " << *value << " to type " + << *destination_type; + } + } + case Value::Kind::TupleValue: { + const auto& tuple = cast(value); + const auto& destination_tuple_type = cast(destination_type); + CHECK(tuple->elements().size() == + destination_tuple_type->elements().size()); + std::vector> new_elements; + for (size_t i = 0; i < tuple->elements().size(); ++i) { + new_elements.push_back(Convert(tuple->elements()[i], + destination_tuple_type->elements()[i])); + } + return arena_->New(std::move(new_elements)); + } + } +} + auto Interpreter::StepExp() -> Transition { Nonnull act = stack_.Top()->todo.Top(); const Expression& exp = cast(*act).expression(); @@ -758,8 +826,10 @@ auto Interpreter::StepStmt() -> Transition { return Done{}; } auto c = match_stmt.clauses()[clause_num]; - std::optional matches = PatternMatch( - &c.pattern().value(), act->results()[0], stmt.source_loc()); + std::optional matches = + PatternMatch(&c.pattern().value(), + Convert(act->results()[0], &c.pattern().static_type()), + stmt.source_loc()); if (matches) { // We have a match, start the body. // Ensure we don't process any more clauses. act->set_pos(match_stmt.clauses().size() + 1); @@ -781,14 +851,18 @@ auto Interpreter::StepStmt() -> Transition { act->Clear(); return Spawn{ arena_->New(&cast(stmt).condition())}; - } else if (cast(*act->results().back()).value()) { - // { {true :: (while ([]) s) :: C, E, F} :: S, H} - // -> { { s :: (while (e) s) :: C, E, F } :: S, H} - return Spawn{arena_->New(&cast(stmt).body())}; } else { - // { {false :: (while ([]) s) :: C, E, F} :: S, H} - // -> { { C, E, F } :: S, H} - return Done{}; + Nonnull condition = + Convert(act->results().back(), arena_->New()); + if (cast(*condition).value()) { + // { {true :: (while ([]) s) :: C, E, F} :: S, H} + // -> { { s :: (while (e) s) :: C, E, F } :: S, H} + return Spawn{arena_->New(&cast(stmt).body())}; + } else { + // { {false :: (while ([]) s) :: C, E, F} :: S, H} + // -> { { C, E, F } :: S, H} + return Done{}; + } } case Statement::Kind::Break: { CHECK(act->pos() == 0); @@ -831,16 +905,17 @@ auto Interpreter::StepStmt() -> Transition { return Done{}; } } - case Statement::Kind::VariableDefinition: + case Statement::Kind::VariableDefinition: { + const auto& definition = cast(stmt); if (act->pos() == 0) { // { {(var x = e) :: C, E, F} :: S, H} // -> { {e :: (var x = []) :: C, E, F} :: S, H} - return Spawn{arena_->New( - &cast(stmt).init())}; + return Spawn{arena_->New(&definition.init())}; } else { // { { v :: (x = []) :: C, E, F} :: S, H} // -> { { C, E(x := a), F} :: S, H(a := copy(v))} - Nonnull v = act->results()[0]; + Nonnull v = + Convert(act->results()[0], &definition.pattern().static_type()); Nonnull p = &cast(stmt).pattern().value(); @@ -854,6 +929,7 @@ auto Interpreter::StepStmt() -> Transition { } return Done{}; } + } case Statement::Kind::ExpressionStatement: if (act->pos() == 0) { // { {e :: C, E, F} :: S, H} @@ -863,43 +939,49 @@ auto Interpreter::StepStmt() -> Transition { } else { return Done{}; } - case Statement::Kind::Assign: + case Statement::Kind::Assign: { + const auto& assign = cast(stmt); if (act->pos() == 0) { // { {(lv = e) :: C, E, F} :: S, H} // -> { {lv :: ([] = e) :: C, E, F} :: S, H} - return Spawn{arena_->New(&cast(stmt).lhs())}; + return Spawn{arena_->New(&assign.lhs())}; } else if (act->pos() == 1) { // { { a :: ([] = e) :: C, E, F} :: S, H} // -> { { e :: (a = []) :: C, E, F} :: S, H} - return Spawn{arena_->New(&cast(stmt).rhs())}; + return Spawn{arena_->New(&assign.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]; + auto val = Convert(act->results()[1], &assign.lhs().static_type()); PatternAssignment(pat, val, stmt.source_loc()); return Done{}; } + } case Statement::Kind::If: 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(&cast(stmt).condition())}; - } else if (cast(*act->results()[0]).value()) { - // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} :: - // S, H} - // -> { { then_stmt :: C, E, F } :: S, H} - return Delegate{ - arena_->New(&cast(stmt).then_statement())}; - } else if (cast(stmt).else_statement()) { - // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} :: - // S, H} - // -> { { else_stmt :: C, E, F } :: S, H} - return Delegate{ - arena_->New(*cast(stmt).else_statement())}; } else { - return Done{}; + Nonnull condition = + Convert(act->results()[0], arena_->New()); + if (cast(*condition).value()) { + // { {true :: if ([]) then_stmt else else_stmt :: C, E, F} :: + // S, H} + // -> { { then_stmt :: C, E, F } :: S, H} + return Delegate{ + arena_->New(&cast(stmt).then_statement())}; + } else if (cast(stmt).else_statement()) { + // { {false :: if ([]) then_stmt else else_stmt :: C, E, F} :: + // S, H} + // -> { { else_stmt :: C, E, F } :: S, H} + return Delegate{ + arena_->New(*cast(stmt).else_statement())}; + } else { + return Done{}; + } } case Statement::Kind::Return: if (act->pos() == 0) { @@ -910,6 +992,8 @@ auto Interpreter::StepStmt() -> Transition { } else { // { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H} // -> { {v :: C', E', F'} :: S, H} + // TODO(geoffromer): convert the result to the function's return type, + // once #880 gives us a way to find that type. return UnwindFunctionCall{act->results()[0]}; } case Statement::Kind::Sequence: { @@ -967,8 +1051,10 @@ auto Interpreter::StepStmt() -> Transition { arena_->New(stmt.source_loc()))); frame->todo.Push(ignore_result); // Push the continuation onto the current stack_. + Nonnull arg = + Convert(act->results()[0], arena_->New()); std::vector>& continuation_vector = - cast(*act->results()[0]).stack(); + cast(*arg).stack(); while (!continuation_vector.empty()) { stack_.Push(continuation_vector.back()); continuation_vector.pop_back(); @@ -1054,8 +1140,11 @@ class Interpreter::DoTransition { void operator()(const CallFunction& call) { interpreter->stack_.Top()->todo.Pop(); - std::optional matches = interpreter->PatternMatch( - &call.function->param_pattern().value(), call.args, call.source_loc); + Nonnull converted_args = interpreter->Convert( + call.args, &call.function->param_pattern().static_type()); + std::optional matches = + interpreter->PatternMatch(&call.function->param_pattern().value(), + converted_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 diff --git a/executable_semantics/interpreter/interpreter.h b/executable_semantics/interpreter/interpreter.h index c3303e53447c..55252b7ca742 100644 --- a/executable_semantics/interpreter/interpreter.h +++ b/executable_semantics/interpreter/interpreter.h @@ -150,6 +150,11 @@ class Interpreter { void PatternAssignment(Nonnull pat, Nonnull val, SourceLocation source_loc); + // Returns the result of converting `value` to type `destination_type`. + auto Convert(Nonnull value, + Nonnull destination_type) const + -> Nonnull; + void PrintState(llvm::raw_ostream& out); Nonnull arena_; diff --git a/executable_semantics/interpreter/type_checker.cpp b/executable_semantics/interpreter/type_checker.cpp index 52e6582478c1..fd92854fb203 100644 --- a/executable_semantics/interpreter/type_checker.cpp +++ b/executable_semantics/interpreter/type_checker.cpp @@ -49,7 +49,7 @@ static void SetStaticType(Nonnull pattern, // Sets the static type of `definition`. Can be called multiple times on // the same node, so long as the types are the same on each call. -static void SetStaticType(Nonnull definition, +static void SetStaticType(Nonnull definition, Nonnull type) { if (definition->has_static_type()) { CHECK(TypeEqual(&definition->static_type(), type)); @@ -1057,8 +1057,8 @@ auto TypeChecker::TypeCheckFunDef(FunctionDeclaration* f, TypeEnv types, // Evaluate the return type expression auto return_type = interpreter_.InterpPattern(values, &f->return_type()); if (f->name() == "main") { - ExpectType(f->source_loc(), "return type of `main`", arena_->New(), - return_type); + ExpectExactType(f->source_loc(), "return type of `main`", + arena_->New(), return_type); // TODO: Check that main doesn't have any parameters. } std::optional> body_stmt; @@ -1181,6 +1181,7 @@ void TypeChecker::TypeCheck(Nonnull d, const TypeEnv& types, } Nonnull declared_type = interpreter_.InterpExp(values, &binding_type->expression()); + SetStaticType(&var, declared_type); ExpectType(var.source_loc(), "initializer of variable", declared_type, &var.initializer().static_type()); return;