Skip to content

VisualBasicCompilation.GetSemanticModel should check that the tree is valid #26689

@svick

Description

@svick

Version Used: 2.8.0, master

Steps to Reproduce:

Try to get semantic model for syntax tree that's not part of the compilation or is null:

var tree1 = SyntaxFactory.ParseSyntaxTree("");
var tree2 = SyntaxFactory.ParseSyntaxTree(@"
Class C
    Sub M()
    End Sub
End Class");

var compilation = VisualBasicCompilation.Create(null).AddSyntaxTrees(tree1);

compilation.GetSemanticModel(tree2);
compilation.GetSemanticModel(null);

Expected Behavior: Both calls to GetSemanticModel throw an exception.

Actual Behavior: Both calls to GetSemanticModel succeed.


The relevant code:

Public Shadows Function GetSemanticModel(syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False) As SemanticModel
Return New SyntaxTreeSemanticModel(Me, DirectCast(Me.SourceModule, SourceModuleSymbol), syntaxTree, ignoreAccessibility)
End Function

Friend Sub New(compilation As VisualBasicCompilation, sourceModule As SourceModuleSymbol, syntaxTree As SyntaxTree, Optional ignoreAccessibility As Boolean = False)
_compilation = compilation
_sourceModule = sourceModule
_syntaxTree = syntaxTree
_ignoresAccessibility = ignoreAccessibility
_binderFactory = New BinderFactory(sourceModule, syntaxTree)
End Sub

Note that C# performs both checks:

public new SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility)
{
if (syntaxTree == null)
{
throw new ArgumentNullException(nameof(syntaxTree));
}
if (!_syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree))
{
throw new ArgumentException(string.Format(CSharpResources.SyntaxTreeNotFoundTo, syntaxTree), nameof(syntaxTree));
}
return new SyntaxTreeSemanticModel(this, (SyntaxTree)syntaxTree, ignoreAccessibility);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-CompilersConcept-APIThis issue involves adding, removing, clarification, or modification of an API.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions