diff --git a/src/Compilers/VisualBasic/Portable/Semantics/Conversions.vb b/src/Compilers/VisualBasic/Portable/Semantics/Conversions.vb index 05c150a14e9a9f3a8e3c005db227c4500d165c3e..502663ac17ccad37630d479713e1ea30cb86ed3c 100644 --- a/src/Compilers/VisualBasic/Portable/Semantics/Conversions.vb +++ b/src/Compilers/VisualBasic/Portable/Semantics/Conversions.vb @@ -916,13 +916,16 @@ Namespace Microsoft.CodeAnalysis.VisualBasic userDefinedConversionsMightStillBeApplicable = False Dim conv As ConversionKind - ' Using .IsConstant() for field accesses can result in an infinite loop. - ' To detect such a loop pass the already visited constants from the binder. + ' Using source.IsConstant for field accesses can result in an infinite loop. + ' To resolve the cycle, first call GetConstantValue with the already visited constants from the binder. + ' The check for source.IsConstant is still necessary because the node might still + ' be considered as a non-constant in some error conditions (a reference before declaration, + ' for example). Dim sourceIsConstant As Boolean = False If source.Kind = BoundKind.FieldAccess Then - sourceIsConstant = DirectCast(source, BoundFieldAccess).FieldSymbol.GetConstantValue(binder.ConstantFieldsInProgress) IsNot Nothing + sourceIsConstant = DirectCast(source, BoundFieldAccess).FieldSymbol.GetConstantValue(binder.ConstantFieldsInProgress) IsNot Nothing AndAlso source.IsConstant ElseIf source.Kind = BoundKind.Local Then - sourceIsConstant = DirectCast(source, BoundLocal).LocalSymbol.GetConstantValue(binder) IsNot Nothing + sourceIsConstant = DirectCast(source, BoundLocal).LocalSymbol.GetConstantValue(binder) IsNot Nothing AndAlso source.IsConstant Else sourceIsConstant = source.IsConstant End If diff --git a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb index ab1a482a817730d2d9a00ab04b37db8b35ad721a..966df975272fdf4ba65da3ee36cda88054685d22 100644 --- a/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb +++ b/src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb @@ -4727,5 +4727,28 @@ Expected - 2 CompileAndVerify(compilation, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub + + + Public Sub ConvertConstantBeforeItsDeclaration() + Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( + + + , options:=TestOptions.ReleaseExe) + + compilation.AssertTheseDiagnostics( + +BC32000: Local variable 'STR' cannot be referred to before it is declared. + Dim x as Integer = STR + ~~~ +) + End Sub + End Class End Namespace