Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[internal] scala: parse and report package scopes #13738

Merged
merged 1 commit into from
Nov 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ case class Analysis(
providedSymbolsEncoded: Vector[String],
importsByScope: HashMap[String, ArrayBuffer[AnImport]],
consumedSymbolsByScope: HashMap[String, HashSet[String]],
scopes: Vector[String],
)

case class ProvidedSymbol(sawClass: Boolean, sawTrait: Boolean, sawObject: Boolean)
Expand All @@ -28,6 +29,7 @@ class SourceAnalysisTraverser extends Traverser {
val providedSymbolsByScope = HashMap[String, HashMap[String, ProvidedSymbol]]()
val importsByScope = HashMap[String, ArrayBuffer[AnImport]]()
val consumedSymbolsByScope = HashMap[String, HashSet[String]]()
val scopes = HashSet[String]()

// Extract a qualified name from a tree.
def extractName(tree: Tree): String = {
Expand Down Expand Up @@ -134,6 +136,11 @@ class SourceAnalysisTraverser extends Traverser {
consumedSymbolsByScope(fullPackageName).add(name)
}

def recordScope(name: String): Unit = {
val scopeName = (nameParts.toVector ++ Vector(name)).mkString(".")
scopes.add(scopeName)
}

def visitTemplate(templ: Template, name: String): Unit = {
templ.inits.foreach(init => apply(init))
withNamePart(name, () => {
Expand All @@ -144,7 +151,9 @@ class SourceAnalysisTraverser extends Traverser {

override def apply(tree: Tree): Unit = tree match {
case Pkg(ref, stats) => {
withNamePart(extractName(ref), () => super.apply(stats))
val name = extractName(ref)
recordScope(name)
withNamePart(name, () => super.apply(stats))
}

case Defn.Class(_mods, nameNode, _tparams, _ctor, templ) => {
Expand Down Expand Up @@ -283,6 +292,7 @@ class SourceAnalysisTraverser extends Traverser {
providedSymbolsEncoded = gatherEncodedProvidedSymbols(),
importsByScope = importsByScope,
consumedSymbolsByScope = consumedSymbolsByScope,
scopes = scopes.toVector,
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ class ScalaSourceDependencyAnalysis:
provided_symbols_encoded: FrozenOrderedSet[str]
imports_by_scope: FrozenDict[str, tuple[ScalaImport, ...]]
consumed_symbols_by_scope: FrozenDict[str, FrozenOrderedSet[str]]
scopes: FrozenOrderedSet[str]
Copy link
Member

@stuhood stuhood Nov 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm: we already have the relevant scopes via consumed_symbols_by_scope, don't we? In particular, to resolve #13655, it seems like we want to look up a symbol in any of its enclosing scopes, which actually requires the structure that we already have there. See the TODO I linked.

Copy link
Contributor Author

@tdyas tdyas Nov 29, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't. The scope key in consumed_symbols_by_scope is the scope where the consumed symbol was used, not the scopes that could potentially provide the symbol.

Moreover, take this example:

package foo
package bar.grok

If the file has no consumed symbols in foo, then foo won't show up as a scope key in consumed_symbols_by_scope even though foo should be inferred as a scope from which to find consumed symbols.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't. The scope key in consumed_symbols_by_scope is the scope where the consumed symbol was used, not the scopes that could potentially provide the symbol.

But the symbol could only possibly be provided by one of the parent scopes, right? Where a symbol is consumed is relevant.

For example, in:

package a {
  package b {
    class A {
      ...
    }
  }
  class C {
    ...
  }
}

... class A should not be visible to class C.


So is the idea just to walk upward from consumed_symbols_by_scope in the scopes, and suffix the symbol on each parent scope? In future, it might make things easier to include the consuming code in the same change, as it would answer these questions directly.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So is the idea just to walk upward from consumed_symbols_by_scope in the scopes, and suffix the symbol on each parent scope?

No. In this example, let's say that class A references X. Then that symbol could be a.b.X or a.X.

Also, I'm not understanding why you mentioned "... class A should not be visible to class C." Am I missing something?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, I'm not understanding why you mentioned "... class A should not be visible to class C." Am I missing something?

Sorry, I meant: should not be in scope. i.e., C would not be able to refer to A without qualification. It would need to refer to it as absolute: a.b.A. So: visible, but not automatically in scope.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So is the idea just to walk upward from consumed_symbols_by_scope in the scopes, and suffix the symbol on each parent scope?

Rethinking this, that is probably what I'll end up doing. Will handle that in the PR to actually update the dep inference logic.


def all_imports(self) -> Iterator[str]:
# TODO: This might also be an import relative to its scope.
Expand Down Expand Up @@ -180,6 +181,7 @@ def from_json_dict(cls, d: dict) -> ScalaSourceDependencyAnalysis:
for key, values in d["consumedSymbolsByScope"].items()
}
),
scopes=FrozenOrderedSet(d["scopes"]),
)

def to_debug_json_dict(self) -> dict[str, Any]:
Expand All @@ -193,6 +195,7 @@ def to_debug_json_dict(self) -> dict[str, Any]:
"consumed_symbols_by_scope": {
k: sorted(list(v)) for k, v in self.consumed_symbols_by_scope.items()
},
"scopes": list(self.scopes),
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -305,3 +305,49 @@ def this(bar: SomeTypeInSecondaryConstructor) {
"org.pantsbuild.example.TupleTypeArg1",
"org.pantsbuild.example.TupleTypeArg2",
}


def test_extract_package_scopes(rule_runner: RuleRunner) -> None:
rule_runner.write_files(
{
"BUILD": textwrap.dedent(
"""
scala_source(
name="source",
source="Source.scala",
)
"""
),
"Source.scala": textwrap.dedent(
"""
package outer
package more.than.one.part.at.once
package inner
"""
),
}
)

target = rule_runner.get_target(address=Address("", target_name="source"))

source_files = rule_runner.request(
SourceFiles,
[
SourceFilesRequest(
(target.get(SourcesField),),
for_sources_types=(ScalaSourceField,),
enable_codegen=True,
)
],
)

analysis = rule_runner.request(
ScalaSourceDependencyAnalysis,
[source_files],
)

assert sorted(analysis.scopes) == [
"outer",
"outer.more.than.one.part.at.once",
"outer.more.than.one.part.at.once.inner",
]