Refactor Duplicate Code Patterns in StaticScope Class (#3550)

These changes are aimed at improving code readability and
maintainability within the `StaticScope` class of the AST folder.

- **Optimized Print and PrintID Methods:**
Introduced a template function `PrintCommon` to handle common logic in
`Print` and `PrintID`. This change simplifies the class interface and
avoids repetition, enhancing code readability.

- **Simplified TryResolveHere Method:**
Streamlined the `TryResolveHere` method by simplifying the conditional
logic. The refactored code is more readable and easier to understand,
improving overall code quality.

---------

Co-authored-by: Richard Smith <richard@metafoo.co.uk>
This commit is contained in:
Daniel James Szelogowski
2024-01-12 22:35:54 +00:00
committed by GitHub
co-authored by Richard Smith
parent f5e9158fa7
commit 44fdcc3db8
2 changed files with 18 additions and 19 deletions
+15 -19
View File
@@ -35,20 +35,21 @@ auto StaticScope::Add(std::string_view name, ValueNodeView entity,
return Success();
}
void StaticScope::Print(llvm::raw_ostream& out) const {
template <typename Action>
void StaticScope::PrintCommon(Action action) const {
if (ast_node_) {
ast_node_.value()->Print(out);
action(ast_node_.value());
} else {
*trace_stream_ << "package";
}
}
void StaticScope::Print(llvm::raw_ostream& out) const {
PrintCommon([&out](auto node) { node->Print(out); });
}
void StaticScope::PrintID(llvm::raw_ostream& out) const {
if (ast_node_) {
ast_node_.value()->PrintID(out);
} else {
*trace_stream_ << "package";
}
PrintCommon([&out](auto node) { node->PrintID(out); });
}
void StaticScope::MarkDeclared(std::string_view name) {
@@ -136,20 +137,15 @@ auto StaticScope::TryResolveHere(std::string_view name,
}
});
if (allow_undeclared) {
if (allow_undeclared || it->second.status == NameStatus::Usable) {
return {it->second.entity};
}
switch (it->second.status) {
case NameStatus::KnownButNotDeclared:
return ProgramError(source_loc)
<< "'" << name << "' has not been declared yet";
case NameStatus::DeclaredButNotUsable:
return ProgramError(source_loc) << "'" << name
<< "' is not usable until after it "
"has been completely declared";
case NameStatus::Usable:
return {it->second.entity};
}
return ProgramError(source_loc)
<< "'" << name
<< (it->second.status == NameStatus::KnownButNotDeclared
? "' has not been declared yet"
: "' is not usable until after it has been completely "
"declared");
}
auto StaticScope::AddReturnedVar(ValueNodeView returned_var_def_view)
+3
View File
@@ -55,6 +55,9 @@ class StaticScope {
auto Add(std::string_view name, ValueNodeView entity,
NameStatus status = NameStatus::Usable) -> ErrorOr<Success>;
template <typename Action>
void PrintCommon(Action action) const;
void Print(llvm::raw_ostream& out) const;
void PrintID(llvm::raw_ostream& out) const;