Skip to content

Commit

Permalink
Report a better error when lookup finds a package when expecting a value
Browse files Browse the repository at this point in the history
  • Loading branch information
MikePopoloski committed Dec 23, 2023
1 parent 1c5df1b commit 9f04262
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
1 change: 1 addition & 0 deletions scripts/diagnostics.txt
Original file line number Diff line number Diff line change
Expand Up @@ -853,6 +853,7 @@ error DotIntoInstArray "object is an array so expecting an index here, not a dot
error UnresolvedForwardTypedef "forward typedef '{}' does not resolve to a data type"
error DefinitionUsedAsType "'{}' is {} definition but is used like a type"
error DefinitionUsedAsValue "'{}' is {} definition but is used as a value"
error UndeclaredButFoundPackage "'{}' is a package, did you mean to use '::' here?"
error AutoVariableHierarchical "cannot refer to automatic variable via hierarchical reference"
error TypeHierarchical "cannot refer to type names via hierarchical reference"
error NonStaticClassProperty "invalid use of non-static class property '{}'"
Expand Down
9 changes: 7 additions & 2 deletions source/ast/Lookup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2169,8 +2169,7 @@ void Lookup::reportUndeclared(const Scope& initialScope, std::string_view name,
}

// Otherwise, check if this names a definition, in which case we can give a nicer error.
auto def = initialScope.getCompilation().getDefinition(name, initialScope);
if (def) {
if (auto def = comp.getDefinition(name, initialScope)) {
if (isHierarchical) {
result.addDiag(initialScope, diag::CouldNotResolveHierarchicalPath, range) << name;
}
Expand All @@ -2182,6 +2181,12 @@ void Lookup::reportUndeclared(const Scope& initialScope, std::string_view name,
return;
}

// Also check for a package with this name.
if (auto pkg = comp.getPackage(name)) {
result.addDiag(initialScope, diag::UndeclaredButFoundPackage, range.end()) << name << range;
return;
}

// Count the number of times we've performed typo correction.
comp.didTypoCorrection();

Expand Down
18 changes: 18 additions & 0 deletions tests/unittests/ast/LookupTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2045,3 +2045,21 @@ endmodule
REQUIRE(diags.size() == 1);
CHECK(diags[0].code == diag::DotIntoInstArray);
}

TEST_CASE("Undeclared identifier -- package correction") {
auto tree = SyntaxTree::fromText(R"(
package my_pkg;
endpackage
module m;
int i = my_pkg;
endmodule
)");

Compilation compilation;
compilation.addSyntaxTree(tree);

auto& diags = compilation.getAllDiagnostics();
REQUIRE(diags.size() == 1);
CHECK(diags[0].code == diag::UndeclaredButFoundPackage);
}

0 comments on commit 9f04262

Please sign in to comment.