mirror of
https://github.com/carbon-language/carbon-lang.git
synced 2026-10-05 21:31:24 +01:00
Global variables (#378)
* global variables * implemented type checking of global variable, added test case * added a comment * improvements based on Dave's suggestions * improvements based on Jon's suggestions * added test cases about global variable ordering
This commit is contained in:
@@ -304,6 +304,14 @@ auto FunctionDeclaration::InitGlobals(Env& globals) const -> void {
|
||||
globals.Set(definition->name, a);
|
||||
}
|
||||
|
||||
// Adds an entry in `globals` mapping the variable's name to the
|
||||
// result of evaluating the initializer.
|
||||
auto VariableDeclaration::InitGlobals(Env& globals) const -> void {
|
||||
auto v = InterpExp(globals, initializer);
|
||||
Address a = AllocateValue(v);
|
||||
globals.Set(name, a);
|
||||
}
|
||||
|
||||
// { S, H} -> { { C, E, F} :: S, H}
|
||||
// where C is the body of the function,
|
||||
// E is the environment (functions + parameters + locals)
|
||||
|
||||
@@ -620,6 +620,9 @@ auto StructDeclaration::Name() const -> std::string { return *definition.name; }
|
||||
|
||||
auto ChoiceDeclaration::Name() const -> std::string { return name; }
|
||||
|
||||
// Returns the name of the declared variable.
|
||||
auto VariableDeclaration::Name() const -> std::string { return name; }
|
||||
|
||||
auto StructDeclaration::TypeChecked(TypeEnv env, Env ct_env) const
|
||||
-> Declaration {
|
||||
auto fields = new std::list<Member*>();
|
||||
@@ -642,6 +645,19 @@ auto ChoiceDeclaration::TypeChecked(TypeEnv env, Env ct_env) const
|
||||
return *this; // TODO.
|
||||
}
|
||||
|
||||
// Signals a type error if the initializing expression does not have
|
||||
// the declared type of the variable, otherwise returns this
|
||||
// declaration with annotated types.
|
||||
auto VariableDeclaration::TypeChecked(TypeEnv env, Env ct_env) const
|
||||
-> Declaration {
|
||||
TCResult typeCheckedInitializer =
|
||||
TypeCheckExp(initializer, env, ct_env, nullptr, TCContext::ValueContext);
|
||||
Value* declaredType = ToType(sourceLocation, InterpExp(ct_env, type));
|
||||
ExpectType(sourceLocation, "initializer of variable", declaredType,
|
||||
typeCheckedInitializer.type);
|
||||
return *this;
|
||||
}
|
||||
|
||||
auto TopLevel(std::list<Declaration>* fs) -> std::pair<TypeEnv, Env> {
|
||||
ExecutionEnvironment tops;
|
||||
bool found_main = false;
|
||||
@@ -687,4 +703,11 @@ auto ChoiceDeclaration::TopLevel(ExecutionEnvironment& tops) const -> void {
|
||||
tops.first.Set(Name(), ct);
|
||||
}
|
||||
|
||||
// Associate the variable name with it's declared type in the
|
||||
// compile-time symbol table.
|
||||
auto VariableDeclaration::TopLevel(ExecutionEnvironment& tops) const -> void {
|
||||
Value* declaredType = ToType(sourceLocation, InterpExp(tops.second, type));
|
||||
tops.first.Set(Name(), declaredType);
|
||||
}
|
||||
|
||||
} // namespace Carbon
|
||||
|
||||
Reference in New Issue
Block a user