[executable semantics] class-ify Declaration (#307)

* [executable semantics] class-ify Declaration

NFC (no functional change).

Proof of concept that we can simplify code by replacing unions with safer, more
regular types.  Hand-rolled existentials (type-erasing CoW wrappers) are a follow-on
step that will further simplify usage.

Began adding `const` where possible, and replacing `std::string*` with
`std::string`.  Most `const`s can disappear as we replace reference semantics
with value semantics, but in the meantime it's an important step in the right
direction.
This commit is contained in:
Dave Abrahams
2021-02-27 13:32:03 -08:00
committed by GitHub
parent cd57024042
commit 2205fd52ce
14 changed files with 191 additions and 210 deletions
+16 -49
View File
@@ -8,57 +8,24 @@
namespace Carbon {
auto MakeFunDecl(FunctionDefinition* f) -> Declaration* {
auto* d = new Declaration();
d->tag = DeclarationKind::FunctionDeclaration;
d->u.fun_def = f;
return d;
}
void FunctionDeclaration::Print() const { PrintFunDef(definition); }
auto MakeStructDecl(int line_num, std::string name, std::list<Member*>* members)
-> Declaration* {
auto* d = new Declaration();
d->tag = DeclarationKind::StructDeclaration;
d->u.struct_def = new StructDefinition();
d->u.struct_def->line_num = line_num;
d->u.struct_def->name = new std::string(std::move(name));
d->u.struct_def->members = members;
return d;
}
auto MakeChoiceDecl(int line_num, std::string name,
std::list<std::pair<std::string, Expression*>>* alts)
-> Declaration* {
auto* d = new Declaration();
d->tag = DeclarationKind::ChoiceDeclaration;
d->u.choice_def.line_num = line_num;
d->u.choice_def.name = new std::string(std::move(name));
d->u.choice_def.alternatives = alts;
return d;
}
void PrintDecl(Declaration* d) {
switch (d->tag) {
case DeclarationKind::FunctionDeclaration:
PrintFunDef(d->u.fun_def);
break;
case DeclarationKind::StructDeclaration:
std::cout << "struct " << *d->u.struct_def->name << " {" << std::endl;
for (auto& member : *d->u.struct_def->members) {
PrintMember(member);
}
std::cout << "}" << std::endl;
break;
case DeclarationKind::ChoiceDeclaration:
std::cout << "choice " << *d->u.choice_def.name << " {" << std::endl;
for (auto& alternative : *d->u.choice_def.alternatives) {
std::cout << "alt " << alternative.first << " ";
PrintExp(alternative.second);
std::cout << ";" << std::endl;
}
std::cout << "}" << std::endl;
break;
void StructDeclaration::Print() const {
std::cout << "struct " << *definition.name << " {" << std::endl;
for (auto& member : *definition.members) {
PrintMember(member);
}
std::cout << "}" << std::endl;
}
void ChoiceDeclaration::Print() const {
std::cout << "choice " << name << " {" << std::endl;
for (auto& alternative : alternatives) {
std::cout << "alt " << alternative.first << " ";
PrintExp(alternative.second);
std::cout << ";" << std::endl;
}
std::cout << "}" << std::endl;
}
} // namespace Carbon