[NFC] Convert NameScope from struct to class (#4623)

This is a preparation change for adding name poisoning support
(https://github.com/carbon-language/carbon-lang/issues/4622), which is
expected to require more elaborate logic around NameScope since a name
can be not defined yet, defined, or poisoned.

The API separates looking up a name from getting the full entry since we
have cases where the entries are invalidated between the time we're
looking for the name and when we access (and sometimes modify) the
entry.

This change has the following benefits:
* `names` and `name_map` are internal to `NameScope` and are guaranteed
to match.
* `extended_scopes` and `import_ir_scopes` can not be manipulated (only
new scopes can be added).
* `inst_id`, `name_id` and `parent_scope_id` are constants.
* `has_error` can only be mutated from false to true.

---------

Co-authored-by: jonmeow <jperkins@google.com>
This commit is contained in:
Boaz Brickner
2024-12-06 21:50:50 +00:00
committed by GitHub
co-authored by jonmeow
parent e7a86b03c6
commit daba2c72cf
19 changed files with 526 additions and 140 deletions
+6 -6
View File
@@ -359,16 +359,16 @@ auto Context::LookupNameInExactScope(SemIRLoc loc, SemIR::NameId name_id,
SemIR::NameScopeId scope_id,
const SemIR::NameScope& scope)
-> std::pair<SemIR::InstId, SemIR::AccessKind> {
if (auto lookup = scope.name_map.Lookup(name_id)) {
auto entry = scope.names[lookup.value()];
if (auto entry_id = scope.Lookup(name_id)) {
auto entry = scope.GetEntry(*entry_id);
LoadImportRef(*this, entry.inst_id);
return {entry.inst_id, entry.access_kind};
}
if (!scope.import_ir_scopes.empty()) {
if (!scope.import_ir_scopes().empty()) {
// TODO: Enforce other access modifiers for imports.
return {ImportNameFromOtherPackage(*this, loc, scope_id,
scope.import_ir_scopes, name_id),
scope.import_ir_scopes(), name_id),
SemIR::AccessKind::Public};
}
return {SemIR::InstId::Invalid, SemIR::AccessKind::Public};
@@ -525,7 +525,7 @@ auto Context::LookupQualifiedName(SemIRLoc loc, SemIR::NameId name_id,
continue;
}
const auto& name_scope = name_scopes().Get(scope_id);
has_error |= name_scope.has_error;
has_error |= name_scope.has_error();
auto [scope_result_id, access_kind] =
LookupNameInExactScope(loc, name_id, scope_id, name_scope);
@@ -546,7 +546,7 @@ auto Context::LookupQualifiedName(SemIRLoc loc, SemIR::NameId name_id,
if (!scope_result_id.is_valid() || is_access_prohibited) {
// If nothing is found in this scope or if we encountered an invalid
// access, look in its extended scopes.
const auto& extended = name_scope.extended_scopes;
const auto& extended = name_scope.extended_scopes();
scopes.reserve(scopes.size() + extended.size());
for (auto extended_id : llvm::reverse(extended)) {
// Substitute into the constant describing the extended scope to