repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/EditorFeatures/CSharpTest2/Recommendations/TrueKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class TrueKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor2() { await VerifyAbsenceAsync( @"class C { #line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [WorkItem(542970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542970")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf() { await VerifyKeywordAsync( @"#if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Or() { await VerifyKeywordAsync( @"#if a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_And() { await VerifyKeywordAsync( @"#if a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Not() { await VerifyKeywordAsync( @"#if ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Paren() { await VerifyKeywordAsync( @"#if ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Equals() { await VerifyKeywordAsync( @"#if a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_NotEquals() { await VerifyKeywordAsync( @"#if a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf() { await VerifyKeywordAsync( @"#if true #elif $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPelIf_Or() { await VerifyKeywordAsync( @"#if true #elif a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_And() { await VerifyKeywordAsync( @"#if true #elif a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Not() { await VerifyKeywordAsync( @"#if true #elif ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Paren() { await VerifyKeywordAsync( @"#if true #elif ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Equals() { await VerifyKeywordAsync( @"#if true #elif a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_NotEquals() { await VerifyKeywordAsync( @"#if true #elif a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUnaryOperator() { await VerifyKeywordAsync( @"class C { public static bool operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeInactiveRegion() { await VerifyKeywordAsync( @"class C { void Init() { #if $$ H"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class TrueKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor2() { await VerifyAbsenceAsync( @"class C { #line $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"var q = $$")); } [WorkItem(542970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542970")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf() { await VerifyKeywordAsync( @"#if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Or() { await VerifyKeywordAsync( @"#if a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_And() { await VerifyKeywordAsync( @"#if a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Not() { await VerifyKeywordAsync( @"#if ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Paren() { await VerifyKeywordAsync( @"#if ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_Equals() { await VerifyKeywordAsync( @"#if a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPIf_NotEquals() { await VerifyKeywordAsync( @"#if a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf() { await VerifyKeywordAsync( @"#if true #elif $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPelIf_Or() { await VerifyKeywordAsync( @"#if true #elif a || $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_And() { await VerifyKeywordAsync( @"#if true #elif a && $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Not() { await VerifyKeywordAsync( @"#if true #elif ! $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Paren() { await VerifyKeywordAsync( @"#if true #elif ( $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_Equals() { await VerifyKeywordAsync( @"#if true #elif a == $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPPElIf_NotEquals() { await VerifyKeywordAsync( @"#if true #elif a != $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUnaryOperator() { await VerifyKeywordAsync( @"class C { public static bool operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterImplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExplicitOperator() { await VerifyAbsenceAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestBeforeInactiveRegion() { await VerifyKeywordAsync( @"class C { void Init() { #if $$ H"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDefault() { await VerifyAbsenceAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSizeOf() { await VerifyAbsenceAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/SourceGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // We only build the Source Generator in the netstandard target #if NETSTANDARD #nullable enable using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace CSharpSyntaxGenerator { [Generator] public sealed class SourceGenerator : CachingSourceGenerator { private static readonly DiagnosticDescriptor s_MissingSyntaxXml = new DiagnosticDescriptor( "CSSG1001", title: "Syntax.xml is missing", messageFormat: "The Syntax.xml file was not included in the project, so we are not generating source.", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_UnableToReadSyntaxXml = new DiagnosticDescriptor( "CSSG1002", title: "Syntax.xml could not be read", messageFormat: "The Syntax.xml file could not even be read. Does it exist?", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_SyntaxXmlError = new DiagnosticDescriptor( "CSSG1003", title: "Syntax.xml has a syntax error", messageFormat: "{0}", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); protected override bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText) { input = context.AdditionalFiles.SingleOrDefault(a => Path.GetFileName(a.Path) == "Syntax.xml"); if (input == null) { context.ReportDiagnostic(Diagnostic.Create(s_MissingSyntaxXml, location: null)); inputText = null; return false; } inputText = input.GetText(); if (inputText == null) { context.ReportDiagnostic(Diagnostic.Create(s_UnableToReadSyntaxXml, location: null)); return false; } return true; } protected override bool TryGenerateSources( AdditionalText input, SourceText inputText, out ImmutableArray<(string hintName, SourceText sourceText)> sources, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { Tree tree; var reader = XmlReader.Create(new SourceTextReader(inputText), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); try { var serializer = new XmlSerializer(typeof(Tree)); tree = (Tree)serializer.Deserialize(reader); } catch (InvalidOperationException ex) when (ex.InnerException is XmlException) { var xmlException = (XmlException)ex.InnerException; var line = inputText.Lines[xmlException.LineNumber - 1]; // LineNumber is one-based. int offset = xmlException.LinePosition - 1; // LinePosition is one-based var position = line.Start + offset; var span = new TextSpan(position, 0); var lineSpan = inputText.Lines.GetLinePositionSpan(span); sources = default; diagnostics = ImmutableArray.Create( Diagnostic.Create( s_SyntaxXmlError, location: Location.Create(input.Path, span, lineSpan), xmlException.Message)); return false; } TreeFlattening.FlattenChildren(tree); var sourcesBuilder = ImmutableArray.CreateBuilder<(string hintName, SourceText sourceText)>(); addResult(writer => SourceWriter.WriteMain(writer, tree, cancellationToken), "Syntax.xml.Main.Generated.cs"); addResult(writer => SourceWriter.WriteInternal(writer, tree, cancellationToken), "Syntax.xml.Internal.Generated.cs"); addResult(writer => SourceWriter.WriteSyntax(writer, tree, cancellationToken), "Syntax.xml.Syntax.Generated.cs"); sources = sourcesBuilder.ToImmutable(); diagnostics = ImmutableArray<Diagnostic>.Empty; return true; void addResult(Action<TextWriter> writeFunction, string hintName) { // Write out the contents to a StringBuilder to avoid creating a single large string // in memory var stringBuilder = new StringBuilder(); using (var textWriter = new StringWriter(stringBuilder)) { writeFunction(textWriter); } // And create a SourceText from the StringBuilder, once again avoiding allocating a single massive string var sourceText = SourceText.From(new StringBuilderReader(stringBuilder), stringBuilder.Length, encoding: Encoding.UTF8); sourcesBuilder.Add((hintName, sourceText)); } } private sealed class SourceTextReader : TextReader { private readonly SourceText _sourceText; private int _position; public SourceTextReader(SourceText sourceText) { _sourceText = sourceText; _position = 0; } public override int Peek() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position]; } public override int Read() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _sourceText.Length - _position); _sourceText.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } private sealed class StringBuilderReader : TextReader { private readonly StringBuilder _stringBuilder; private int _position; public StringBuilderReader(StringBuilder stringBuilder) { _stringBuilder = stringBuilder; _position = 0; } public override int Peek() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position]; } public override int Read() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _stringBuilder.Length - _position); _stringBuilder.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // We only build the Source Generator in the netstandard target #if NETSTANDARD #nullable enable using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace CSharpSyntaxGenerator { [Generator] public sealed class SourceGenerator : CachingSourceGenerator { private static readonly DiagnosticDescriptor s_MissingSyntaxXml = new DiagnosticDescriptor( "CSSG1001", title: "Syntax.xml is missing", messageFormat: "The Syntax.xml file was not included in the project, so we are not generating source.", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_UnableToReadSyntaxXml = new DiagnosticDescriptor( "CSSG1002", title: "Syntax.xml could not be read", messageFormat: "The Syntax.xml file could not even be read. Does it exist?", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); private static readonly DiagnosticDescriptor s_SyntaxXmlError = new DiagnosticDescriptor( "CSSG1003", title: "Syntax.xml has a syntax error", messageFormat: "{0}", category: "SyntaxGenerator", defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true); protected override bool TryGetRelevantInput(in GeneratorExecutionContext context, out AdditionalText? input, out SourceText? inputText) { input = context.AdditionalFiles.SingleOrDefault(a => Path.GetFileName(a.Path) == "Syntax.xml"); if (input == null) { context.ReportDiagnostic(Diagnostic.Create(s_MissingSyntaxXml, location: null)); inputText = null; return false; } inputText = input.GetText(); if (inputText == null) { context.ReportDiagnostic(Diagnostic.Create(s_UnableToReadSyntaxXml, location: null)); return false; } return true; } protected override bool TryGenerateSources( AdditionalText input, SourceText inputText, out ImmutableArray<(string hintName, SourceText sourceText)> sources, out ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { Tree tree; var reader = XmlReader.Create(new SourceTextReader(inputText), new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }); try { var serializer = new XmlSerializer(typeof(Tree)); tree = (Tree)serializer.Deserialize(reader); } catch (InvalidOperationException ex) when (ex.InnerException is XmlException) { var xmlException = (XmlException)ex.InnerException; var line = inputText.Lines[xmlException.LineNumber - 1]; // LineNumber is one-based. int offset = xmlException.LinePosition - 1; // LinePosition is one-based var position = line.Start + offset; var span = new TextSpan(position, 0); var lineSpan = inputText.Lines.GetLinePositionSpan(span); sources = default; diagnostics = ImmutableArray.Create( Diagnostic.Create( s_SyntaxXmlError, location: Location.Create(input.Path, span, lineSpan), xmlException.Message)); return false; } TreeFlattening.FlattenChildren(tree); var sourcesBuilder = ImmutableArray.CreateBuilder<(string hintName, SourceText sourceText)>(); addResult(writer => SourceWriter.WriteMain(writer, tree, cancellationToken), "Syntax.xml.Main.Generated.cs"); addResult(writer => SourceWriter.WriteInternal(writer, tree, cancellationToken), "Syntax.xml.Internal.Generated.cs"); addResult(writer => SourceWriter.WriteSyntax(writer, tree, cancellationToken), "Syntax.xml.Syntax.Generated.cs"); sources = sourcesBuilder.ToImmutable(); diagnostics = ImmutableArray<Diagnostic>.Empty; return true; void addResult(Action<TextWriter> writeFunction, string hintName) { // Write out the contents to a StringBuilder to avoid creating a single large string // in memory var stringBuilder = new StringBuilder(); using (var textWriter = new StringWriter(stringBuilder)) { writeFunction(textWriter); } // And create a SourceText from the StringBuilder, once again avoiding allocating a single massive string var sourceText = SourceText.From(new StringBuilderReader(stringBuilder), stringBuilder.Length, encoding: Encoding.UTF8); sourcesBuilder.Add((hintName, sourceText)); } } private sealed class SourceTextReader : TextReader { private readonly SourceText _sourceText; private int _position; public SourceTextReader(SourceText sourceText) { _sourceText = sourceText; _position = 0; } public override int Peek() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position]; } public override int Read() { if (_position == _sourceText.Length) { return -1; } return _sourceText[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _sourceText.Length - _position); _sourceText.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } private sealed class StringBuilderReader : TextReader { private readonly StringBuilder _stringBuilder; private int _position; public StringBuilderReader(StringBuilder stringBuilder) { _stringBuilder = stringBuilder; _position = 0; } public override int Peek() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position]; } public override int Read() { if (_position == _stringBuilder.Length) { return -1; } return _stringBuilder[_position++]; } public override int Read(char[] buffer, int index, int count) { var charsToCopy = Math.Min(count, _stringBuilder.Length - _position); _stringBuilder.CopyTo(_position, buffer, index, charsToCopy); _position += charsToCopy; return charsToCopy; } } } } #endif
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/Compilers/Test/Core/TempFiles/DisposableDirectory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class DisposableDirectory : TempDirectory, IDisposable { public DisposableDirectory(TempRoot root) : base(root) { } public void Dispose() { if (Path != null && Directory.Exists(Path)) { try { Directory.Delete(Path, recursive: true); } catch { } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; namespace Microsoft.CodeAnalysis.Test.Utilities { public sealed class DisposableDirectory : TempDirectory, IDisposable { public DisposableDirectory(TempRoot root) : base(root) { } public void Dispose() { if (Path != null && Directory.Exists(Path)) { try { Directory.Delete(Path, recursive: true); } catch { } } } } }
-1
dotnet/roslyn
56,293
Control exposure of tuple fields
Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
jcouv
"2021-09-09T18:17:36Z"
"2021-09-14T19:56:11Z"
dcadde85baf3b034319815445e453538a807ba4e
0bcaa937e2560ad2e442e2a70386109f6195aab6
Control exposure of tuple fields. Fixes https://github.com/dotnet/roslyn/issues/51204 The point of this change is to remove the special case for tuples in `AssertMemberExposure`.
./src/VisualStudio/Core/Def/Packaging/PackageInstallerServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.ServiceBroker; using Microsoft.VisualStudio.Threading; using NuGet.VisualStudio; using NuGet.VisualStudio.Contracts; using Roslyn.Utilities; using SVsServiceProvider = Microsoft.VisualStudio.Shell.SVsServiceProvider; using VSUtilities = Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Packaging { /// <summary> /// Free threaded wrapper around the NuGet.VisualStudio STA package installer interfaces. /// We want to be able to make queries about packages from any thread. For example, the /// add-NuGet-reference feature wants to know what packages a project already has /// references to. NuGet.VisualStudio provides this information, but only in a COM STA /// manner. As we don't want our background work to bounce and block on the UI thread /// we have this helper class which queries the information on the UI thread and caches /// the data so it can be read from the background. /// </summary> [ExportWorkspaceService(typeof(IPackageInstallerService)), Shared] internal partial class PackageInstallerService : AbstractDelayStartedService, IPackageInstallerService, IVsSearchProviderCallback { // Proper name, should not be localized. private const string NugetTitle = "NuGet"; private readonly VSUtilities.IUIThreadOperationExecutor _operationExecutor; private readonly VisualStudioWorkspaceImpl _workspace; private readonly SVsServiceProvider _serviceProvider; private readonly Shell.IAsyncServiceProvider _asyncServiceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IAsynchronousOperationListener _listener; private readonly Lazy<IVsPackageInstaller2>? _packageInstaller; private readonly Lazy<IVsPackageUninstaller>? _packageUninstaller; private readonly Lazy<IVsPackageSourceProvider>? _packageSourceProvider; private IVsPackage? _nugetPackageManager; /// <summary> /// Used to keep track of what types of changes we've seen so we can then determine what to refresh on the UI /// thread. If we hear about project changes, we only refresh that project. If we hear about a solution level /// change, we'll refresh all projects. /// </summary> /// <remarks> /// <c>solutionChanged == true iff changedProject == null</c> and <c>solutionChanged == false iff changedProject /// != null</c>. So technically having both values is redundant. However, i like the clarity of having both. /// </remarks> private readonly AsyncBatchingWorkQueue<(bool solutionChanged, ProjectId? changedProject)>? _workQueue; private readonly ConcurrentDictionary<ProjectId, ProjectState> _projectToInstalledPackageAndVersion = new(); /// <summary> /// Lock used to protect reads and writes of <see cref="_packageSourcesTask"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Task uses to compute the set of package sources on demand when asked the first time. The value will be /// computed and cached in the task. When this value changes, the task will simply be cleared out. /// </summary> private Task<ImmutableArray<PackageSource>>? _packageSourcesTask; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PackageInstallerService( IThreadingContext threadingContext, VSUtilities.IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListenerProvider listenerProvider, VisualStudioWorkspaceImpl workspace, SVsServiceProvider serviceProvider, [Import("Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider")] object asyncServiceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, [Import(AllowDefault = true)] Lazy<IVsPackageInstaller2>? packageInstaller, [Import(AllowDefault = true)] Lazy<IVsPackageUninstaller>? packageUninstaller, [Import(AllowDefault = true)] Lazy<IVsPackageSourceProvider>? packageSourceProvider) : base(threadingContext, workspace, SymbolSearchOptions.Enabled, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInNuGetPackages) { _operationExecutor = operationExecutor; _workspace = workspace; _serviceProvider = serviceProvider; // MEFv2 doesn't support type based contract for Import above and for this particular contract // (SAsyncServiceProvider) actual type cast doesn't work. (https://github.com/microsoft/vs-mef/issues/138) // workaround by getting the service as object and cast to actual interface _asyncServiceProvider = (Shell.IAsyncServiceProvider)asyncServiceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; _packageInstaller = packageInstaller; _packageUninstaller = packageUninstaller; _packageSourceProvider = packageSourceProvider; _listener = listenerProvider.GetListener(FeatureAttribute.PackageInstaller); // Setup the work queue to allow us to hear about flurries of changes and then respond to them in batches // every second. Note: we pass in EqualityComparer<...>.Default since we don't care about ordering, and // since once we hear about changes to a project (or the whole solution), we don't need to keep track if we // hear about the same thing in that batch window interval. _workQueue = new AsyncBatchingWorkQueue<(bool solutionChanged, ProjectId? changedProject)>( TimeSpan.FromSeconds(1), this.ProcessWorkQueueAsync, equalityComparer: EqualityComparer<(bool solutionChanged, ProjectId? changedProject)>.Default, _listener, this.DisposalToken); } public event EventHandler? PackageSourcesChanged; public ImmutableArray<PackageSource> TryGetPackageSources() { Task<ImmutableArray<PackageSource>> localPackageSourcesTask; lock (_gate) { if (_packageSourcesTask is null) _packageSourcesTask = Task.Run(() => GetPackageSourcesAsync(), this.DisposalToken); localPackageSourcesTask = _packageSourcesTask; } if (localPackageSourcesTask.Status == TaskStatus.RanToCompletion) { return localPackageSourcesTask.Result; } else { // The result was not available yet (or it was canceled/faulted). Just return an empty result to // signify we couldn't get this right now. return ImmutableArray<PackageSource>.Empty; } } private async Task<ImmutableArray<PackageSource>> GetPackageSourcesAsync() { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); try { if (_packageSourceProvider != null) return _packageSourceProvider.Value.GetSources(includeUnOfficial: true, includeDisabled: false).SelectAsArray(r => new PackageSource(r.Key, r.Value)); } catch (Exception ex) when (ex is InvalidDataException || ex is InvalidOperationException) { // These exceptions can happen when the nuget.config file is broken. } catch (ArgumentException ae) when (FatalError.ReportAndCatch(ae)) { // This exception can happen when the nuget.config file is broken, e.g. invalid credentials. // https://github.com/dotnet/roslyn/issues/40857 } return ImmutableArray<PackageSource>.Empty; } [MemberNotNullWhen(true, nameof(_packageInstaller))] [MemberNotNullWhen(true, nameof(_packageUninstaller))] [MemberNotNullWhen(true, nameof(_packageSourceProvider))] private bool IsEnabled { get { return _packageInstaller != null && _packageUninstaller != null && _packageSourceProvider != null; } } bool IPackageInstallerService.IsEnabled(ProjectId projectId) { if (!IsEnabled) { return false; } if (_projectToInstalledPackageAndVersion.TryGetValue(projectId, out var state)) { return state.IsEnabled; } // If we haven't scanned the project yet, assume that we're available for it. return true; } private async ValueTask<IVsPackageSourceProvider> GetPackageSourceProviderAsync() { Contract.ThrowIfFalse(IsEnabled); if (!_packageSourceProvider.IsValueCreated) { // Switch to background thread for known assembly load await TaskScheduler.Default; } return _packageSourceProvider.Value; } protected override async Task EnableServiceAsync(CancellationToken cancellationToken) { if (!IsEnabled) { return; } // Continue on captured context since EnableServiceAsync is part of a UI thread initialization sequence var packageSourceProvider = await GetPackageSourceProviderAsync().ConfigureAwait(true); // Start listening to additional events workspace changes. _workspace.WorkspaceChanged += OnWorkspaceChanged; packageSourceProvider.SourcesChanged += OnSourceProviderSourcesChanged; } protected override void StartWorking() { this.AssertIsForeground(); if (!this.IsEnabled) { return; } OnSourceProviderSourcesChanged(this, EventArgs.Empty); Contract.ThrowIfNull(_workQueue, "We should only be called after EnableService is called"); // Kick off an initial set of work that will analyze the entire solution. _workQueue.AddWork((solutionChanged: true, changedProject: null)); } private void OnSourceProviderSourcesChanged(object sender, EventArgs e) { lock (_gate) { // If the existing _packageSourcesTask is null, that means no one has asked us about package sources // yet. So no need for us to do anything if that's true. We'll just continue waiting until first // asked. However, if it's not null, that means we have already been asked. In that case, proactively // get the new set of sources so they're ready for the next time we're asked. if (_packageSourcesTask != null) _packageSourcesTask = Task.Run(() => GetPackageSourcesAsync(), this.DisposalToken); } PackageSourcesChanged?.Invoke(this, EventArgs.Empty); } public bool TryInstallPackage( Workspace workspace, DocumentId documentId, string source, string packageName, string? version, bool includePrerelease, IProgressTracker progressTracker, CancellationToken cancellationToken) { return this.ThreadingContext.JoinableTaskFactory.Run( () => TryInstallPackageAsync(workspace, documentId, source, packageName, version, includePrerelease, progressTracker, cancellationToken)); } private async Task<bool> TryInstallPackageAsync( Workspace workspace, DocumentId documentId, string source, string packageName, string? version, bool includePrerelease, IProgressTracker progressTracker, CancellationToken cancellationToken) { // The 'workspace == _workspace' line is probably not necessary. However, we include // it just to make sure that someone isn't trying to install a package into a workspace // other than the VisualStudioWorkspace. if (workspace == _workspace && _workspace != null && IsEnabled) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var projectId = documentId.ProjectId; var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(SDTE)); var dteProject = _workspace.TryGetDTEProject(projectId); var projectGuid = _workspace.GetProjectGuid(projectId); if (dteProject != null && projectGuid != Guid.Empty) { var undoManager = _editorAdaptersFactoryService.TryGetUndoManager( workspace, documentId, cancellationToken); return await TryInstallAndAddUndoActionAsync( source, packageName, version, includePrerelease, projectGuid, dte, dteProject, undoManager, progressTracker, cancellationToken).ConfigureAwait(false); } } return false; } private async Task<bool> TryInstallPackageAsync( string source, string packageName, string? version, bool includePrerelease, Guid projectGuid, EnvDTE.DTE dte, EnvDTE.Project dteProject, IProgressTracker progressTracker, CancellationToken cancellationToken) { Contract.ThrowIfFalse(IsEnabled); var description = string.Format(ServicesVSResources.Installing_0, packageName); progressTracker.Description = description; await UpdateStatusBarAsync(dte, description, cancellationToken).ConfigureAwait(false); try { return await this.PerformNuGetProjectServiceWorkAsync(async (nugetService, cancellationToken) => { // explicitly switch to BG thread to do the installation as nuget installer APIs are free threaded. await TaskScheduler.Default; var installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); if (installedPackagesMap.ContainsKey(packageName)) return false; // Once we start the installation, we can't cancel anymore. cancellationToken = default; if (version == null) { _packageInstaller.Value.InstallLatestPackage( source, dteProject, packageName, includePrerelease, ignoreDependencies: false); } else { _packageInstaller.Value.InstallPackage( source, dteProject, packageName, version, ignoreDependencies: false); } installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); var installedVersion = installedPackagesMap.TryGetValue(packageName, out var result) ? result : null; await UpdateStatusBarAsync( dte, string.Format(ServicesVSResources.Installing_0_completed, GetStatusBarText(packageName, installedVersion)), cancellationToken).ConfigureAwait(false); return true; }, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { await UpdateStatusBarAsync(dte, ServicesVSResources.Package_install_canceled, cancellationToken).ConfigureAwait(false); return false; } catch (Exception e) when (FatalError.ReportAndCatch(e)) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); dte.StatusBar.Text = string.Format(ServicesVSResources.Package_install_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Installing_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); return false; } } private async Task UpdateStatusBarAsync(EnvDTE.DTE dte, string text, CancellationToken cancellationToken) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); dte.StatusBar.Text = text; } private static string GetStatusBarText(string packageName, string? installedVersion) => installedVersion == null ? packageName : $"{packageName} - {installedVersion}"; private async Task<bool> TryUninstallPackageAsync( string packageName, Guid projectGuid, EnvDTE.DTE dte, EnvDTE.Project dteProject, IProgressTracker progressTracker, CancellationToken cancellationToken) { Contract.ThrowIfFalse(IsEnabled); var description = string.Format(ServicesVSResources.Uninstalling_0, packageName); progressTracker.Description = description; await UpdateStatusBarAsync(dte, description, cancellationToken).ConfigureAwait(false); try { return await this.PerformNuGetProjectServiceWorkAsync(async (nugetService, cancellationToken) => { // explicitly switch to BG thread to do the installation as nuget installer APIs are free threaded. await TaskScheduler.Default; var installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); if (!installedPackagesMap.TryGetValue(packageName, out var installedVersion)) return false; cancellationToken.ThrowIfCancellationRequested(); // Once we start the installation, we can't cancel anymore. cancellationToken = default; _packageUninstaller.Value.UninstallPackage(dteProject, packageName, removeDependencies: true); await UpdateStatusBarAsync( dte, string.Format(ServicesVSResources.Uninstalling_0_completed, GetStatusBarText(packageName, installedVersion)), cancellationToken).ConfigureAwait(false); return true; }, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { await UpdateStatusBarAsync(dte, ServicesVSResources.Package_uninstall_canceled, cancellationToken).ConfigureAwait(false); return false; } catch (Exception e) when (FatalError.ReportAndCatch(e)) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); dte.StatusBar.Text = string.Format(ServicesVSResources.Package_uninstall_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Uninstalling_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); return false; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { ThisCanBeCalledOnAnyThread(); var solutionChanged = false; ProjectId? changedProject = null; switch (e.Kind) { default: // Nothing to do for any other events. return; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: changedProject = e.ProjectId; break; case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: solutionChanged = true; break; } Contract.ThrowIfNull(_workQueue, "We should only register for events after having create the WorkQueue"); _workQueue.AddWork((solutionChanged, changedProject)); } private ValueTask ProcessWorkQueueAsync( ImmutableArray<(bool solutionChanged, ProjectId? changedProject)> workQueue, CancellationToken cancellationToken) { ThisCanBeCalledOnAnyThread(); Contract.ThrowIfNull(_workQueue, "How could we be processing a workqueue change without a workqueue?"); // If we've been disconnected, then there's no point proceeding. if (_workspace == null || !IsEnabled) return ValueTaskFactory.CompletedTask; return ProcessWorkQueueWorkerAsync(workQueue, cancellationToken); } [MethodImpl(MethodImplOptions.NoInlining)] private async ValueTask ProcessWorkQueueWorkerAsync( ImmutableArray<(bool solutionChanged, ProjectId? changedProject)> workQueue, CancellationToken cancellationToken) { ThisCanBeCalledOnAnyThread(); await PerformNuGetProjectServiceWorkAsync<object>(async (nugetService, cancellationToken) => { // Figure out the entire set of projects to process. using var _ = PooledHashSet<ProjectId>.GetInstance(out var projectsToProcess); var solution = _workspace.CurrentSolution; AddProjectsToProcess(workQueue, solution, projectsToProcess); // And Process them one at a time. foreach (var projectId in projectsToProcess) { cancellationToken.ThrowIfCancellationRequested(); await ProcessProjectChangeAsync(nugetService, solution, projectId, cancellationToken).ConfigureAwait(false); } return null; }, cancellationToken).ConfigureAwait(false); } private async Task<T?> PerformNuGetProjectServiceWorkAsync<T>( Func<INuGetProjectService, CancellationToken, ValueTask<T?>> doWorkAsync, CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true). // GetServiceAsync/GetProxyAsync and the cast below are all explicitly documented as being BG thread safe. await TaskScheduler.Default; var serviceContainer = (IBrokeredServiceContainer?)await _asyncServiceProvider.GetServiceAsync(typeof(SVsBrokeredServiceContainer)).ConfigureAwait(false); var serviceBroker = serviceContainer?.GetFullAccessServiceBroker(); if (serviceBroker == null) return default; var nugetService = await serviceBroker.GetProxyAsync<INuGetProjectService>(NuGetServices.NuGetProjectServiceV1, cancellationToken: cancellationToken).ConfigureAwait(false); using (nugetService as IDisposable) { // If we didn't get a nuget service, there's nothing we can do in terms of querying the solution for // nuget info. if (nugetService == null) return default; return await doWorkAsync(nugetService, cancellationToken).ConfigureAwait(false); } } private void AddProjectsToProcess( ImmutableArray<(bool solutionChanged, ProjectId? changedProject)> workQueue, Solution solution, HashSet<ProjectId> projectsToProcess) { ThisCanBeCalledOnAnyThread(); // If we detected a solution change, then we need to process all projects. // This includes all the projects that we already know about, as well as // all the projects in the current workspace solution. if (workQueue.Any(t => t.solutionChanged)) { projectsToProcess.AddRange(solution.ProjectIds); projectsToProcess.AddRange(_projectToInstalledPackageAndVersion.Keys); } else { projectsToProcess.AddRange(workQueue.Select(t => t.changedProject).WhereNotNull()); } } private async Task ProcessProjectChangeAsync( INuGetProjectService nugetService, Solution solution, ProjectId projectId, CancellationToken cancellationToken) { ThisCanBeCalledOnAnyThread(); var project = solution.GetProject(projectId); // We really only need to know the NuGet status for managed language projects. // Also, the NuGet APIs may throw on some projects that don't implement the // full set of DTE APIs they expect. So we filter down to just C# and VB here // as we know these languages are safe to build up this index for. ProjectState? newState = null; if (project?.Language == LanguageNames.CSharp || project?.Language == LanguageNames.VisualBasic) { var projectGuid = _workspace.GetProjectGuid(projectId); if (projectGuid != Guid.Empty) { newState = await GetCurrentProjectStateAsync( nugetService, projectGuid, cancellationToken).ConfigureAwait(false); } } // If we weren't able to get the nuget state for the project (i.e. it's not a c#/vb project, or we got a // crash attempting to get nuget information). Mark this project as something that nuget-add-import is not // supported for. _projectToInstalledPackageAndVersion[projectId] = newState ?? ProjectState.Disabled; } private static async Task<ProjectState?> GetCurrentProjectStateAsync( INuGetProjectService nugetService, Guid projectGuid, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { var installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); return new ProjectState(installedPackagesMap); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private static async Task<ImmutableDictionary<string, string>> GetInstalledPackagesMapAsync(INuGetProjectService nugetService, Guid projectGuid, CancellationToken cancellationToken) { var installedPackagesResult = await nugetService.GetInstalledPackagesAsync(projectGuid, cancellationToken).ConfigureAwait(false); using var _ = PooledDictionary<string, string>.GetInstance(out var installedPackages); if (installedPackagesResult?.Status == InstalledPackageResultStatus.Successful) { foreach (var installedPackage in installedPackagesResult.Packages) installedPackages[installedPackage.Id] = installedPackage.Version; } var installedPackagesMap = installedPackages.ToImmutableDictionary(); return installedPackagesMap; } public bool IsInstalled(Workspace workspace, ProjectId projectId, string packageName) { ThisCanBeCalledOnAnyThread(); return _projectToInstalledPackageAndVersion.TryGetValue(projectId, out var installedPackages) && installedPackages.IsInstalled(packageName); } public ImmutableArray<string> GetInstalledVersions(string packageName) { ThisCanBeCalledOnAnyThread(); using var _ = PooledHashSet<string>.GetInstance(out var installedVersions); foreach (var state in _projectToInstalledPackageAndVersion.Values) { if (state.TryGetInstalledVersion(packageName, out var version)) installedVersions.Add(version); } // Order the versions with a weak heuristic so that 'newer' versions come first. // Essentially, we try to break the version on dots, and then we use a LogicalComparer // to try to more naturally order the things we see between the dots. var versionsAndSplits = installedVersions.Select(v => new { Version = v, Split = v.Split('.') }).ToList(); versionsAndSplits.Sort((v1, v2) => { var diff = CompareSplit(v1.Split, v2.Split); return diff != 0 ? diff : -v1.Version.CompareTo(v2.Version); }); return versionsAndSplits.Select(v => v.Version).ToImmutableArray(); } private int CompareSplit(string[] split1, string[] split2) { ThisCanBeCalledOnAnyThread(); for (int i = 0, n = Math.Min(split1.Length, split2.Length); i < n; i++) { // Prefer things that look larger. i.e. 7 should come before 6. // Use a logical string comparer so that 10 is understood to be // greater than 3. var diff = -LogicalStringComparer.Instance.Compare(split1[i], split2[i]); if (diff != 0) { return diff; } } // Choose the one with more parts. return split2.Length - split1.Length; } public ImmutableArray<Project> GetProjectsWithInstalledPackage(Solution solution, string packageName, string version) { ThisCanBeCalledOnAnyThread(); using var _ = ArrayBuilder<Project>.GetInstance(out var result); foreach (var (projectId, state) in _projectToInstalledPackageAndVersion) { if (state.TryGetInstalledVersion(packageName, out var installedVersion) && installedVersion == version) { var project = solution.GetProject(projectId); if (project != null) result.Add(project); } } return result.ToImmutable(); } public bool CanShowManagePackagesDialog() => TryGetOrLoadNuGetPackageManager(out _); private bool TryGetOrLoadNuGetPackageManager([NotNullWhen(true)] out IVsPackage? nugetPackageManager) { this.AssertIsForeground(); if (_nugetPackageManager != null) { nugetPackageManager = _nugetPackageManager; return true; } nugetPackageManager = null; var shell = (IVsShell)_serviceProvider.GetService(typeof(SVsShell)); if (shell == null) { return false; } var nugetGuid = new Guid("5fcc8577-4feb-4d04-ad72-d6c629b083cc"); shell.LoadPackage(ref nugetGuid, out nugetPackageManager); _nugetPackageManager = nugetPackageManager; return nugetPackageManager != null; } public void ShowManagePackagesDialog(string packageName) { if (!TryGetOrLoadNuGetPackageManager(out var nugetPackageManager)) { return; } // We're able to launch the package manager (with an item in its search box) by // using the IVsSearchProvider API that the NuGet package exposes. // // We get that interface for it and then pass it a SearchQuery that effectively // wraps the package name we're looking for. The NuGet package will then read // out that string and populate their search box with it. var extensionProvider = (IVsPackageExtensionProvider)nugetPackageManager; var extensionGuid = new Guid("042C2B4B-C7F7-49DB-B7A2-402EB8DC7892"); var emptyGuid = Guid.Empty; var searchProvider = (IVsSearchProvider)extensionProvider.CreateExtensionInstance(ref emptyGuid, ref extensionGuid); var task = searchProvider.CreateSearch(dwCookie: 1, pSearchQuery: new SearchQuery(packageName), pSearchCallback: this); task.Start(); } public void ReportProgress(IVsSearchTask pTask, uint dwProgress, uint dwMaxProgress) { } public void ReportComplete(IVsSearchTask pTask, uint dwResultsFound) { } public void ReportResult(IVsSearchTask pTask, IVsSearchItemResult pSearchItemResult) => pSearchItemResult.InvokeAction(); public void ReportResults(IVsSearchTask pTask, uint dwResults, IVsSearchItemResult[] pSearchItemResults) { } private class SearchQuery : IVsSearchQuery { public SearchQuery(string packageName) => this.SearchString = packageName; public string SearchString { get; } public uint ParseError => 0; public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens) => 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.ServiceBroker; using Microsoft.VisualStudio.Threading; using NuGet.VisualStudio; using NuGet.VisualStudio.Contracts; using Roslyn.Utilities; using SVsServiceProvider = Microsoft.VisualStudio.Shell.SVsServiceProvider; using VSUtilities = Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Packaging { /// <summary> /// Free threaded wrapper around the NuGet.VisualStudio STA package installer interfaces. /// We want to be able to make queries about packages from any thread. For example, the /// add-NuGet-reference feature wants to know what packages a project already has /// references to. NuGet.VisualStudio provides this information, but only in a COM STA /// manner. As we don't want our background work to bounce and block on the UI thread /// we have this helper class which queries the information on the UI thread and caches /// the data so it can be read from the background. /// </summary> [ExportWorkspaceService(typeof(IPackageInstallerService)), Shared] internal partial class PackageInstallerService : AbstractDelayStartedService, IPackageInstallerService, IVsSearchProviderCallback { // Proper name, should not be localized. private const string NugetTitle = "NuGet"; private readonly VSUtilities.IUIThreadOperationExecutor _operationExecutor; private readonly VisualStudioWorkspaceImpl _workspace; private readonly SVsServiceProvider _serviceProvider; private readonly Shell.IAsyncServiceProvider _asyncServiceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; private readonly IAsynchronousOperationListener _listener; private readonly Lazy<IVsPackageInstaller2>? _packageInstaller; private readonly Lazy<IVsPackageUninstaller>? _packageUninstaller; private readonly Lazy<IVsPackageSourceProvider>? _packageSourceProvider; private IVsPackage? _nugetPackageManager; /// <summary> /// Used to keep track of what types of changes we've seen so we can then determine what to refresh on the UI /// thread. If we hear about project changes, we only refresh that project. If we hear about a solution level /// change, we'll refresh all projects. /// </summary> /// <remarks> /// <c>solutionChanged == true iff changedProject == null</c> and <c>solutionChanged == false iff changedProject /// != null</c>. So technically having both values is redundant. However, i like the clarity of having both. /// </remarks> private readonly AsyncBatchingWorkQueue<(bool solutionChanged, ProjectId? changedProject)>? _workQueue; private readonly ConcurrentDictionary<ProjectId, ProjectState> _projectToInstalledPackageAndVersion = new(); /// <summary> /// Lock used to protect reads and writes of <see cref="_packageSourcesTask"/>. /// </summary> private readonly object _gate = new(); /// <summary> /// Task uses to compute the set of package sources on demand when asked the first time. The value will be /// computed and cached in the task. When this value changes, the task will simply be cleared out. /// </summary> private Task<ImmutableArray<PackageSource>>? _packageSourcesTask; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PackageInstallerService( IThreadingContext threadingContext, VSUtilities.IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListenerProvider listenerProvider, VisualStudioWorkspaceImpl workspace, SVsServiceProvider serviceProvider, [Import("Microsoft.VisualStudio.Shell.Interop.SAsyncServiceProvider")] object asyncServiceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService, [Import(AllowDefault = true)] Lazy<IVsPackageInstaller2>? packageInstaller, [Import(AllowDefault = true)] Lazy<IVsPackageUninstaller>? packageUninstaller, [Import(AllowDefault = true)] Lazy<IVsPackageSourceProvider>? packageSourceProvider) : base(threadingContext, workspace, SymbolSearchOptions.Enabled, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInNuGetPackages) { _operationExecutor = operationExecutor; _workspace = workspace; _serviceProvider = serviceProvider; // MEFv2 doesn't support type based contract for Import above and for this particular contract // (SAsyncServiceProvider) actual type cast doesn't work. (https://github.com/microsoft/vs-mef/issues/138) // workaround by getting the service as object and cast to actual interface _asyncServiceProvider = (Shell.IAsyncServiceProvider)asyncServiceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; _packageInstaller = packageInstaller; _packageUninstaller = packageUninstaller; _packageSourceProvider = packageSourceProvider; _listener = listenerProvider.GetListener(FeatureAttribute.PackageInstaller); // Setup the work queue to allow us to hear about flurries of changes and then respond to them in batches // every second. Note: we pass in EqualityComparer<...>.Default since we don't care about ordering, and // since once we hear about changes to a project (or the whole solution), we don't need to keep track if we // hear about the same thing in that batch window interval. _workQueue = new AsyncBatchingWorkQueue<(bool solutionChanged, ProjectId? changedProject)>( TimeSpan.FromSeconds(1), this.ProcessWorkQueueAsync, equalityComparer: EqualityComparer<(bool solutionChanged, ProjectId? changedProject)>.Default, _listener, this.DisposalToken); } public event EventHandler? PackageSourcesChanged; public ImmutableArray<PackageSource> TryGetPackageSources() { Task<ImmutableArray<PackageSource>> localPackageSourcesTask; lock (_gate) { if (_packageSourcesTask is null) _packageSourcesTask = Task.Run(() => GetPackageSourcesAsync(), this.DisposalToken); localPackageSourcesTask = _packageSourcesTask; } if (localPackageSourcesTask.Status == TaskStatus.RanToCompletion) { return localPackageSourcesTask.Result; } else { // The result was not available yet (or it was canceled/faulted). Just return an empty result to // signify we couldn't get this right now. return ImmutableArray<PackageSource>.Empty; } } private async Task<ImmutableArray<PackageSource>> GetPackageSourcesAsync() { await ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); try { if (_packageSourceProvider != null) return _packageSourceProvider.Value.GetSources(includeUnOfficial: true, includeDisabled: false).SelectAsArray(r => new PackageSource(r.Key, r.Value)); } catch (Exception ex) when (ex is InvalidDataException || ex is InvalidOperationException) { // These exceptions can happen when the nuget.config file is broken. } catch (ArgumentException ae) when (FatalError.ReportAndCatch(ae)) { // This exception can happen when the nuget.config file is broken, e.g. invalid credentials. // https://github.com/dotnet/roslyn/issues/40857 } return ImmutableArray<PackageSource>.Empty; } [MemberNotNullWhen(true, nameof(_packageInstaller))] [MemberNotNullWhen(true, nameof(_packageUninstaller))] [MemberNotNullWhen(true, nameof(_packageSourceProvider))] private bool IsEnabled { get { return _packageInstaller != null && _packageUninstaller != null && _packageSourceProvider != null; } } bool IPackageInstallerService.IsEnabled(ProjectId projectId) { if (!IsEnabled) { return false; } if (_projectToInstalledPackageAndVersion.TryGetValue(projectId, out var state)) { return state.IsEnabled; } // If we haven't scanned the project yet, assume that we're available for it. return true; } private async ValueTask<IVsPackageSourceProvider> GetPackageSourceProviderAsync() { Contract.ThrowIfFalse(IsEnabled); if (!_packageSourceProvider.IsValueCreated) { // Switch to background thread for known assembly load await TaskScheduler.Default; } return _packageSourceProvider.Value; } protected override async Task EnableServiceAsync(CancellationToken cancellationToken) { if (!IsEnabled) { return; } // Continue on captured context since EnableServiceAsync is part of a UI thread initialization sequence var packageSourceProvider = await GetPackageSourceProviderAsync().ConfigureAwait(true); // Start listening to additional events workspace changes. _workspace.WorkspaceChanged += OnWorkspaceChanged; packageSourceProvider.SourcesChanged += OnSourceProviderSourcesChanged; } protected override void StartWorking() { this.AssertIsForeground(); if (!this.IsEnabled) { return; } OnSourceProviderSourcesChanged(this, EventArgs.Empty); Contract.ThrowIfNull(_workQueue, "We should only be called after EnableService is called"); // Kick off an initial set of work that will analyze the entire solution. _workQueue.AddWork((solutionChanged: true, changedProject: null)); } private void OnSourceProviderSourcesChanged(object sender, EventArgs e) { lock (_gate) { // If the existing _packageSourcesTask is null, that means no one has asked us about package sources // yet. So no need for us to do anything if that's true. We'll just continue waiting until first // asked. However, if it's not null, that means we have already been asked. In that case, proactively // get the new set of sources so they're ready for the next time we're asked. if (_packageSourcesTask != null) _packageSourcesTask = Task.Run(() => GetPackageSourcesAsync(), this.DisposalToken); } PackageSourcesChanged?.Invoke(this, EventArgs.Empty); } public bool TryInstallPackage( Workspace workspace, DocumentId documentId, string source, string packageName, string? version, bool includePrerelease, IProgressTracker progressTracker, CancellationToken cancellationToken) { return this.ThreadingContext.JoinableTaskFactory.Run( () => TryInstallPackageAsync(workspace, documentId, source, packageName, version, includePrerelease, progressTracker, cancellationToken)); } private async Task<bool> TryInstallPackageAsync( Workspace workspace, DocumentId documentId, string source, string packageName, string? version, bool includePrerelease, IProgressTracker progressTracker, CancellationToken cancellationToken) { // The 'workspace == _workspace' line is probably not necessary. However, we include // it just to make sure that someone isn't trying to install a package into a workspace // other than the VisualStudioWorkspace. if (workspace == _workspace && _workspace != null && IsEnabled) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var projectId = documentId.ProjectId; var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(SDTE)); var dteProject = _workspace.TryGetDTEProject(projectId); var projectGuid = _workspace.GetProjectGuid(projectId); if (dteProject != null && projectGuid != Guid.Empty) { var undoManager = _editorAdaptersFactoryService.TryGetUndoManager( workspace, documentId, cancellationToken); return await TryInstallAndAddUndoActionAsync( source, packageName, version, includePrerelease, projectGuid, dte, dteProject, undoManager, progressTracker, cancellationToken).ConfigureAwait(false); } } return false; } private async Task<bool> TryInstallPackageAsync( string source, string packageName, string? version, bool includePrerelease, Guid projectGuid, EnvDTE.DTE dte, EnvDTE.Project dteProject, IProgressTracker progressTracker, CancellationToken cancellationToken) { Contract.ThrowIfFalse(IsEnabled); var description = string.Format(ServicesVSResources.Installing_0, packageName); progressTracker.Description = description; await UpdateStatusBarAsync(dte, description, cancellationToken).ConfigureAwait(false); try { return await this.PerformNuGetProjectServiceWorkAsync(async (nugetService, cancellationToken) => { // explicitly switch to BG thread to do the installation as nuget installer APIs are free threaded. await TaskScheduler.Default; var installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); if (installedPackagesMap.ContainsKey(packageName)) return false; // Once we start the installation, we can't cancel anymore. cancellationToken = default; if (version == null) { _packageInstaller.Value.InstallLatestPackage( source, dteProject, packageName, includePrerelease, ignoreDependencies: false); } else { _packageInstaller.Value.InstallPackage( source, dteProject, packageName, version, ignoreDependencies: false); } installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); var installedVersion = installedPackagesMap.TryGetValue(packageName, out var result) ? result : null; await UpdateStatusBarAsync( dte, string.Format(ServicesVSResources.Installing_0_completed, GetStatusBarText(packageName, installedVersion)), cancellationToken).ConfigureAwait(false); return true; }, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { await UpdateStatusBarAsync(dte, ServicesVSResources.Package_install_canceled, cancellationToken).ConfigureAwait(false); return false; } catch (Exception e) when (FatalError.ReportAndCatch(e)) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); dte.StatusBar.Text = string.Format(ServicesVSResources.Package_install_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Installing_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); return false; } } private async Task UpdateStatusBarAsync(EnvDTE.DTE dte, string text, CancellationToken cancellationToken) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); dte.StatusBar.Text = text; } private static string GetStatusBarText(string packageName, string? installedVersion) => installedVersion == null ? packageName : $"{packageName} - {installedVersion}"; private async Task<bool> TryUninstallPackageAsync( string packageName, Guid projectGuid, EnvDTE.DTE dte, EnvDTE.Project dteProject, IProgressTracker progressTracker, CancellationToken cancellationToken) { Contract.ThrowIfFalse(IsEnabled); var description = string.Format(ServicesVSResources.Uninstalling_0, packageName); progressTracker.Description = description; await UpdateStatusBarAsync(dte, description, cancellationToken).ConfigureAwait(false); try { return await this.PerformNuGetProjectServiceWorkAsync(async (nugetService, cancellationToken) => { // explicitly switch to BG thread to do the installation as nuget installer APIs are free threaded. await TaskScheduler.Default; var installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); if (!installedPackagesMap.TryGetValue(packageName, out var installedVersion)) return false; cancellationToken.ThrowIfCancellationRequested(); // Once we start the installation, we can't cancel anymore. cancellationToken = default; _packageUninstaller.Value.UninstallPackage(dteProject, packageName, removeDependencies: true); await UpdateStatusBarAsync( dte, string.Format(ServicesVSResources.Uninstalling_0_completed, GetStatusBarText(packageName, installedVersion)), cancellationToken).ConfigureAwait(false); return true; }, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { await UpdateStatusBarAsync(dte, ServicesVSResources.Package_uninstall_canceled, cancellationToken).ConfigureAwait(false); return false; } catch (Exception e) when (FatalError.ReportAndCatch(e)) { await this.ThreadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); dte.StatusBar.Text = string.Format(ServicesVSResources.Package_uninstall_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Uninstalling_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); return false; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { ThisCanBeCalledOnAnyThread(); var solutionChanged = false; ProjectId? changedProject = null; switch (e.Kind) { default: // Nothing to do for any other events. return; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: changedProject = e.ProjectId; break; case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: solutionChanged = true; break; } Contract.ThrowIfNull(_workQueue, "We should only register for events after having create the WorkQueue"); _workQueue.AddWork((solutionChanged, changedProject)); } private ValueTask ProcessWorkQueueAsync( ImmutableArray<(bool solutionChanged, ProjectId? changedProject)> workQueue, CancellationToken cancellationToken) { ThisCanBeCalledOnAnyThread(); Contract.ThrowIfNull(_workQueue, "How could we be processing a workqueue change without a workqueue?"); // If we've been disconnected, then there's no point proceeding. if (_workspace == null || !IsEnabled) return ValueTaskFactory.CompletedTask; return ProcessWorkQueueWorkerAsync(workQueue, cancellationToken); } [MethodImpl(MethodImplOptions.NoInlining)] private async ValueTask ProcessWorkQueueWorkerAsync( ImmutableArray<(bool solutionChanged, ProjectId? changedProject)> workQueue, CancellationToken cancellationToken) { ThisCanBeCalledOnAnyThread(); await PerformNuGetProjectServiceWorkAsync<object>(async (nugetService, cancellationToken) => { // Figure out the entire set of projects to process. using var _ = PooledHashSet<ProjectId>.GetInstance(out var projectsToProcess); var solution = _workspace.CurrentSolution; AddProjectsToProcess(workQueue, solution, projectsToProcess); // And Process them one at a time. foreach (var projectId in projectsToProcess) { cancellationToken.ThrowIfCancellationRequested(); await ProcessProjectChangeAsync(nugetService, solution, projectId, cancellationToken).ConfigureAwait(false); } return null; }, cancellationToken).ConfigureAwait(false); } private async Task<T?> PerformNuGetProjectServiceWorkAsync<T>( Func<INuGetProjectService, CancellationToken, ValueTask<T?>> doWorkAsync, CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true). // GetServiceAsync/GetProxyAsync and the cast below are all explicitly documented as being BG thread safe. await TaskScheduler.Default; var serviceContainer = (IBrokeredServiceContainer?)await _asyncServiceProvider.GetServiceAsync(typeof(SVsBrokeredServiceContainer)).ConfigureAwait(false); var serviceBroker = serviceContainer?.GetFullAccessServiceBroker(); if (serviceBroker == null) return default; var nugetService = await serviceBroker.GetProxyAsync<INuGetProjectService>(NuGetServices.NuGetProjectServiceV1, cancellationToken: cancellationToken).ConfigureAwait(false); using (nugetService as IDisposable) { // If we didn't get a nuget service, there's nothing we can do in terms of querying the solution for // nuget info. if (nugetService == null) return default; return await doWorkAsync(nugetService, cancellationToken).ConfigureAwait(false); } } private void AddProjectsToProcess( ImmutableArray<(bool solutionChanged, ProjectId? changedProject)> workQueue, Solution solution, HashSet<ProjectId> projectsToProcess) { ThisCanBeCalledOnAnyThread(); // If we detected a solution change, then we need to process all projects. // This includes all the projects that we already know about, as well as // all the projects in the current workspace solution. if (workQueue.Any(t => t.solutionChanged)) { projectsToProcess.AddRange(solution.ProjectIds); projectsToProcess.AddRange(_projectToInstalledPackageAndVersion.Keys); } else { projectsToProcess.AddRange(workQueue.Select(t => t.changedProject).WhereNotNull()); } } private async Task ProcessProjectChangeAsync( INuGetProjectService nugetService, Solution solution, ProjectId projectId, CancellationToken cancellationToken) { ThisCanBeCalledOnAnyThread(); var project = solution.GetProject(projectId); // We really only need to know the NuGet status for managed language projects. // Also, the NuGet APIs may throw on some projects that don't implement the // full set of DTE APIs they expect. So we filter down to just C# and VB here // as we know these languages are safe to build up this index for. ProjectState? newState = null; if (project?.Language == LanguageNames.CSharp || project?.Language == LanguageNames.VisualBasic) { var projectGuid = _workspace.GetProjectGuid(projectId); if (projectGuid != Guid.Empty) { newState = await GetCurrentProjectStateAsync( nugetService, projectGuid, cancellationToken).ConfigureAwait(false); } } // If we weren't able to get the nuget state for the project (i.e. it's not a c#/vb project, or we got a // crash attempting to get nuget information). Mark this project as something that nuget-add-import is not // supported for. _projectToInstalledPackageAndVersion[projectId] = newState ?? ProjectState.Disabled; } private static async Task<ProjectState?> GetCurrentProjectStateAsync( INuGetProjectService nugetService, Guid projectGuid, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { var installedPackagesMap = await GetInstalledPackagesMapAsync(nugetService, projectGuid, cancellationToken).ConfigureAwait(false); return new ProjectState(installedPackagesMap); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { return null; } } private static async Task<ImmutableDictionary<string, string>> GetInstalledPackagesMapAsync(INuGetProjectService nugetService, Guid projectGuid, CancellationToken cancellationToken) { var installedPackagesResult = await nugetService.GetInstalledPackagesAsync(projectGuid, cancellationToken).ConfigureAwait(false); using var _ = PooledDictionary<string, string>.GetInstance(out var installedPackages); if (installedPackagesResult?.Status == InstalledPackageResultStatus.Successful) { foreach (var installedPackage in installedPackagesResult.Packages) installedPackages[installedPackage.Id] = installedPackage.Version; } var installedPackagesMap = installedPackages.ToImmutableDictionary(); return installedPackagesMap; } public bool IsInstalled(Workspace workspace, ProjectId projectId, string packageName) { ThisCanBeCalledOnAnyThread(); return _projectToInstalledPackageAndVersion.TryGetValue(projectId, out var installedPackages) && installedPackages.IsInstalled(packageName); } public ImmutableArray<string> GetInstalledVersions(string packageName) { ThisCanBeCalledOnAnyThread(); using var _ = PooledHashSet<string>.GetInstance(out var installedVersions); foreach (var state in _projectToInstalledPackageAndVersion.Values) { if (state.TryGetInstalledVersion(packageName, out var version)) installedVersions.Add(version); } // Order the versions with a weak heuristic so that 'newer' versions come first. // Essentially, we try to break the version on dots, and then we use a LogicalComparer // to try to more naturally order the things we see between the dots. var versionsAndSplits = installedVersions.Select(v => new { Version = v, Split = v.Split('.') }).ToList(); versionsAndSplits.Sort((v1, v2) => { var diff = CompareSplit(v1.Split, v2.Split); return diff != 0 ? diff : -v1.Version.CompareTo(v2.Version); }); return versionsAndSplits.Select(v => v.Version).ToImmutableArray(); } private int CompareSplit(string[] split1, string[] split2) { ThisCanBeCalledOnAnyThread(); for (int i = 0, n = Math.Min(split1.Length, split2.Length); i < n; i++) { // Prefer things that look larger. i.e. 7 should come before 6. // Use a logical string comparer so that 10 is understood to be // greater than 3. var diff = -LogicalStringComparer.Instance.Compare(split1[i], split2[i]); if (diff != 0) { return diff; } } // Choose the one with more parts. return split2.Length - split1.Length; } public ImmutableArray<Project> GetProjectsWithInstalledPackage(Solution solution, string packageName, string version) { ThisCanBeCalledOnAnyThread(); using var _ = ArrayBuilder<Project>.GetInstance(out var result); foreach (var (projectId, state) in _projectToInstalledPackageAndVersion) { if (state.TryGetInstalledVersion(packageName, out var installedVersion) && installedVersion == version) { var project = solution.GetProject(projectId); if (project != null) result.Add(project); } } return result.ToImmutable(); } public bool CanShowManagePackagesDialog() => TryGetOrLoadNuGetPackageManager(out _); private bool TryGetOrLoadNuGetPackageManager([NotNullWhen(true)] out IVsPackage? nugetPackageManager) { this.AssertIsForeground(); if (_nugetPackageManager != null) { nugetPackageManager = _nugetPackageManager; return true; } nugetPackageManager = null; var shell = (IVsShell)_serviceProvider.GetService(typeof(SVsShell)); if (shell == null) { return false; } var nugetGuid = new Guid("5fcc8577-4feb-4d04-ad72-d6c629b083cc"); shell.LoadPackage(ref nugetGuid, out nugetPackageManager); _nugetPackageManager = nugetPackageManager; return nugetPackageManager != null; } public void ShowManagePackagesDialog(string packageName) { if (!TryGetOrLoadNuGetPackageManager(out var nugetPackageManager)) { return; } // We're able to launch the package manager (with an item in its search box) by // using the IVsSearchProvider API that the NuGet package exposes. // // We get that interface for it and then pass it a SearchQuery that effectively // wraps the package name we're looking for. The NuGet package will then read // out that string and populate their search box with it. var extensionProvider = (IVsPackageExtensionProvider)nugetPackageManager; var extensionGuid = new Guid("042C2B4B-C7F7-49DB-B7A2-402EB8DC7892"); var emptyGuid = Guid.Empty; var searchProvider = (IVsSearchProvider)extensionProvider.CreateExtensionInstance(ref emptyGuid, ref extensionGuid); var task = searchProvider.CreateSearch(dwCookie: 1, pSearchQuery: new SearchQuery(packageName), pSearchCallback: this); task.Start(); } public void ReportProgress(IVsSearchTask pTask, uint dwProgress, uint dwMaxProgress) { } public void ReportComplete(IVsSearchTask pTask, uint dwResultsFound) { } public void ReportResult(IVsSearchTask pTask, IVsSearchItemResult pSearchItemResult) => pSearchItemResult.InvokeAction(); public void ReportResults(IVsSearchTask pTask, uint dwResults, IVsSearchItemResult[] pSearchItemResults) { } private class SearchQuery : IVsSearchQuery { public SearchQuery(string packageName) => this.SearchString = packageName; public string SearchString { get; } public uint ParseError => 0; public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens) => 0; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/CSharpTest/Diagnostics/Suppression/SuppressionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Suppression { public abstract partial class CSharpSuppressionTests : AbstractSuppressionDiagnosticTest { protected override ParseOptions GetScriptOptions() => Options.Script; protected internal override string GetLanguage() => LanguageNames.CSharp; #region "Pragma disable tests" public abstract partial class CSharpPragmaWarningDisableSuppressionTests : CSharpSuppressionTests { protected sealed override int CodeActionIndex { get { return 0; } } public class CompilerDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) => Tuple.Create<DiagnosticAnalyzer, IConfigurationFixProvider>(null, new CSharpSuppressionCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirective() { await TestAsync( @" class Class { void Method() { [|int x = 0;|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} int x = 0; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [WorkItem(26015, "https://github.com/dotnet/roslyn/issues/26015")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundMultiLineStatement() { await TestAsync( @" class Class { void Method() { [|string x = @""multi line"";|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} string x = @""multi line""; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestMultilineStatementPragmaWarningDirective() { await TestAsync( @" class Class { void Method() { [|int x = 0 + 1;|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} int x = 0 #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} + 1; }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveWithExistingTrivia() { await TestAsync( @" class Class { void Method() { // Start comment previous line /* Start comment same line */ [|int x = 0;|] // End comment same line /* End comment next line */ } }", $@" class Class {{ void Method() {{ // Start comment previous line #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} /* Start comment same line */ int x = 0; // End comment same line #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} /* End comment next line */ }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(16681, "https://github.com/dotnet/roslyn/issues/16681")] public async Task TestPragmaWarningDirectiveWithDocumentationComment1() { await TestAsync( @" sealed class Class { /// <summary>Text</summary> [|protected void Method()|] { } }", $@" sealed class Class {{ /// <summary>Text</summary> #pragma warning disable CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} protected void Method() #pragma warning restore CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} {{ }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(16681, "https://github.com/dotnet/roslyn/issues/16681")] public async Task TestPragmaWarningDirectiveWithDocumentationComment2() { await TestAsync( @" sealed class Class { /// <summary>Text</summary> /// <remarks> /// <see cref=""[|Class2|]""/> /// </remarks> void Method() { } }", $@" sealed class Class {{ #pragma warning disable CS1574 // {CSharpResources.WRN_BadXMLRef_Title} /// <summary>Text</summary> /// <remarks> /// <see cref=""Class2""/> /// </remarks> void Method() #pragma warning restore CS1574 // {CSharpResources.WRN_BadXMLRef_Title} {{ }} }}", new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestMultipleInstancesOfPragmaWarningDirective() { await TestAsync( @" class Class { void Method() { [|int x = 0, y = 0;|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} int x = 0, y = 0; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(3311, "https://github.com/dotnet/roslyn/issues/3311")] public async Task TestNoDuplicateSuppressionCodeFixes() { var source = @" class Class { void Method() { [|int x = 0, y = 0; string s;|] } }"; var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions(source, parameters); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(new CSharpCompilerDiagnosticAnalyzer())); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.ExportProvider.GetExportedValue<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>()); var incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace); var suppressionProvider = CreateDiagnosticProviderAndFixer(workspace).Item2; var suppressionProviderFactory = new Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>(() => suppressionProvider, new CodeChangeProviderMetadata("SuppressionProvider", languages: new[] { LanguageNames.CSharp })); var fixService = new CodeFixService( diagnosticService, SpecializedCollections.EmptyEnumerable<Lazy<IErrorLoggerService>>(), SpecializedCollections.EmptyEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>(), SpecializedCollections.SingletonEnumerable(suppressionProviderFactory)); var document = GetDocumentAndSelectSpan(workspace, out var span); var diagnostics = await diagnosticService.GetDiagnosticsForSpanAsync(document, span); Assert.Equal(2, diagnostics.Where(d => d.Id == "CS0219").Count()); var allFixes = (await fixService.GetFixesAsync(document, span, includeConfigurationFixes: true, cancellationToken: CancellationToken.None)) .SelectMany(fixCollection => fixCollection.Fixes); var cs0219Fixes = allFixes.Where(fix => fix.PrimaryDiagnostic.Id == "CS0219").ToArray(); // Ensure that there are no duplicate suppression fixes. Assert.Equal(1, cs0219Fixes.Length); var cs0219EquivalenceKey = cs0219Fixes[0].Action.EquivalenceKey; Assert.NotNull(cs0219EquivalenceKey); // Ensure that there *is* a fix for the other warning and that it has a *different* // equivalence key so that it *doesn't* get de-duplicated Assert.Equal(1, diagnostics.Where(d => d.Id == "CS0168").Count()); var cs0168Fixes = allFixes.Where(fix => fix.PrimaryDiagnostic.Id == "CS0168"); var cs0168EquivalenceKey = cs0168Fixes.Single().Action.EquivalenceKey; Assert.NotNull(cs0168EquivalenceKey); Assert.NotEqual(cs0219EquivalenceKey, cs0168EquivalenceKey); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestErrorAndWarningScenario() { await TestAsync( @" class Class { void Method() { return 0; [|int x = ""0"";|] } }", $@" class Class {{ void Method() {{ return 0; #pragma warning disable CS0162 // {CSharpResources.WRN_UnreachableCode_Title} int x = ""0""; #pragma warning restore CS0162 // {CSharpResources.WRN_UnreachableCode_Title} }} }}"); } [WorkItem(956453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/956453")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestWholeFilePragmaWarningDirective() { await TestAsync( @"class Class { void Method() { [|int x = 0;|] } }", $@"#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} class Class {{ void Method() {{ int x = 0; }} }} #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title}"); } [WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionAroundSingleToken() { await TestAsync( @" using System; [Obsolete] class Session { } class Program { static void Main() { [|Session|] } }", $@" using System; [Obsolete] class Session {{ }} class Program {{ static void Main() {{ #pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} Session #pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} }} }}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia1() { await TestAsync( @" class Class { void Method() { // Comment // Comment [|#pragma abcde|] } // Comment }", $@" class Class {{ void Method() {{ // Comment // Comment #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abcde }} // Comment #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} }}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia2() { await TestAsync( @"[|#pragma abcde|]", $@"#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abcde #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia3() { await TestAsync( @"[|#pragma abcde|] ", $@"#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abcde #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia4() { await TestAsync( @" [|#pragma abc|] class C { } ", $@" #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abc class C {{ }} #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} "); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia5() { await TestAsync( @"class C1 { } [|#pragma abc|] class C2 { } class C3 { }", $@"class C1 {{ }} #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abc class C2 {{ }} #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} class C3 {{ }}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia6() { await TestAsync( @"class C1 { } class C2 { } /// <summary><see [|cref=""abc""|]/></summary> class C3 { } // comment // comment // comment", $@"class C1 {{ }} #pragma warning disable CS1574 // {CSharpResources.WRN_BadXMLRef_Title} class C2 {{ }} /// <summary><see cref=""abc""/></summary> class #pragma warning restore CS1574 // {CSharpResources.WRN_BadXMLRef_Title} C3 {{ }} // comment // comment // comment", CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)); } } public class UserHiddenDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestHiddenDiagnosticCannotBeSuppressed() { await TestMissingAsync( @" using System; class Class { int Method() { [|System.Int32 x = 0;|] return x; } }"); } } public partial class UserInfoDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Decsciptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic Title", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Decsciptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Decsciptor, classDecl.Identifier.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestInfoDiagnosticSuppressed() { await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } }"); } } public partial class FormattingDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new FormattingDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } protected override Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(TestWorkspace workspace, TestParameters parameters) { var solution = workspace.CurrentSolution; var compilationOptions = solution.Projects.Single().CompilationOptions; var specificDiagnosticOptions = new[] { KeyValuePairUtil.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions); var updatedSolution = solution.WithProjectCompilationOptions(solution.ProjectIds.Single(), compilationOptions); workspace.ChangeSolution(updatedSolution); return base.GetCodeActionsAsync(workspace, parameters); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(38587, "https://github.com/dotnet/roslyn/issues/38587")] public async Task TestFormattingDiagnosticSuppressed() { await TestAsync( @" using System; class Class { int Method() { [|int x = 0 ;|] } }", @" using System; class Class { int Method() { #pragma warning disable format int x = 0 ; #pragma warning restore format } }"); } } public class UserErrorDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestErrorDiagnosticCanBeSuppressed() { await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", @" using System; #pragma warning disable ErrorDiagnostic // ErrorDiagnostic class Class #pragma warning restore ErrorDiagnostic // ErrorDiagnostic { int Method() { int x = 0; } }"); } } public class DiagnosticWithBadIdSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { // Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here. protected override bool IncludeNoLocationDiagnostics => false; private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("@~DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestDiagnosticWithBadIdSuppressed() { // Diagnostics with bad/invalid ID are not reported. await TestMissingAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }"); } } } public partial class MultilineDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Decsciptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic Title", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Decsciptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Decsciptor, classDecl.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [WorkItem(2764, "https://github.com/dotnet/roslyn/issues/2764")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundMultilineDiagnostic() { await TestAsync( @" [|class Class { }|] ", $@" #pragma warning disable {UserDiagnosticAnalyzer.Decsciptor.Id} // {UserDiagnosticAnalyzer.Decsciptor.Title} class Class {{ }} #pragma warning restore {UserDiagnosticAnalyzer.Decsciptor.Id} // {UserDiagnosticAnalyzer.Decsciptor.Title} "); } } #endregion #region "SuppressMessageAttribute tests" public abstract partial class CSharpGlobalSuppressMessageSuppressionTests : CSharpSuppressionTests { protected sealed override int CodeActionIndex { get { return 1; } } public class CompilerDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) => Tuple.Create<DiagnosticAnalyzer, IConfigurationFixProvider>(null, new CSharpSuppressionCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestCompilerDiagnosticsCannotBeSuppressed() { // Another test verifies we have a pragma warning action for this source, this verifies there are no other suppression actions. await TestActionCountAsync( @" class Class { void Method() { [|int x = 0;|] } }", 1); } } public class FormattingDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return Tuple.Create<DiagnosticAnalyzer, IConfigurationFixProvider>( new FormattingDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } protected override Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(TestWorkspace workspace, TestParameters parameters) { var solution = workspace.CurrentSolution; var compilationOptions = solution.Projects.Single().CompilationOptions; var specificDiagnosticOptions = new[] { KeyValuePairUtil.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions); var updatedSolution = solution.WithProjectCompilationOptions(solution.ProjectIds.Single(), compilationOptions); workspace.ChangeSolution(updatedSolution); return base.GetCodeActionsAsync(workspace, parameters); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(38587, "https://github.com/dotnet/roslyn/issues/38587")] public async Task TestCompilerDiagnosticsCannotBeSuppressed() { // Another test verifies we have a pragma warning action for this source, this verifies there are no other suppression actions. await TestActionCountAsync( @" class Class { void Method() { [|int x = 0 ;|] } }", 1); } } public class UserHiddenDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestHiddenDiagnosticsCannotBeSuppressed() { await TestMissingAsync( @" using System; class Class { void Method() { [|System.Int32 x = 0;|] } }"); } } public partial class UserInfoDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration, SyntaxKind.EnumDeclaration, SyntaxKind.NamespaceDeclaration, SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.FieldDeclaration, SyntaxKind.EventDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, classDecl.Identifier.GetLocation())); break; case SyntaxKind.NamespaceDeclaration: var ns = (NamespaceDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, ns.Name.GetLocation())); break; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, method.Identifier.GetLocation())); break; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, property.Identifier.GetLocation())); break; case SyntaxKind.FieldDeclaration: var field = (FieldDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, field.Declaration.Variables.First().Identifier.GetLocation())); break; case SyntaxKind.EventDeclaration: var e = (EventDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, e.Identifier.GetLocation())); break; case SyntaxKind.EnumDeclaration: // Report diagnostic on each descendant comment trivia foreach (var trivia in context.Node.DescendantTrivia().Where(t => t.Kind() is SyntaxKind.SingleLineCommentTrivia or SyntaxKind.MultiLineCommentTrivia)) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, trivia.GetLocation())); } break; } } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(37529, "https://github.com/dotnet/roslyn/issues/37529")] public async Task GeneratedCodeShouldNotHaveTrailingWhitespace() { var expected = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "; Assert.All(Regex.Split(expected, "\r?\n"), line => Assert.False(HasTrailingWhitespace(line))); await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", expected); } private static bool HasTrailingWhitespace(string line) => line.LastOrNull() is char last && char.IsWhiteSpace(last); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(37529, "https://github.com/dotnet/roslyn/issues/37529")] public async Task GeneratedCodeShouldNotHaveLeadingBlankLines() { var expected = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "; var lines = Regex.Split(expected, "\r?\n"); Assert.False(string.IsNullOrWhiteSpace(lines.First())); await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(37529, "https://github.com/dotnet/roslyn/issues/37529")] public async Task GeneratedCodeShouldNotHaveMoreThanOneTrailingBlankLine() { var expected = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "; var lines = Regex.Split(expected, "\r?\n"); Assert.False(string.IsNullOrWhiteSpace(lines[lines.Length - 2])); await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType() { await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""~T:Class"")] [|class Class|] { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnNamespace() { await TestInRegularAndScriptAsync( @" using System; [|namespace N|] { class Class { int Method() { int x = 0; } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""namespace"", Target = ""~N:N"")] ", index: 1); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""namespace"", Target = ""~N:N"")] [|namespace N|] { class Class { int Method() { int x = 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnTypeInsideNamespace() { await TestAsync( @" using System; namespace N1 { namespace N2 { [|class Class|] { int Method() { int x = 0; } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:N1.N2.Class"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""~T:N1.N2.Class"")] namespace N1 { namespace N2 { [|class Class|] { int Method() { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnNestedType() { await TestAsync( @" using System; namespace N { class Generic<T> { [|class Class|] { int Method() { int x = 0; } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:N.Generic`1.Class"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""~T:N.Generic`1.Class"")] namespace N { class Generic<T> { [|class Class|] { int Method() { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnMethod() { await TestAsync( @" using System; namespace N { class Generic<T> { class Class { [|int Method() { int x = 0; }|] } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method()|] { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnOverloadedMethod() { await TestAsync( @" using System; namespace N { class Generic<T> { class Class { [|int Method(int y, ref char z) { int x = 0; }|] int Method() { int x = 0; } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method(int y, ref char z)|] { int x = 0; } int Method() { int x = 0; } } } }"); await TestAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method(int y, ref char z) { int x = 0; } int Method() { int x = 0; }|] } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnGenericMethod() { await TestAsync( @" using System; namespace N { class Generic<T> { class Class { [|int Method<U>(U u) { int x = 0; }|] } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method``1(``0)~System.Int32"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method``1(``0)~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method<U>(U u)|] { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnProperty() { await TestAsync( @" using System; namespace N { class Generic { class Class { [|int Property|] { get { int x = 0; } } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~P:N.Generic.Class.Property"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~P:N.Generic.Class.Property"")] namespace N { class Generic { class Class { [|int Property|] { get { int x = 0; } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnField() { await TestAsync( @" using System; class Class { [|int field = 0;|] }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:Class.field"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~F:Class.field"")] class Class { [|int field = 0;|] }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")] public async Task TestSuppressionOnTriviaBetweenFields() { await TestAsync( @" using System; // suppressions on field are not relevant. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:E.Field1"")] using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:E.Field2"")] enum E { [| Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields Field2 |] }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:E"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:E"")] enum E { [| Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields Field2 |] }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnField2() { await TestAsync( @" using System; class Class { int [|field = 0|], field2 = 1; }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:Class.field"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~F:Class.field"")] class Class { int [|field|] = 0, field2 = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnEvent() { await TestAsync( @" using System; public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text {get; private set;} // readonly } class Class { // Declare the delegate (if using non-generic pattern). public delegate void SampleEventHandler(object sender, SampleEventArgs e); // Declare the event. [|public event SampleEventHandler SampleEvent { add { } remove { } }|] }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~E:Class.SampleEvent"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~E:Class.SampleEvent"")] public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text {get; private set;} // readonly } class Class { // Declare the delegate (if using non-generic pattern). public delegate void SampleEventHandler(object sender, SampleEventArgs e); // Declare the event. [|public event SampleEventHandler SampleEvent|] { add { } remove { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithExistingGlobalSuppressionsDocument() { var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithExistingGlobalSuppressionsDocument2() { // Own custom file named GlobalSuppressions.cs var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ // My own file named GlobalSuppressions.cs. using System; class Class { } ]]> </Document> </Project> </Workspace>"; var expectedText = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithExistingGlobalSuppressionsDocument3() { // Own custom file named GlobalSuppressions.cs + existing GlobalSuppressions2.cs with global suppressions var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ // My own file named GlobalSuppressions.cs. using System; class Class { } ]]> </Document> <Document FilePath=""GlobalSuppressions2.cs""><![CDATA[// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() { var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@" using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithoutUsingDirectiveInExistingGlobalSuppressionsDocument() { var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@" using System.Diagnostics.CodeAnalysis; [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } } } public abstract class CSharpLocalSuppressMessageSuppressionTests : CSharpSuppressionTests { protected sealed override int CodeActionIndex { get { return 2; } } public class UserInfoDiagnosticSuppressionTests : CSharpLocalSuppressMessageSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration, SyntaxKind.NamespaceDeclaration, SyntaxKind.MethodDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())); break; case SyntaxKind.NamespaceDeclaration: var ns = (NamespaceDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())); break; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())); break; } } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType() { var initial = @" using System; // Some trivia /* More Trivia */ [|class Class|] { int Method() { int x = 0; } }"; var expected = $@" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType2() { // Type already has attributes. var initial = @" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] [|class Class|] { int Method() { int x = 0; } }"; var expected = $@" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType3() { // Type already has attributes with trailing trivia. var initial = @" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] /* Some More Trivia */ [|class Class|] { int Method() { int x = 0; } }"; var expected = $@" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] /* Some More Trivia */ class Class {{ int Method() {{ int x = 0; }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnTypeInsideNamespace() { var initial = @" using System; namespace N1 { namespace N2 { [|class Class|] { int Method() { int x = 0; } } } }"; var expected = $@" using System; namespace N1 {{ namespace N2 {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }} }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnNestedType() { var initial = @" using System; namespace N { class Generic<T> { [|class Class|] { int Method() { int x = 0; } } } }"; var expected = $@" using System; namespace N {{ class Generic<T> {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }} }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnMethod() { var initial = @" using System; namespace N { class Generic<T> { class Class { [|int Method()|] { int x = 0; } } } }"; var expected = $@" using System; namespace N {{ class Generic<T> {{ class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] int Method() {{ int x = 0; }} }} }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("int Method()", "[|int Method()|]"); await TestMissingAsync(expected); } } } #endregion #region NoLocation Diagnostics tests public partial class CSharpDiagnosticWithoutLocationSuppressionTests : CSharpSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("NoLocationDiagnostic", "NoLocationDiagnostic", "NoLocationDiagnostic", "NoLocationDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) => context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)); } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } protected override int CodeActionIndex { get { return 0; } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(1073825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073825")] public async Task TestDiagnosticWithoutLocationCanBeSuppressed() { await TestAsync( @"[||] using System; class Class { int Method() { int x = 0; } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""NoLocationDiagnostic"", ""NoLocationDiagnostic:NoLocationDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] "); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CSharp.Diagnostics.SimplifyTypeNames; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ErrorLogger; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Suppression { public abstract partial class CSharpSuppressionTests : AbstractSuppressionDiagnosticTest { protected override ParseOptions GetScriptOptions() => Options.Script; protected internal override string GetLanguage() => LanguageNames.CSharp; #region "Pragma disable tests" public abstract partial class CSharpPragmaWarningDisableSuppressionTests : CSharpSuppressionTests { protected sealed override int CodeActionIndex { get { return 0; } } public class CompilerDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) => Tuple.Create<DiagnosticAnalyzer, IConfigurationFixProvider>(null, new CSharpSuppressionCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirective() { await TestAsync( @" class Class { void Method() { [|int x = 0;|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} int x = 0; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [WorkItem(26015, "https://github.com/dotnet/roslyn/issues/26015")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundMultiLineStatement() { await TestAsync( @" class Class { void Method() { [|string x = @""multi line"";|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} string x = @""multi line""; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [WorkItem(56165, "https://github.com/dotnet/roslyn/issues/56165")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundMultiLineInterpolatedString() { await TestAsync( @" using System; [Obsolete] class Session { } class Class { void Method() { var s = $@"" hi {[|new Session()|]} ""; } }", $@" using System; [Obsolete] class Session {{ }} class Class {{ void Method() {{ #pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} var s = $@"" hi {{new Session()}} ""; #pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestMultilineStatementPragmaWarningDirective() { await TestAsync( @" class Class { void Method() { [|int x = 0 + 1;|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} int x = 0 + 1; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestMultilineStatementPragmaWarningDirective2() { await TestAsync( @" class Class { void Method() { [|int x = 0, y = 1;|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} int x = 0, y = 1; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveWithExistingTrivia() { await TestAsync( @" class Class { void Method() { // Start comment previous line /* Start comment same line */ [|int x = 0;|] // End comment same line /* End comment next line */ } }", $@" class Class {{ void Method() {{ // Start comment previous line #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} /* Start comment same line */ int x = 0; // End comment same line #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} /* End comment next line */ }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(16681, "https://github.com/dotnet/roslyn/issues/16681")] public async Task TestPragmaWarningDirectiveWithDocumentationComment1() { await TestAsync( @" sealed class Class { /// <summary>Text</summary> [|protected void Method()|] { } }", $@" sealed class Class {{ /// <summary>Text</summary> #pragma warning disable CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} protected void Method() #pragma warning restore CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} {{ }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningExpressionBodiedMember1() { await TestAsync( @" sealed class Class { [|protected int Method()|] => 1; }", $@" sealed class Class {{ #pragma warning disable CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} protected int Method() => 1; #pragma warning restore CS0628 // {CSharpResources.WRN_ProtectedInSealed_Title} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningExpressionBodiedMember2() { await TestAsync( @" using System; [Obsolete] class Session { } class Class { string Method() => @$""hi {[|new Session()|]} ""; }", $@" using System; [Obsolete] class Session {{ }} class Class {{ string Method() #pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} => @$""hi {{new Session()}} ""; #pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningExpressionBodiedLocalFunction() { await TestAsync( @" using System; [Obsolete] class Session { } class Class { void M() { string Method() => @$""hi {[|new Session()|]} ""; } }", $@" using System; [Obsolete] class Session {{ }} class Class {{ void M() {{ #pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} string Method() => @$""hi {{new Session()}} ""; #pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningExpressionBodiedLambda() { await TestAsync( @" using System; [Obsolete] class Session { } class Class { void M() { new Func<string>(() => @$""hi {[|new Session()|]} ""); } }", $@" using System; [Obsolete] class Session {{ }} class Class {{ void M() {{ #pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} new Func<string>(() => @$""hi {{new Session()}} ""); #pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(16681, "https://github.com/dotnet/roslyn/issues/16681")] public async Task TestPragmaWarningDirectiveWithDocumentationComment2() { await TestAsync( @" sealed class Class { /// <summary>Text</summary> /// <remarks> /// <see cref=""[|Class2|]""/> /// </remarks> void Method() { } }", $@" sealed class Class {{ #pragma warning disable CS1574 // {CSharpResources.WRN_BadXMLRef_Title} /// <summary>Text</summary> /// <remarks> /// <see cref=""Class2""/> /// </remarks> void Method() #pragma warning restore CS1574 // {CSharpResources.WRN_BadXMLRef_Title} {{ }} }}", new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestMultipleInstancesOfPragmaWarningDirective() { await TestAsync( @" class Class { void Method() { [|int x = 0, y = 0;|] } }", $@" class Class {{ void Method() {{ #pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} int x = 0, y = 0; #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} }} }}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(3311, "https://github.com/dotnet/roslyn/issues/3311")] public async Task TestNoDuplicateSuppressionCodeFixes() { var source = @" class Class { void Method() { [|int x = 0, y = 0; string s;|] } }"; var parameters = new TestParameters(); using var workspace = CreateWorkspaceFromOptions(source, parameters); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(new CSharpCompilerDiagnosticAnalyzer())); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(workspace.ExportProvider.GetExportedValue<IDiagnosticUpdateSourceRegistrationService>()); var diagnosticService = Assert.IsType<DiagnosticAnalyzerService>(workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>()); var incrementalAnalyzer = diagnosticService.CreateIncrementalAnalyzer(workspace); var suppressionProvider = CreateDiagnosticProviderAndFixer(workspace).Item2; var suppressionProviderFactory = new Lazy<IConfigurationFixProvider, CodeChangeProviderMetadata>(() => suppressionProvider, new CodeChangeProviderMetadata("SuppressionProvider", languages: new[] { LanguageNames.CSharp })); var fixService = new CodeFixService( diagnosticService, SpecializedCollections.EmptyEnumerable<Lazy<IErrorLoggerService>>(), SpecializedCollections.EmptyEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>(), SpecializedCollections.SingletonEnumerable(suppressionProviderFactory)); var document = GetDocumentAndSelectSpan(workspace, out var span); var diagnostics = await diagnosticService.GetDiagnosticsForSpanAsync(document, span); Assert.Equal(2, diagnostics.Where(d => d.Id == "CS0219").Count()); var allFixes = (await fixService.GetFixesAsync(document, span, includeConfigurationFixes: true, cancellationToken: CancellationToken.None)) .SelectMany(fixCollection => fixCollection.Fixes); var cs0219Fixes = allFixes.Where(fix => fix.PrimaryDiagnostic.Id == "CS0219").ToArray(); // Ensure that there are no duplicate suppression fixes. Assert.Equal(1, cs0219Fixes.Length); var cs0219EquivalenceKey = cs0219Fixes[0].Action.EquivalenceKey; Assert.NotNull(cs0219EquivalenceKey); // Ensure that there *is* a fix for the other warning and that it has a *different* // equivalence key so that it *doesn't* get de-duplicated Assert.Equal(1, diagnostics.Where(d => d.Id == "CS0168").Count()); var cs0168Fixes = allFixes.Where(fix => fix.PrimaryDiagnostic.Id == "CS0168"); var cs0168EquivalenceKey = cs0168Fixes.Single().Action.EquivalenceKey; Assert.NotNull(cs0168EquivalenceKey); Assert.NotEqual(cs0219EquivalenceKey, cs0168EquivalenceKey); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestErrorAndWarningScenario() { await TestAsync( @" class Class { void Method() { return 0; [|int x = ""0"";|] } }", $@" class Class {{ void Method() {{ return 0; #pragma warning disable CS0162 // {CSharpResources.WRN_UnreachableCode_Title} int x = ""0""; #pragma warning restore CS0162 // {CSharpResources.WRN_UnreachableCode_Title} }} }}"); } [WorkItem(956453, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/956453")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestWholeFilePragmaWarningDirective() { await TestAsync( @"class Class { void Method() { [|int x = 0;|] } }", $@"#pragma warning disable CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title} class Class {{ void Method() {{ int x = 0; }} }} #pragma warning restore CS0219 // {CSharpResources.WRN_UnreferencedVarAssg_Title}"); } [WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionAroundSingleToken() { await TestAsync( @" using System; [Obsolete] class Session { } class Program { static void Main() { [|Session|] } }", $@" using System; [Obsolete] class Session {{ }} class Program {{ static void Main() {{ #pragma warning disable CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} Session #pragma warning restore CS0612 // {CSharpResources.WRN_DeprecatedSymbol_Title} }} }}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia1() { await TestAsync( @" class Class { void Method() { // Comment // Comment [|#pragma abcde|] } // Comment }", $@" class Class {{ void Method() #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} {{ // Comment // Comment #pragma abcde }} // Comment #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} }}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia2() { await TestAsync( @"[|#pragma abcde|]", $@"#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abcde #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia3() { await TestAsync( @"[|#pragma abcde|] ", $@"#pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abcde #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia4() { await TestAsync( @" [|#pragma abc|] class C { } ", $@" #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abc class C {{ }} #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} "); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia5() { await TestAsync( @"class C1 { } [|#pragma abc|] class C2 { } class C3 { }", $@"class C1 {{ }} #pragma warning disable CS1633 // {CSharpResources.WRN_IllegalPragma_Title} #pragma abc class C2 {{ }} #pragma warning restore CS1633 // {CSharpResources.WRN_IllegalPragma_Title} class C3 {{ }}"); } [WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundTrivia6() { await TestAsync( @"class C1 { } class C2 { } /// <summary><see [|cref=""abc""|]/></summary> class C3 { } // comment // comment // comment", $@"class C1 {{ }} #pragma warning disable CS1574 // {CSharpResources.WRN_BadXMLRef_Title} class C2 {{ }} /// <summary><see cref=""abc""/></summary> class #pragma warning restore CS1574 // {CSharpResources.WRN_BadXMLRef_Title} C3 {{ }} // comment // comment // comment", CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)); } } public class UserHiddenDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestHiddenDiagnosticCannotBeSuppressed() { await TestMissingAsync( @" using System; class Class { int Method() { [|System.Int32 x = 0;|] return x; } }"); } } public partial class UserInfoDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Decsciptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic Title", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Decsciptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Decsciptor, classDecl.Identifier.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestInfoDiagnosticSuppressed() { await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } }"); } } public partial class FormattingDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new FormattingDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } protected override Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(TestWorkspace workspace, TestParameters parameters) { var solution = workspace.CurrentSolution; var compilationOptions = solution.Projects.Single().CompilationOptions; var specificDiagnosticOptions = new[] { KeyValuePairUtil.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions); var updatedSolution = solution.WithProjectCompilationOptions(solution.ProjectIds.Single(), compilationOptions); workspace.ChangeSolution(updatedSolution); return base.GetCodeActionsAsync(workspace, parameters); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(38587, "https://github.com/dotnet/roslyn/issues/38587")] public async Task TestFormattingDiagnosticSuppressed() { await TestAsync( @" using System; class Class { int Method() { [|int x = 0 ;|] } }", @" using System; class Class { int Method() { #pragma warning disable format int x = 0 ; #pragma warning restore format } }"); } } public class UserErrorDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.Error, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestErrorDiagnosticCanBeSuppressed() { await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", @" using System; #pragma warning disable ErrorDiagnostic // ErrorDiagnostic class Class #pragma warning restore ErrorDiagnostic // ErrorDiagnostic { int Method() { int x = 0; } }"); } } public class DiagnosticWithBadIdSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { // Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here. protected override bool IncludeNoLocationDiagnostics => false; private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("@~DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestDiagnosticWithBadIdSuppressed() { // Diagnostics with bad/invalid ID are not reported. await TestMissingAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }"); } } } public partial class MultilineDiagnosticSuppressionTests : CSharpPragmaWarningDisableSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Decsciptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic Title", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Decsciptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Decsciptor, classDecl.GetLocation())); } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [WorkItem(2764, "https://github.com/dotnet/roslyn/issues/2764")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestPragmaWarningDirectiveAroundMultilineDiagnostic() { await TestAsync( @" [|class Class { }|] ", $@" #pragma warning disable {UserDiagnosticAnalyzer.Decsciptor.Id} // {UserDiagnosticAnalyzer.Decsciptor.Title} class Class {{ }} #pragma warning restore {UserDiagnosticAnalyzer.Decsciptor.Id} // {UserDiagnosticAnalyzer.Decsciptor.Title} "); } } #endregion #region "SuppressMessageAttribute tests" public abstract partial class CSharpGlobalSuppressMessageSuppressionTests : CSharpSuppressionTests { protected sealed override int CodeActionIndex { get { return 1; } } public class CompilerDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) => Tuple.Create<DiagnosticAnalyzer, IConfigurationFixProvider>(null, new CSharpSuppressionCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestCompilerDiagnosticsCannotBeSuppressed() { // Another test verifies we have a pragma warning action for this source, this verifies there are no other suppression actions. await TestActionCountAsync( @" class Class { void Method() { [|int x = 0;|] } }", 1); } } public class FormattingDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return Tuple.Create<DiagnosticAnalyzer, IConfigurationFixProvider>( new FormattingDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } protected override Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(TestWorkspace workspace, TestParameters parameters) { var solution = workspace.CurrentSolution; var compilationOptions = solution.Projects.Single().CompilationOptions; var specificDiagnosticOptions = new[] { KeyValuePairUtil.Create(IDEDiagnosticIds.FormattingDiagnosticId, ReportDiagnostic.Warn) }; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions); var updatedSolution = solution.WithProjectCompilationOptions(solution.ProjectIds.Single(), compilationOptions); workspace.ChangeSolution(updatedSolution); return base.GetCodeActionsAsync(workspace, parameters); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(38587, "https://github.com/dotnet/roslyn/issues/38587")] public async Task TestCompilerDiagnosticsCannotBeSuppressed() { // Another test verifies we have a pragma warning action for this source, this verifies there are no other suppression actions. await TestActionCountAsync( @" class Class { void Method() { [|int x = 0 ;|] } }", 1); } } public class UserHiddenDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpSimplifyTypeNamesDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestHiddenDiagnosticsCannotBeSuppressed() { await TestMissingAsync( @" using System; class Class { void Method() { [|System.Int32 x = 0;|] } }"); } } public partial class UserInfoDiagnosticSuppressionTests : CSharpGlobalSuppressMessageSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration, SyntaxKind.EnumDeclaration, SyntaxKind.NamespaceDeclaration, SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.FieldDeclaration, SyntaxKind.EventDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, classDecl.Identifier.GetLocation())); break; case SyntaxKind.NamespaceDeclaration: var ns = (NamespaceDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, ns.Name.GetLocation())); break; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, method.Identifier.GetLocation())); break; case SyntaxKind.PropertyDeclaration: var property = (PropertyDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, property.Identifier.GetLocation())); break; case SyntaxKind.FieldDeclaration: var field = (FieldDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, field.Declaration.Variables.First().Identifier.GetLocation())); break; case SyntaxKind.EventDeclaration: var e = (EventDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(Descriptor, e.Identifier.GetLocation())); break; case SyntaxKind.EnumDeclaration: // Report diagnostic on each descendant comment trivia foreach (var trivia in context.Node.DescendantTrivia().Where(t => t.Kind() is SyntaxKind.SingleLineCommentTrivia or SyntaxKind.MultiLineCommentTrivia)) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, trivia.GetLocation())); } break; } } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(37529, "https://github.com/dotnet/roslyn/issues/37529")] public async Task GeneratedCodeShouldNotHaveTrailingWhitespace() { var expected = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "; Assert.All(Regex.Split(expected, "\r?\n"), line => Assert.False(HasTrailingWhitespace(line))); await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", expected); } private static bool HasTrailingWhitespace(string line) => line.LastOrNull() is char last && char.IsWhiteSpace(last); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(37529, "https://github.com/dotnet/roslyn/issues/37529")] public async Task GeneratedCodeShouldNotHaveLeadingBlankLines() { var expected = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "; var lines = Regex.Split(expected, "\r?\n"); Assert.False(string.IsNullOrWhiteSpace(lines.First())); await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(37529, "https://github.com/dotnet/roslyn/issues/37529")] public async Task GeneratedCodeShouldNotHaveMoreThanOneTrailingBlankLine() { var expected = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "; var lines = Regex.Split(expected, "\r?\n"); Assert.False(string.IsNullOrWhiteSpace(lines[lines.Length - 2])); await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType() { await TestAsync( @" using System; [|class Class|] { int Method() { int x = 0; } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""~T:Class"")] [|class Class|] { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnNamespace() { await TestInRegularAndScriptAsync( @" using System; [|namespace N|] { class Class { int Method() { int x = 0; } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""namespace"", Target = ""~N:N"")] ", index: 1); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""namespace"", Target = ""~N:N"")] [|namespace N|] { class Class { int Method() { int x = 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnTypeInsideNamespace() { await TestAsync( @" using System; namespace N1 { namespace N2 { [|class Class|] { int Method() { int x = 0; } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:N1.N2.Class"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""~T:N1.N2.Class"")] namespace N1 { namespace N2 { [|class Class|] { int Method() { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnNestedType() { await TestAsync( @" using System; namespace N { class Generic<T> { [|class Class|] { int Method() { int x = 0; } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:N.Generic`1.Class"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""~T:N.Generic`1.Class"")] namespace N { class Generic<T> { [|class Class|] { int Method() { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnMethod() { await TestAsync( @" using System; namespace N { class Generic<T> { class Class { [|int Method() { int x = 0; }|] } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method()|] { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnOverloadedMethod() { await TestAsync( @" using System; namespace N { class Generic<T> { class Class { [|int Method(int y, ref char z) { int x = 0; }|] int Method() { int x = 0; } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method(int y, ref char z)|] { int x = 0; } int Method() { int x = 0; } } } }"); await TestAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method(System.Int32,System.Char@)~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method(int y, ref char z) { int x = 0; } int Method() { int x = 0; }|] } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method~System.Int32"")] "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnGenericMethod() { await TestAsync( @" using System; namespace N { class Generic<T> { class Class { [|int Method<U>(U u) { int x = 0; }|] } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method``1(``0)~System.Int32"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~M:N.Generic`1.Class.Method``1(``0)~System.Int32"")] namespace N { class Generic<T> { class Class { [|int Method<U>(U u)|] { int x = 0; } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnProperty() { await TestAsync( @" using System; namespace N { class Generic { class Class { [|int Property|] { get { int x = 0; } } } } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~P:N.Generic.Class.Property"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~P:N.Generic.Class.Property"")] namespace N { class Generic { class Class { [|int Property|] { get { int x = 0; } } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnField() { await TestAsync( @" using System; class Class { [|int field = 0;|] }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:Class.field"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~F:Class.field"")] class Class { [|int field = 0;|] }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")] public async Task TestSuppressionOnTriviaBetweenFields() { await TestAsync( @" using System; // suppressions on field are not relevant. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:E.Field1"")] using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:E.Field2"")] enum E { [| Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields Field2 |] }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:E"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:E"")] enum E { [| Field1, // trailing trivia for comma token which doesn't belong to span of any of the fields Field2 |] }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnField2() { await TestAsync( @" using System; class Class { int [|field = 0|], field2 = 1; }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~F:Class.field"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~F:Class.field"")] class Class { int [|field|] = 0, field2 = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnEvent() { await TestAsync( @" using System; public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text {get; private set;} // readonly } class Class { // Declare the delegate (if using non-generic pattern). public delegate void SampleEventHandler(object sender, SampleEventArgs e); // Declare the event. [|public event SampleEventHandler SampleEvent { add { } remove { } }|] }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~E:Class.SampleEvent"")] "); // Also verify that the added attribute does indeed suppress the diagnostic. await TestMissingAsync( @" using System; using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""member"", Target = ""~E:Class.SampleEvent"")] public class SampleEventArgs { public SampleEventArgs(string s) { Text = s; } public String Text {get; private set;} // readonly } class Class { // Declare the delegate (if using non-generic pattern). public delegate void SampleEventHandler(object sender, SampleEventArgs e); // Declare the event. [|public event SampleEventHandler SampleEvent|] { add { } remove { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithExistingGlobalSuppressionsDocument() { var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithExistingGlobalSuppressionsDocument2() { // Own custom file named GlobalSuppressions.cs var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ // My own file named GlobalSuppressions.cs. using System; class Class { } ]]> </Document> </Project> </Workspace>"; var expectedText = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithExistingGlobalSuppressionsDocument3() { // Own custom file named GlobalSuppressions.cs + existing GlobalSuppressions2.cs with global suppressions var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ // My own file named GlobalSuppressions.cs. using System; class Class { } ]]> </Document> <Document FilePath=""GlobalSuppressions2.cs""><![CDATA[// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() { var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@" using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionWithoutUsingDirectiveInExistingGlobalSuppressionsDocument() { var initialMarkup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System; class Class { } [|class Class2|] { } ]]> </Document> <Document FilePath=""GlobalSuppressions.cs""><![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] ]]> </Document> </Project> </Workspace>"; var expectedText = $@" using System.Diagnostics.CodeAnalysis; [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""<Pending>"", Scope = ""type"", Target = ""Class"")] [assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] "; await TestAsync(initialMarkup, expectedText); } } } public abstract class CSharpLocalSuppressMessageSuppressionTests : CSharpSuppressionTests { protected sealed override int CodeActionIndex { get { return 2; } } public class UserInfoDiagnosticSuppressionTests : CSharpLocalSuppressMessageSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration, SyntaxKind.NamespaceDeclaration, SyntaxKind.MethodDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.ClassDeclaration: var classDecl = (ClassDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())); break; case SyntaxKind.NamespaceDeclaration: var ns = (NamespaceDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())); break; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)context.Node; context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())); break; } } } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType() { var initial = @" using System; // Some trivia /* More Trivia */ [|class Class|] { int Method() { int x = 0; } }"; var expected = $@" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType2() { // Type already has attributes. var initial = @" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] [|class Class|] { int Method() { int x = 0; } }"; var expected = $@" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnSimpleType3() { // Type already has attributes with trailing trivia. var initial = @" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] /* Some More Trivia */ [|class Class|] { int Method() { int x = 0; } }"; var expected = $@" using System; // Some trivia /* More Trivia */ [System.Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification = ""<Pending>"")] [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] /* Some More Trivia */ class Class {{ int Method() {{ int x = 0; }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnTypeInsideNamespace() { var initial = @" using System; namespace N1 { namespace N2 { [|class Class|] { int Method() { int x = 0; } } } }"; var expected = $@" using System; namespace N1 {{ namespace N2 {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }} }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnNestedType() { var initial = @" using System; namespace N { class Generic<T> { [|class Class|] { int Method() { int x = 0; } } } }"; var expected = $@" using System; namespace N {{ class Generic<T> {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] class Class {{ int Method() {{ int x = 0; }} }} }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("class Class", "[|class Class|]"); await TestMissingAsync(expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestSuppressionOnMethod() { var initial = @" using System; namespace N { class Generic<T> { class Class { [|int Method()|] { int x = 0; } } } }"; var expected = $@" using System; namespace N {{ class Generic<T> {{ class Class {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] int Method() {{ int x = 0; }} }} }} }}"; await TestAsync(initial, expected); // Also verify that the added attribute does indeed suppress the diagnostic. expected = expected.Replace("int Method()", "[|int Method()|]"); await TestMissingAsync(expected); } } } #endregion #region NoLocation Diagnostics tests public partial class CSharpDiagnosticWithoutLocationSuppressionTests : CSharpSuppressionTests { private class UserDiagnosticAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("NoLocationDiagnostic", "NoLocationDiagnostic", "NoLocationDiagnostic", "NoLocationDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor); } } public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) => context.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)); } internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } protected override int CodeActionIndex { get { return 0; } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [WorkItem(1073825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1073825")] public async Task TestDiagnosticWithoutLocationCanBeSuppressed() { await TestAsync( @"[||] using System; class Class { int Method() { int x = 0; } }", $@"// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage(""NoLocationDiagnostic"", ""NoLocationDiagnostic:NoLocationDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] "); } } #endregion } }
1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Suppression Public MustInherit Class VisualBasicSuppressionTests Inherits AbstractSuppressionDiagnosticTest Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overrides Function MassageActions(ByVal actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return actions(0).NestedCodeActions End Function Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function #Region "Pragma disable tests" Public MustInherit Class VisualBasicPragmaWarningDisableSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 0 End Get End Property Public Class CompilerDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirective() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() [|Dim x As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable [|Dim x As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective1() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() [|Dim x _ As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x _ As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable [|Dim x _ As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective2() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) If i < [|j.MaxValue|] AndAlso i > 0 Then Console.WriteLine(i) End If End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} If i < j.MaxValue AndAlso i > 0 Then #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Console.WriteLine(i) End If End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance If i < [|j.MaxValue|] AndAlso i > 0 Then #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Console.WriteLine(i) End If End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective3() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) If i > 0 AndAlso i < [|j.MaxValue|] Then Console.WriteLine(i) End If End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} If i > 0 AndAlso i < j.MaxValue Then #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Console.WriteLine(i) End If End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance If i > 0 AndAlso i < [|j.MaxValue|] Then #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Console.WriteLine(i) End If End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective4() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim [|x As Integer|], y As Integer End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer, y As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable Dim [|x As Integer|], y As Integer #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective5() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim x As Integer, [|y As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer, y As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable Dim x As Integer, [|y As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective6() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) Dim x = <root> <condition value=<%= i < [|j.MaxValue|] %>/> </root> End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Dim x = <root> <condition value=<%= i < j.MaxValue %>/> </root> #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Dim x = <root> <condition value=<%= i < [|j.MaxValue|] %>/> </root> #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective7() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(j As Short) Dim x = From i As Integer In {} Where i < [|j.MaxValue|] Select i End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Dim x = From i As Integer In {{}} Where i < j.MaxValue Select i #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Dim x = From i As Integer In {} Where i < [|j.MaxValue|] Select i #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveWithExistingTrivia() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() ' Trivia previous line [|Dim x As Integer|] ' Trivia same line ' Trivia next line End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() ' Trivia previous line #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer ' Trivia same line #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} ' Trivia next line End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() ' Trivia previous line #Disable Warning BC42024 ' Unused local variable [|Dim x As Integer|] ' Trivia same line #Enable Warning BC42024 ' Unused local variable ' Trivia next line End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionAroundSingleToken() As Task Dim source = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main [|C|] End Sub End Module]]> Dim expected = $" Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title} C #Enable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title} End Sub End Module" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' Type or member is obsolete [|C|] #Enable Warning BC40008 ' Type or member is obsolete End Sub End Module]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia1() As Task Dim source = <![CDATA[ Class C ' Comment ' Comment ''' <summary><see [|cref="abc"|]/></summary> Sub M() ' Comment End Sub End Class]]> Dim expected = $" Class C ' Comment ' Comment #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} ''' <summary><see cref=""abc""/></summary> Sub M() ' Comment #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} End Sub End Class" Dim enableDocCommentProcessing = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose) Await TestAsync(source.Value, expected, enableDocCommentProcessing) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = $" Class C ' Comment ' Comment #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} ''' <summary><see [|cref=""abc""|]/></summary> Sub M() ' Comment #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} End Sub End Class" Await TestMissingAsync(fixedSource, New TestParameters(enableDocCommentProcessing)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia2() As Task Dim source = <![CDATA['''[|<summary></summary>|]]]> Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title} '''<summary></summary> #Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia3() As Task Dim source = <![CDATA[ '''[|<summary></summary>|] ]]> Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title} '''<summary></summary> #Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia4() As Task Dim source = <![CDATA[ '''<summary><see [|cref="abc"|]/></summary> Class C : End Class ]]> Dim expected = $" #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} '''<summary><see cref=""abc""/></summary> Class C : End Class #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} " Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia5() As Task Dim source = <![CDATA[class C1 : End Class '''<summary><see [|cref="abc"|]/></summary> Class C2 : End Class Class C3 : End Class]]> Dim expected = $"class C1 : End Class #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} '''<summary><see cref=""abc""/></summary> Class C2 : End Class #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} Class C3 : End Class" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia6() As Task Dim source = <![CDATA[class C1 : End Class Class C2 : End Class [|'''|] Class C3 : End Class]]> Dim expected = $"class C1 : End Class #Disable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title} Class C2 : End Class ''' #Enable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title} Class C3 : End Class" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function End Class Public Class UserHiddenDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestHiddenDiagnosticCannotBeSuppressed() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim i as [|System.Int32|] = 0 Console.WriteLine(i) End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestInfoDiagnosticSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning InfoDiagnostic ' InfoDiagnostic Class C #Enable Warning InfoDiagnostic ' InfoDiagnostic Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning InfoDiagnostic ' InfoDiagnostic [|Class C|] #Enable Warning InfoDiagnostic ' InfoDiagnostic Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class Public Class DiagnosticWithBadIdSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Protected Overrides ReadOnly Property IncludeNoLocationDiagnostics As Boolean Get ' Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here. Return False End Get End Property Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("#$DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestDiagnosticWithBadIdSuppressed() As Task ' Diagnostics with bad/invalid ID are not reported. Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserWarningDiagnosticWithNameMatchingKeywordSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("REm", "REm Title", "REm", "REm", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestWarningDiagnosticWithNameMatchingKeywordSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning [REm] ' REm Title Class C #Enable Warning [REm] ' REm Title Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning [REm] ' REm Title [|Class C|] #Enable Warning [REm] ' REm Title Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class Public Class UserErrorDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.[Error], isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestErrorDiagnosticCanBeSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning ErrorDiagnostic ' ErrorDiagnostic Class C #Enable Warning ErrorDiagnostic ' ErrorDiagnostic Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning ErrorDiagnostic ' ErrorDiagnostic [|Class C|] #Enable Warning ErrorDiagnostic ' ErrorDiagnostic Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class End Class #End Region #Region "SuppressMessageAttribute tests" Public MustInherit Class VisualBasicGlobalSuppressMessageSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 1 End Get End Property Public Class CompilerDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestCompilerDiagnosticsCannotBeSuppressed() As Task Dim source = <![CDATA[ Class Class1 Sub Method() [|Dim x|] End Sub End Class]]> Await TestActionCountAsync(source.Value, 1) End Function End Class Public Class UserHiddenDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestHiddenDiagnosticsCannotBeSuppressed() As Task Dim source = <![CDATA[ Imports System Class Class1 Sub Method() [|Dim x As System.Int32 = 0|] End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Select Case context.Node.Kind() Case SyntaxKind.ClassStatement Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) Exit Select Case SyntaxKind.NamespaceStatement Dim ns = DirectCast(context.Node, NamespaceStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())) Exit Select Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(context.Node, MethodStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())) Exit Select Case SyntaxKind.PropertyStatement Dim p = DirectCast(context.Node, PropertyStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation())) Exit Select Case SyntaxKind.FieldDeclaration Dim f = DirectCast(context.Node, FieldDeclarationSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation())) Exit Select Case SyntaxKind.EventStatement Dim e = DirectCast(context.Node, EventStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation())) Exit Select End Select End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType() As Task Dim source = <![CDATA[ Imports System [|Class Class1|] Sub Method() Dim x End Sub End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")> [|Class Class1|] Sub Method() Dim x End Sub End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNamespace() As Task Dim source = <![CDATA[ Imports System [|Namespace N|] Class Class1 Sub Method() Dim x End Sub End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")> " Await TestInRegularAndScriptAsync(source.Value, expected, index:=1) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")> [|Namespace N|] Class Class1 Sub Method() Dim x End Sub End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnTypeInsideNamespace() As Task Dim source = <![CDATA[ Imports System Namespace N1 Namespace N2 [|Class Class1|] Sub Method() Dim x End Sub End Class End Namespace End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")> Namespace N1 Namespace N2 [|Class Class1|] Sub Method() Dim x End Sub End Class End Namespace End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNestedType() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) [|Class Class1|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")> Namespace N Class Generic(Of T) [|Class Class1|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method() Dim x End Sub|] End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method() Dim x End Sub|] End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnOverloadedMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method(y as Integer, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method(y as Integer, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnGenericMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method(Of U)(y as U, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method(Of U)(y as U, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnProperty() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic Private Class C [|Private ReadOnly Property P() As Integer|] Get Dim x As Integer = 0 End Get End Property End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")> Namespace N Class Generic Private Class C [|Private ReadOnly Property P() As Integer|] Get Dim x As Integer = 0 End Get End Property End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnField() As Task Dim source = <![CDATA[ Imports System Class C [|Private ReadOnly F As Integer|] End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")> Class C [|Private ReadOnly F As Integer|] End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnEvent() As Task Dim source = <![CDATA[ Imports System Public Class SampleEventArgs Public Sub New(s As String) Text = s End Sub Public Property Text() As [String] Get Return m_Text End Get Private Set m_Text = Value End Set End Property Private m_Text As [String] End Class Class C ' Declare the delegate (if using non-generic pattern). Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs) ' Declare the event. [|Public Custom Event SampleEvent As SampleEventHandler|] AddHandler(ByVal value As SampleEventHandler) End AddHandler RemoveHandler(ByVal value As SampleEventHandler) End RemoveHandler End Event End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")> Public Class SampleEventArgs Public Sub New(s As String) Text = s End Sub Public Property Text() As [String] Get Return m_Text End Get Private Set m_Text = Value End Set End Property Private m_Text As [String] End Class Class C ' Declare the delegate (if using non-generic pattern). Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs) ' Declare the event. [|Public Custom Event SampleEvent As SampleEventHandler|] AddHandler(ByVal value As SampleEventHandler) End AddHandler RemoveHandler(ByVal value As SampleEventHandler) End RemoveHandler End Event End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument() As Task Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument2() As Task ' Own custom file named GlobalSuppressions.cs Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ ' My own file named GlobalSuppressions.vb Class Class3 End Class ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument3() As Task ' Own custom file named GlobalSuppressions.vb + existing GlobalSuppressions2.vb with global suppressions Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ ' My own file named GlobalSuppressions.vb Class Class3 End Class ]]> </Document> <Document FilePath="GlobalSuppressions2.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() As Task Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $" Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function End Class End Class Public MustInherit Class VisualBasicLocalSuppressMessageSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 2 End Get End Property Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicLocalSuppressMessageSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Select Case context.Node.Kind() Case SyntaxKind.ClassStatement Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) Exit Select Case SyntaxKind.NamespaceStatement Dim ns = DirectCast(context.Node, NamespaceStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())) Exit Select Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(context.Node, MethodStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())) Exit Select Case SyntaxKind.PropertyStatement Dim p = DirectCast(context.Node, PropertyStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation())) Exit Select Case SyntaxKind.FieldDeclaration Dim f = DirectCast(context.Node, FieldDeclarationSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation())) Exit Select Case SyntaxKind.EventStatement Dim e = DirectCast(context.Node, EventStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation())) Exit Select End Select End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType() As Task Dim source = <![CDATA[ Imports System ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType2() As Task ' Type already has attributes. Dim source = <![CDATA[ Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType3() As Task ' Type has structured trivia. Dim source = <![CDATA[ Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType4() As Task ' Type has structured trivia and attributes. Dim source = <![CDATA[ Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnTypeInsideNamespace() As Task Dim source = <![CDATA[ Imports System Namespace N ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class End Namespace]]> Dim expected = $" Imports System Namespace N ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class End Namespace" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNestedType() As Task Dim source = <![CDATA[ Imports System Class Generic(Of T) ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class End Class]]> Dim expected = $" Imports System Class Generic(Of T) ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class End Class" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnMethod() As Task Dim source = <![CDATA[ Imports System Class Generic(Of T) Class C ' Some Trivia [|Sub Method() Dim x End Sub|] End Class End Class]]> Dim expected = $" Imports System Class Generic(Of T) Class C ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Sub Method() Dim x End Sub End Class End Class" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Sub Method()", "[|Sub Method()|]") Await TestMissingAsync(fixedSource) End Function End Class End Class #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Suppression Public MustInherit Class VisualBasicSuppressionTests Inherits AbstractSuppressionDiagnosticTest Protected Overrides Function GetScriptOptions() As ParseOptions Return TestOptions.Script End Function Protected Overrides Function MassageActions(ByVal actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return actions(0).NestedCodeActions End Function Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))) End Function Protected Overrides Function GetLanguage() As String Return LanguageNames.VisualBasic End Function #Region "Pragma disable tests" Public MustInherit Class VisualBasicPragmaWarningDisableSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 0 End Get End Property Public Class CompilerDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirective() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() [|Dim x As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable [|Dim x As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective1() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() [|Dim x _ As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x _ As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable [|Dim x _ As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective2() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) If i < [|j.MaxValue|] AndAlso i > 0 Then Console.WriteLine(i) End If End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} If i < j.MaxValue AndAlso i > 0 Then #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Console.WriteLine(i) End If End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance If i < [|j.MaxValue|] AndAlso i > 0 Then #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Console.WriteLine(i) End If End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective3() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) If i > 0 AndAlso i < [|j.MaxValue|] Then Console.WriteLine(i) End If End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} If i > 0 AndAlso i < j.MaxValue Then #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Console.WriteLine(i) End If End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance If i > 0 AndAlso i < [|j.MaxValue|] Then #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Console.WriteLine(i) End If End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective4() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim [|x As Integer|], y As Integer End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer, y As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable Dim [|x As Integer|], y As Integer #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective5() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim x As Integer, [|y As Integer|] End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer, y As Integer #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable Dim x As Integer, [|y As Integer|] #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective6() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) Dim x = <root> <condition value=<%= i < [|j.MaxValue|] %>/> </root> End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Dim x = <root> <condition value=<%= i < j.MaxValue %>/> </root> #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(i As Integer, j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Dim x = <root> <condition value=<%= i < [|j.MaxValue|] %>/> </root> #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective7() As Task Dim source = <![CDATA[ Imports System Class C Sub Method(j As Short) Dim x = From i As Integer In {} Where i < [|j.MaxValue|] Select i End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method(j As Short) #Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} Dim x = From i As Integer In {{}} Where i < j.MaxValue Select i #Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method(j As Short) #Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance Dim x = From i As Integer In {} Where i < [|j.MaxValue|] Select i #Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineStatementPragmaWarningDirective8() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() [|Dim x _ As Integer|] _ : Return End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x _ As Integer _ : Return #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() #Disable Warning BC42024 ' Unused local variable [|Dim x _ As Integer|] _ : Return #Enable Warning BC42024 ' Unused local variable End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(56165, "https://github.com/dotnet/roslyn/issues/56165")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestMultilineInterpolatedString() As Task Dim source = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main Dim s = $" Hi {[|new C()|]} " End Sub End Module]]> Dim expected = $" Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title} Dim s = $"" Hi {{new C()}} "" #Enable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title} End Sub End Module" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' Type or member is obsolete Dim s = $" Hi {[|new C()|]} " #Enable Warning BC40008 ' Type or member is obsolete End Sub End Module]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveWithExistingTrivia() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() ' Trivia previous line [|Dim x As Integer|] ' Trivia same line ' Trivia next line End Sub End Class]]> Dim expected = $" Imports System Class C Sub Method() ' Trivia previous line #Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} Dim x As Integer ' Trivia same line #Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title} ' Trivia next line End Sub End Class" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System Class C Sub Method() ' Trivia previous line #Disable Warning BC42024 ' Unused local variable [|Dim x As Integer|] ' Trivia same line #Enable Warning BC42024 ' Unused local variable ' Trivia next line End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionAroundSingleToken() As Task Dim source = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main [|C|] End Sub End Module]]> Dim expected = $" Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title} C #Enable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title} End Sub End Module" Await TestAsync(source.Value, expected) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System <Obsolete> Class C End Class Module Module1 Sub Main #Disable Warning BC40008 ' Type or member is obsolete [|C|] #Enable Warning BC40008 ' Type or member is obsolete End Sub End Module]]> Await TestMissingAsync(fixedSource.Value) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia1() As Task Dim source = <![CDATA[ Class C ' Comment ' Comment ''' <summary><see [|cref="abc"|]/></summary> Sub M() ' Comment End Sub End Class]]> Dim expected = $" Class C ' Comment ' Comment #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} ''' <summary><see cref=""abc""/></summary> Sub M() ' Comment #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} End Sub End Class" Dim enableDocCommentProcessing = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose) Await TestAsync(source.Value, expected, enableDocCommentProcessing) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = $" Class C ' Comment ' Comment #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} ''' <summary><see [|cref=""abc""|]/></summary> Sub M() ' Comment #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} End Sub End Class" Await TestMissingAsync(fixedSource, New TestParameters(enableDocCommentProcessing)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia2() As Task Dim source = <![CDATA['''[|<summary></summary>|]]]> Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title} '''<summary></summary> #Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia3() As Task Dim source = <![CDATA[ '''[|<summary></summary>|] ]]> Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title} '''<summary></summary> #Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia4() As Task Dim source = <![CDATA[ '''<summary><see [|cref="abc"|]/></summary> Class C : End Class ]]> Dim expected = $" #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} '''<summary><see cref=""abc""/></summary> Class C : End Class #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} " Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia5() As Task Dim source = <![CDATA[class C1 : End Class '''<summary><see [|cref="abc"|]/></summary> Class C2 : End Class Class C3 : End Class]]> Dim expected = $"class C1 : End Class #Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} '''<summary><see cref=""abc""/></summary> Class C2 : End Class #Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title} Class C3 : End Class" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function <WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestPragmaWarningDirectiveAroundTrivia6() As Task Dim source = <![CDATA[class C1 : End Class Class C2 : End Class [|'''|] Class C3 : End Class]]> Dim expected = $"class C1 : End Class #Disable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title} Class C2 : End Class ''' #Enable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title} Class C3 : End Class" Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)) End Function End Class Public Class UserHiddenDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestHiddenDiagnosticCannotBeSuppressed() As Task Dim source = <![CDATA[ Imports System Class C Sub Method() Dim i as [|System.Int32|] = 0 Console.WriteLine(i) End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestInfoDiagnosticSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning InfoDiagnostic ' InfoDiagnostic Class C #Enable Warning InfoDiagnostic ' InfoDiagnostic Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning InfoDiagnostic ' InfoDiagnostic [|Class C|] #Enable Warning InfoDiagnostic ' InfoDiagnostic Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class Public Class DiagnosticWithBadIdSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Protected Overrides ReadOnly Property IncludeNoLocationDiagnostics As Boolean Get ' Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here. Return False End Get End Property Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("#$DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestDiagnosticWithBadIdSuppressed() As Task ' Diagnostics with bad/invalid ID are not reported. Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserWarningDiagnosticWithNameMatchingKeywordSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("REm", "REm Title", "REm", "REm", DiagnosticSeverity.Warning, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestWarningDiagnosticWithNameMatchingKeywordSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning [REm] ' REm Title Class C #Enable Warning [REm] ' REm Title Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning [REm] ' REm Title [|Class C|] #Enable Warning [REm] ' REm Title Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class Public Class UserErrorDiagnosticSuppressionTests Inherits VisualBasicPragmaWarningDisableSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.[Error], isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestErrorDiagnosticCanBeSuppressed() As Task Dim source = <![CDATA[ Imports System [|Class C|] Sub Method() End Sub End Class]]> Dim expected = <![CDATA[ Imports System #Disable Warning ErrorDiagnostic ' ErrorDiagnostic Class C #Enable Warning ErrorDiagnostic ' ErrorDiagnostic Sub Method() End Sub End Class]]> Await TestAsync(source.Value, expected.Value) ' Also verify that the added directive does indeed suppress the diagnostic. Dim fixedSource = <![CDATA[ Imports System #Disable Warning ErrorDiagnostic ' ErrorDiagnostic [|Class C|] #Enable Warning ErrorDiagnostic ' ErrorDiagnostic Sub Method() End Sub End Class]]> Await TestMissingAsync(fixedSource.Value) End Function End Class End Class #End Region #Region "SuppressMessageAttribute tests" Public MustInherit Class VisualBasicGlobalSuppressMessageSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 1 End Get End Property Public Class CompilerDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider()) End Function <WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestCompilerDiagnosticsCannotBeSuppressed() As Task Dim source = <![CDATA[ Class Class1 Sub Method() [|Dim x|] End Sub End Class]]> Await TestActionCountAsync(source.Value, 1) End Function End Class Public Class UserHiddenDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestHiddenDiagnosticsCannotBeSuppressed() As Task Dim source = <![CDATA[ Imports System Class Class1 Sub Method() [|Dim x As System.Int32 = 0|] End Sub End Class]]> Await TestMissingAsync(source.Value) End Function End Class Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicGlobalSuppressMessageSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Select Case context.Node.Kind() Case SyntaxKind.ClassStatement Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) Exit Select Case SyntaxKind.NamespaceStatement Dim ns = DirectCast(context.Node, NamespaceStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())) Exit Select Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(context.Node, MethodStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())) Exit Select Case SyntaxKind.PropertyStatement Dim p = DirectCast(context.Node, PropertyStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation())) Exit Select Case SyntaxKind.FieldDeclaration Dim f = DirectCast(context.Node, FieldDeclarationSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation())) Exit Select Case SyntaxKind.EventStatement Dim e = DirectCast(context.Node, EventStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation())) Exit Select End Select End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType() As Task Dim source = <![CDATA[ Imports System [|Class Class1|] Sub Method() Dim x End Sub End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")> [|Class Class1|] Sub Method() Dim x End Sub End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNamespace() As Task Dim source = <![CDATA[ Imports System [|Namespace N|] Class Class1 Sub Method() Dim x End Sub End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")> " Await TestInRegularAndScriptAsync(source.Value, expected, index:=1) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")> [|Namespace N|] Class Class1 Sub Method() Dim x End Sub End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnTypeInsideNamespace() As Task Dim source = <![CDATA[ Imports System Namespace N1 Namespace N2 [|Class Class1|] Sub Method() Dim x End Sub End Class End Namespace End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")> Namespace N1 Namespace N2 [|Class Class1|] Sub Method() Dim x End Sub End Class End Namespace End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNestedType() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) [|Class Class1|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")> Namespace N Class Generic(Of T) [|Class Class1|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method() Dim x End Sub|] End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method() Dim x End Sub|] End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnOverloadedMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method(y as Integer, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method(y as Integer, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnGenericMethod() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic(Of T) Class Class1 [|Sub Method(Of U)(y as U, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")> Namespace N Class Generic(Of T) Class Class1 [|Sub Method(Of U)(y as U, ByRef z as Integer) Dim x End Sub|] Sub Method() Dim x End Sub End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnProperty() As Task Dim source = <![CDATA[ Imports System Namespace N Class Generic Private Class C [|Private ReadOnly Property P() As Integer|] Get Dim x As Integer = 0 End Get End Property End Class End Class End Namespace]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")> Namespace N Class Generic Private Class C [|Private ReadOnly Property P() As Integer|] Get Dim x As Integer = 0 End Get End Property End Class End Class End Namespace" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnField() As Task Dim source = <![CDATA[ Imports System Class C [|Private ReadOnly F As Integer|] End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")> Class C [|Private ReadOnly F As Integer|] End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnEvent() As Task Dim source = <![CDATA[ Imports System Public Class SampleEventArgs Public Sub New(s As String) Text = s End Sub Public Property Text() As [String] Get Return m_Text End Get Private Set m_Text = Value End Set End Property Private m_Text As [String] End Class Class C ' Declare the delegate (if using non-generic pattern). Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs) ' Declare the event. [|Public Custom Event SampleEvent As SampleEventHandler|] AddHandler(ByVal value As SampleEventHandler) End AddHandler RemoveHandler(ByVal value As SampleEventHandler) End RemoveHandler End Event End Class]]> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")> " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = $" Imports System <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")> Public Class SampleEventArgs Public Sub New(s As String) Text = s End Sub Public Property Text() As [String] Get Return m_Text End Get Private Set m_Text = Value End Set End Property Private m_Text As [String] End Class Class C ' Declare the delegate (if using non-generic pattern). Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs) ' Declare the event. [|Public Custom Event SampleEvent As SampleEventHandler|] AddHandler(ByVal value As SampleEventHandler) End AddHandler RemoveHandler(ByVal value As SampleEventHandler) End RemoveHandler End Event End Class" Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument() As Task Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument2() As Task ' Own custom file named GlobalSuppressions.cs Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ ' My own file named GlobalSuppressions.vb Class Class3 End Class ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument3() As Task ' Own custom file named GlobalSuppressions.vb + existing GlobalSuppressions2.vb with global suppressions Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ ' My own file named GlobalSuppressions.vb Class Class3 End Class ]]> </Document> <Document FilePath="GlobalSuppressions2.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $"' This file is used by Code Analysis to maintain SuppressMessage ' attributes that are applied to this project. ' Project-level suppressions either have no target or are given ' a specific target and scoped to a namespace, type, member, etc. Imports System.Diagnostics.CodeAnalysis <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() As Task Dim source = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document FilePath="CurrentDocument.vb"><![CDATA[ Imports System Class Class1 End Class [|Class Class2|] End Class]]> </Document> <Document FilePath="GlobalSuppressions.vb"><![CDATA[ Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")> ]]> </Document> </Project> </Workspace> Dim expected = $" Imports System.Diagnostics.CodeAnalysis <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")> <Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")> " Await TestAsync(source.ToString(), expected) End Function End Class End Class Public MustInherit Class VisualBasicLocalSuppressMessageSuppressionTests Inherits VisualBasicSuppressionTests Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer Get Return 2 End Get End Property Public Class UserInfoDiagnosticSuppressionTests Inherits VisualBasicLocalSuppressMessageSuppressionTests Private Class UserDiagnosticAnalyzer Inherits DiagnosticAnalyzer Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True) Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(_descriptor) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement) End Sub Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Select Case context.Node.Kind() Case SyntaxKind.ClassStatement Dim classDecl = DirectCast(context.Node, ClassStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation())) Exit Select Case SyntaxKind.NamespaceStatement Dim ns = DirectCast(context.Node, NamespaceStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation())) Exit Select Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Dim method = DirectCast(context.Node, MethodStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation())) Exit Select Case SyntaxKind.PropertyStatement Dim p = DirectCast(context.Node, PropertyStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation())) Exit Select Case SyntaxKind.FieldDeclaration Dim f = DirectCast(context.Node, FieldDeclarationSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation())) Exit Select Case SyntaxKind.EventStatement Dim e = DirectCast(context.Node, EventStatementSyntax) context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation())) Exit Select End Select End Sub End Class Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider) Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType() As Task Dim source = <![CDATA[ Imports System ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType2() As Task ' Type already has attributes. Dim source = <![CDATA[ Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType3() As Task ' Type has structured trivia. Dim source = <![CDATA[ Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnSimpleType4() As Task ' Type has structured trivia and attributes. Dim source = <![CDATA[ Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")> [|Class C|] Sub Method() Dim x End Sub End Class ]]> Dim expected = $" Imports System ' Some Trivia ''' <summary> ''' My custom type ''' </summary> <Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")> <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class " Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnTypeInsideNamespace() As Task Dim source = <![CDATA[ Imports System Namespace N ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class End Namespace]]> Dim expected = $" Imports System Namespace N ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class End Namespace" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnNestedType() As Task Dim source = <![CDATA[ Imports System Class Generic(Of T) ' Some Trivia [|Class C|] Sub Method() Dim x End Sub End Class End Class]]> Dim expected = $" Imports System Class Generic(Of T) ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Class C Sub Method() Dim x End Sub End Class End Class" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Class C", "[|Class C|]") Await TestMissingAsync(fixedSource) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)> Public Async Function TestSuppressionOnMethod() As Task Dim source = <![CDATA[ Imports System Class Generic(Of T) Class C ' Some Trivia [|Sub Method() Dim x End Sub|] End Class End Class]]> Dim expected = $" Imports System Class Generic(Of T) Class C ' Some Trivia <Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")> Sub Method() Dim x End Sub End Class End Class" Await TestAsync(source.Value, expected) ' Also verify that the added attribute does indeed suppress the diagnostic. Dim fixedSource = expected.Replace("Sub Method()", "[|Sub Method()|]") Await TestMissingAsync(fixedSource) End Function End Class End Class #End Region End Class End Namespace
1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/CSharp/Portable/CodeFixes/Suppression/CSharpSuppressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression { [ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.CSharp), Shared] internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpSuppressionCodeFixProvider() { } protected override SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword); return CreatePragmaDirectiveTrivia(restoreKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine); } protected override SyntaxTriviaList CreatePragmaDisableDirectiveTrivia( Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword); return CreatePragmaDirectiveTrivia(disableKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine); } private static SyntaxTriviaList CreatePragmaDirectiveTrivia( SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var diagnosticId = GetOrMapDiagnosticId(diagnostic, out var includeTitle); var id = SyntaxFactory.IdentifierName(diagnosticId); var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id); var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true); pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)formatNode(pragmaDirective); var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective); var endOfLineTrivia = SyntaxFactory.CarriageReturnLineFeed; var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia); var title = includeTitle ? diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) : null; if (!string.IsNullOrWhiteSpace(title)) { var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation); triviaList = triviaList.Add(titleComment); } if (needsLeadingEndOfLine) { triviaList = triviaList.Insert(0, endOfLineTrivia); } if (needsTrailingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return triviaList; } protected override string DefaultFileExtension => ".cs"; protected override string SingleLineCommentStart => "//"; protected override bool IsAttributeListWithAssemblyAttributes(SyntaxNode node) { return node is AttributeListSyntax attributeList && attributeList.Target != null && attributeList.Target.Identifier.Kind() == SyntaxKind.AssemblyKeyword; } protected override bool IsEndOfLine(SyntaxTrivia trivia) => trivia.IsKind(SyntaxKind.EndOfLineTrivia) || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia); protected override bool IsEndOfFileToken(SyntaxToken token) => token.Kind() == SyntaxKind.EndOfFileToken; protected override SyntaxNode AddGlobalSuppressMessageAttribute( SyntaxNode newRoot, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic, Workspace workspace, Compilation compilation, IAddImportsService addImportsService, CancellationToken cancellationToken) { var compilationRoot = (CompilationUnitSyntax)newRoot; var isFirst = !compilationRoot.AttributeLists.Any(); var attributeName = suppressMessageAttribute.GenerateNameSyntax() .WithAdditionalAnnotations(Simplifier.AddImportsAnnotation); compilationRoot = compilationRoot.AddAttributeLists( CreateAttributeList( targetSymbol, attributeName, diagnostic, isAssemblyAttribute: true, leadingTrivia: default, needsLeadingEndOfLine: true)); if (isFirst && !newRoot.HasLeadingTrivia) compilationRoot = compilationRoot.WithLeadingTrivia(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment)); return compilationRoot; } protected override SyntaxNode AddLocalSuppressMessageAttribute( SyntaxNode targetNode, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic) { var memberNode = (MemberDeclarationSyntax)targetNode; SyntaxTriviaList leadingTriviaForAttributeList; bool needsLeadingEndOfLine; if (!memberNode.GetAttributes().Any()) { leadingTriviaForAttributeList = memberNode.GetLeadingTrivia(); memberNode = memberNode.WithoutLeadingTrivia(); needsLeadingEndOfLine = !leadingTriviaForAttributeList.Any() || !IsEndOfLine(leadingTriviaForAttributeList.Last()); } else { leadingTriviaForAttributeList = default; needsLeadingEndOfLine = true; } var attributeName = suppressMessageAttribute.GenerateNameSyntax(); var attributeList = CreateAttributeList( targetSymbol, attributeName, diagnostic, isAssemblyAttribute: false, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: needsLeadingEndOfLine); return memberNode.AddAttributeLists(attributeList); } private static AttributeListSyntax CreateAttributeList( ISymbol targetSymbol, NameSyntax attributeName, Diagnostic diagnostic, bool isAssemblyAttribute, SyntaxTriviaList leadingTrivia, bool needsLeadingEndOfLine) { var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute); var attributes = new SeparatedSyntaxList<AttributeSyntax>() .Add(SyntaxFactory.Attribute(attributeName, attributeArguments)); AttributeListSyntax attributeList; if (isAssemblyAttribute) { var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)); attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes); } else { attributeList = SyntaxFactory.AttributeList(attributes); } var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed; var triviaList = SyntaxFactory.TriviaList(); if (needsLeadingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return attributeList.WithLeadingTrivia(leadingTrivia.AddRange(triviaList)); } private static AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic, bool isAssemblyAttribute) { // SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target)) var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)); var categoryArgument = SyntaxFactory.AttributeArgument(category); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title); var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)); var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId); var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)); var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr); var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument); if (isAssemblyAttribute) { var scopeString = GetScopeString(targetSymbol.Kind); if (scopeString != null) { var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)); var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr); var targetString = GetTargetString(targetSymbol); var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)); var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr); attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument); } } return attributeArgumentList; } protected override bool IsSingleAttributeInAttributeList(SyntaxNode attribute) { if (attribute is AttributeSyntax attributeSyntax) { return attributeSyntax.Parent is AttributeListSyntax attributeList && attributeList.Attributes.Count == 1; } return false; } protected override bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds) { if (trivia.Kind() == SyntaxKind.PragmaWarningDirectiveTrivia) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); enableDirective = pragmaWarning.DisableOrRestoreKeyword.Kind() == SyntaxKind.RestoreKeyword; hasMultipleIds = pragmaWarning.ErrorCodes.Count > 1; return pragmaWarning.ErrorCodes.Any(n => n.ToString() == id); } enableDirective = false; hasMultipleIds = false; return false; } protected override SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); var currentKeyword = pragmaWarning.DisableOrRestoreKeyword; var toggledKeywordKind = currentKeyword.Kind() == SyntaxKind.DisableKeyword ? SyntaxKind.RestoreKeyword : SyntaxKind.DisableKeyword; var toggledToken = SyntaxFactory.Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia); var newPragmaWarning = pragmaWarning.WithDisableOrRestoreKeyword(toggledToken); return SyntaxFactory.Trivia(newPragmaWarning); } protected override SyntaxToken GetAdjustedTokenForPragmaRestore( SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine) { var nextToken = token.GetNextToken(); if (nextToken.Kind() == SyntaxKind.SemicolonToken && nextToken.Parent is StatementSyntax statement && statement.GetLastToken() == nextToken && token.Parent.FirstAncestorOrSelf<StatementSyntax>() == statement) { // both the current and next tokens belong to the same statement, and the next token // is the final semicolon in a statement. Do not put the pragma before that // semicolon. Place it after the semicolon so the statement stays whole. return nextToken; } return token; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression { [ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.CSharp), Shared] internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpSuppressionCodeFixProvider() { } protected override SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword); return CreatePragmaDirectiveTrivia(restoreKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine); } protected override SyntaxTriviaList CreatePragmaDisableDirectiveTrivia( Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword); return CreatePragmaDirectiveTrivia(disableKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine); } private static SyntaxTriviaList CreatePragmaDirectiveTrivia( SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var diagnosticId = GetOrMapDiagnosticId(diagnostic, out var includeTitle); var id = SyntaxFactory.IdentifierName(diagnosticId); var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id); var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true); pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)formatNode(pragmaDirective); var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective); var endOfLineTrivia = SyntaxFactory.CarriageReturnLineFeed; var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia); var title = includeTitle ? diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) : null; if (!string.IsNullOrWhiteSpace(title)) { var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation); triviaList = triviaList.Add(titleComment); } if (needsLeadingEndOfLine) { triviaList = triviaList.Insert(0, endOfLineTrivia); } if (needsTrailingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return triviaList; } protected override string DefaultFileExtension => ".cs"; protected override string SingleLineCommentStart => "//"; protected override bool IsAttributeListWithAssemblyAttributes(SyntaxNode node) { return node is AttributeListSyntax attributeList && attributeList.Target != null && attributeList.Target.Identifier.Kind() == SyntaxKind.AssemblyKeyword; } protected override bool IsEndOfLine(SyntaxTrivia trivia) => trivia.IsKind(SyntaxKind.EndOfLineTrivia) || trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia); protected override bool IsEndOfFileToken(SyntaxToken token) => token.Kind() == SyntaxKind.EndOfFileToken; protected override SyntaxNode AddGlobalSuppressMessageAttribute( SyntaxNode newRoot, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic, Workspace workspace, Compilation compilation, IAddImportsService addImportsService, CancellationToken cancellationToken) { var compilationRoot = (CompilationUnitSyntax)newRoot; var isFirst = !compilationRoot.AttributeLists.Any(); var attributeName = suppressMessageAttribute.GenerateNameSyntax() .WithAdditionalAnnotations(Simplifier.AddImportsAnnotation); compilationRoot = compilationRoot.AddAttributeLists( CreateAttributeList( targetSymbol, attributeName, diagnostic, isAssemblyAttribute: true, leadingTrivia: default, needsLeadingEndOfLine: true)); if (isFirst && !newRoot.HasLeadingTrivia) compilationRoot = compilationRoot.WithLeadingTrivia(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment)); return compilationRoot; } protected override SyntaxNode AddLocalSuppressMessageAttribute( SyntaxNode targetNode, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic) { var memberNode = (MemberDeclarationSyntax)targetNode; SyntaxTriviaList leadingTriviaForAttributeList; bool needsLeadingEndOfLine; if (!memberNode.GetAttributes().Any()) { leadingTriviaForAttributeList = memberNode.GetLeadingTrivia(); memberNode = memberNode.WithoutLeadingTrivia(); needsLeadingEndOfLine = !leadingTriviaForAttributeList.Any() || !IsEndOfLine(leadingTriviaForAttributeList.Last()); } else { leadingTriviaForAttributeList = default; needsLeadingEndOfLine = true; } var attributeName = suppressMessageAttribute.GenerateNameSyntax(); var attributeList = CreateAttributeList( targetSymbol, attributeName, diagnostic, isAssemblyAttribute: false, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: needsLeadingEndOfLine); return memberNode.AddAttributeLists(attributeList); } private static AttributeListSyntax CreateAttributeList( ISymbol targetSymbol, NameSyntax attributeName, Diagnostic diagnostic, bool isAssemblyAttribute, SyntaxTriviaList leadingTrivia, bool needsLeadingEndOfLine) { var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute); var attributes = new SeparatedSyntaxList<AttributeSyntax>() .Add(SyntaxFactory.Attribute(attributeName, attributeArguments)); AttributeListSyntax attributeList; if (isAssemblyAttribute) { var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)); attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes); } else { attributeList = SyntaxFactory.AttributeList(attributes); } var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed; var triviaList = SyntaxFactory.TriviaList(); if (needsLeadingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return attributeList.WithLeadingTrivia(leadingTrivia.AddRange(triviaList)); } private static AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic, bool isAssemblyAttribute) { // SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target)) var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)); var categoryArgument = SyntaxFactory.AttributeArgument(category); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title); var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)); var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId); var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)); var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr); var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument); if (isAssemblyAttribute) { var scopeString = GetScopeString(targetSymbol.Kind); if (scopeString != null) { var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)); var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr); var targetString = GetTargetString(targetSymbol); var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)); var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr); attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument); } } return attributeArgumentList; } protected override bool IsSingleAttributeInAttributeList(SyntaxNode attribute) { if (attribute is AttributeSyntax attributeSyntax) { return attributeSyntax.Parent is AttributeListSyntax attributeList && attributeList.Attributes.Count == 1; } return false; } protected override bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds) { if (trivia.Kind() == SyntaxKind.PragmaWarningDirectiveTrivia) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); enableDirective = pragmaWarning.DisableOrRestoreKeyword.Kind() == SyntaxKind.RestoreKeyword; hasMultipleIds = pragmaWarning.ErrorCodes.Count > 1; return pragmaWarning.ErrorCodes.Any(n => n.ToString() == id); } enableDirective = false; hasMultipleIds = false; return false; } protected override SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); var currentKeyword = pragmaWarning.DisableOrRestoreKeyword; var toggledKeywordKind = currentKeyword.Kind() == SyntaxKind.DisableKeyword ? SyntaxKind.RestoreKeyword : SyntaxKind.DisableKeyword; var toggledToken = SyntaxFactory.Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia); var newPragmaWarning = pragmaWarning.WithDisableOrRestoreKeyword(toggledToken); return SyntaxFactory.Trivia(newPragmaWarning); } protected override SyntaxNode GetContainingStatement(SyntaxToken token) // If we can't get a containing statement, such as for expression bodied members, then // return the arrow clause instead => (SyntaxNode)token.GetAncestor<StatementSyntax>() ?? token.GetAncestor<ArrowExpressionClauseSyntax>(); protected override bool TokenHasTrailingLineContinuationChar(SyntaxToken token) => false; } }
1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { public const string SuppressMessageAttributeName = "System.Diagnostics.CodeAnalysis.SuppressMessage"; private const string s_globalSuppressionsFileName = "GlobalSuppressions"; private const string s_suppressionsFileCommentTemplate = @"{0} This file is used by Code Analysis to maintain SuppressMessage {0} attributes that are applied to this project. {0} Project-level suppressions either have no target or are given {0} a specific target and scoped to a namespace, type, member, etc. "; protected AbstractSuppressionCodeFixProvider() { } public FixAllProvider GetFixAllProvider() => SuppressionFixAllProvider.Instance; public bool IsFixableDiagnostic(Diagnostic diagnostic) => SuppressionHelpers.CanBeSuppressed(diagnostic) || SuppressionHelpers.CanBeUnsuppressed(diagnostic); protected abstract SyntaxTriviaList CreatePragmaDisableDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine); protected abstract SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine); protected abstract SyntaxNode AddGlobalSuppressMessageAttribute( SyntaxNode newRoot, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic, Workspace workspace, Compilation compilation, IAddImportsService addImportsService, CancellationToken cancellationToken); protected abstract SyntaxNode AddLocalSuppressMessageAttribute( SyntaxNode targetNode, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic); protected abstract string DefaultFileExtension { get; } protected abstract string SingleLineCommentStart { get; } protected abstract bool IsAttributeListWithAssemblyAttributes(SyntaxNode node); protected abstract bool IsEndOfLine(SyntaxTrivia trivia); protected abstract bool IsEndOfFileToken(SyntaxToken token); protected abstract bool IsSingleAttributeInAttributeList(SyntaxNode attribute); protected abstract bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds); protected abstract SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia); protected string GlobalSuppressionsFileHeaderComment { get { return string.Format(s_suppressionsFileCommentTemplate, SingleLineCommentStart); } } protected static string GetOrMapDiagnosticId(Diagnostic diagnostic, out bool includeTitle) { if (diagnostic.Id == IDEDiagnosticIds.FormattingDiagnosticId) { includeTitle = false; return FormattingDiagnosticIds.FormatDocumentControlDiagnosticId; } includeTitle = true; return diagnostic.Id; } protected virtual SyntaxToken GetAdjustedTokenForPragmaDisable(SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine) => token; protected virtual SyntaxToken GetAdjustedTokenForPragmaRestore(SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine) => token; public Task<ImmutableArray<CodeFix>> GetFixesAsync( Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { return GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken); } internal async Task<ImmutableArray<PragmaWarningCodeAction>> GetPragmaSuppressionsAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { var codeFixes = await GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: true, skipUnsuppress: true, cancellationToken: cancellationToken).ConfigureAwait(false); return codeFixes.SelectMany(fix => fix.Action.NestedCodeActions) .OfType<PragmaWarningCodeAction>() .ToImmutableArray(); } private async Task<ImmutableArray<CodeFix>> GetSuppressionsAsync( Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, bool skipSuppressMessage, bool skipUnsuppress, CancellationToken cancellationToken) { var suppressionTargetInfo = await GetSuppressionTargetInfoAsync(document, span, cancellationToken).ConfigureAwait(false); if (suppressionTargetInfo == null) { return ImmutableArray<CodeFix>.Empty; } return await GetSuppressionsAsync( documentOpt: document, project: document.Project, diagnostics: diagnostics, suppressionTargetInfo: suppressionTargetInfo, skipSuppressMessage: skipSuppressMessage, skipUnsuppress: skipUnsuppress, cancellationToken: cancellationToken).ConfigureAwait(false); } public async Task<ImmutableArray<CodeFix>> GetFixesAsync( Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { return ImmutableArray<CodeFix>.Empty; } var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var suppressionTargetInfo = new SuppressionTargetInfo() { TargetSymbol = compilation.Assembly }; return await GetSuppressionsAsync( documentOpt: null, project: project, diagnostics: diagnostics, suppressionTargetInfo: suppressionTargetInfo, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<CodeFix>> GetSuppressionsAsync( Document documentOpt, Project project, IEnumerable<Diagnostic> diagnostics, SuppressionTargetInfo suppressionTargetInfo, bool skipSuppressMessage, bool skipUnsuppress, CancellationToken cancellationToken) { // We only care about diagnostics that can be suppressed/unsuppressed. diagnostics = diagnostics.Where(IsFixableDiagnostic); if (diagnostics.IsEmpty()) { return ImmutableArray<CodeFix>.Empty; } INamedTypeSymbol suppressMessageAttribute = null; if (!skipSuppressMessage) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); suppressMessageAttribute = compilation.SuppressMessageAttributeType(); skipSuppressMessage = suppressMessageAttribute == null || !suppressMessageAttribute.IsAttribute(); } var result = ArrayBuilder<CodeFix>.GetInstance(); foreach (var diagnostic in diagnostics) { if (!diagnostic.IsSuppressed) { var nestedActions = ArrayBuilder<NestedSuppressionCodeAction>.GetInstance(); if (diagnostic.Location.IsInSource && documentOpt != null) { // pragma warning disable. nestedActions.Add(PragmaWarningCodeAction.Create(suppressionTargetInfo, documentOpt, diagnostic, this)); } // SuppressMessageAttribute suppression is not supported for compiler diagnostics. if (!skipSuppressMessage && SuppressionHelpers.CanBeSuppressedWithAttribute(diagnostic)) { // global assembly-level suppress message attribute. nestedActions.Add(new GlobalSuppressMessageCodeAction( suppressionTargetInfo.TargetSymbol, suppressMessageAttribute, project, diagnostic, this)); // local suppress message attribute // please note that in order to avoid issues with existing unit tests referencing the code fix // by their index this needs to be the last added to nestedActions if (suppressionTargetInfo.TargetMemberNode != null && suppressionTargetInfo.TargetSymbol.Kind != SymbolKind.Namespace) { nestedActions.Add(new LocalSuppressMessageCodeAction( this, suppressionTargetInfo.TargetSymbol, suppressMessageAttribute, suppressionTargetInfo.TargetMemberNode, documentOpt, diagnostic)); } } if (nestedActions.Count > 0) { var codeAction = new TopLevelSuppressionCodeAction( diagnostic, nestedActions.ToImmutableAndFree()); result.Add(new CodeFix(project, codeAction, diagnostic)); } } else if (!skipUnsuppress) { var codeAction = await RemoveSuppressionCodeAction.CreateAsync(suppressionTargetInfo, documentOpt, project, diagnostic, this, cancellationToken).ConfigureAwait(false); if (codeAction != null) { result.Add(new CodeFix(project, codeAction, diagnostic)); } } } return result.ToImmutableAndFree(); } internal class SuppressionTargetInfo { public ISymbol TargetSymbol { get; set; } public SyntaxToken StartToken { get; set; } public SyntaxToken EndToken { get; set; } public SyntaxNode NodeWithTokens { get; set; } public SyntaxNode TargetMemberNode { get; set; } } private async Task<SuppressionTargetInfo> GetSuppressionTargetInfoAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.GetLineVisibility(span.Start, cancellationToken) == LineVisibility.Hidden) { return null; } // Find the start token to attach leading pragma disable warning directive. var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var lines = syntaxTree.GetText(cancellationToken).Lines; var indexOfLine = lines.IndexOf(span.Start); var lineAtPos = lines[indexOfLine]; var startToken = root.FindToken(lineAtPos.Start); startToken = GetAdjustedTokenForPragmaDisable(startToken, root, lines, indexOfLine); // Find the end token to attach pragma restore warning directive. var spanEnd = Math.Max(startToken.Span.End, span.End); indexOfLine = lines.IndexOf(spanEnd); lineAtPos = lines[indexOfLine]; var endToken = root.FindToken(lineAtPos.End); endToken = GetAdjustedTokenForPragmaRestore(endToken, root, lines, indexOfLine); var nodeWithTokens = GetNodeWithTokens(startToken, endToken, root); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); ISymbol targetSymbol = null; var targetMemberNode = syntaxFacts.GetContainingMemberDeclaration(root, nodeWithTokens.SpanStart); if (targetMemberNode != null) { targetSymbol = semanticModel.GetDeclaredSymbol(targetMemberNode, cancellationToken); if (targetSymbol == null) { var analyzerDriverService = document.GetLanguageService<IAnalyzerDriverService>(); // targetMemberNode could be a declaration node with multiple decls (e.g. field declaration defining multiple variables). // Let us compute all the declarations intersecting the span. var declsBuilder = ArrayBuilder<DeclarationInfo>.GetInstance(); analyzerDriverService.ComputeDeclarationsInSpan(semanticModel, span, true, declsBuilder, cancellationToken); var decls = declsBuilder.ToImmutableAndFree(); if (!decls.IsEmpty) { var containedDecls = decls.Where(d => span.Contains(d.DeclaredNode.Span)); if (containedDecls.Count() == 1) { // Single containing declaration, use this symbol. var decl = containedDecls.Single(); targetSymbol = decl.DeclaredSymbol; } else { // Otherwise, use the most enclosing declaration. TextSpan? minContainingSpan = null; foreach (var decl in decls) { var declSpan = decl.DeclaredNode.Span; if (declSpan.Contains(span) && (!minContainingSpan.HasValue || minContainingSpan.Value.Contains(declSpan))) { minContainingSpan = declSpan; targetSymbol = decl.DeclaredSymbol; } } } } } } if (targetSymbol == null) { // Outside of a member declaration, suppress diagnostic for the entire assembly. targetSymbol = semanticModel.Compilation.Assembly; } return new SuppressionTargetInfo() { TargetSymbol = targetSymbol, NodeWithTokens = nodeWithTokens, StartToken = startToken, EndToken = endToken, TargetMemberNode = targetMemberNode }; } internal SyntaxNode GetNodeWithTokens(SyntaxToken startToken, SyntaxToken endToken, SyntaxNode root) { if (IsEndOfFileToken(endToken)) { return root; } else { return startToken.GetCommonRoot(endToken); } } protected static string GetScopeString(SymbolKind targetSymbolKind) { switch (targetSymbolKind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: return "member"; case SymbolKind.NamedType: return "type"; case SymbolKind.Namespace: return "namespace"; default: return null; } } protected static string GetTargetString(ISymbol targetSymbol) => "~" + DocumentationCommentId.CreateDeclarationId(targetSymbol); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes.Suppression { internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider { public const string SuppressMessageAttributeName = "System.Diagnostics.CodeAnalysis.SuppressMessage"; private const string s_globalSuppressionsFileName = "GlobalSuppressions"; private const string s_suppressionsFileCommentTemplate = @"{0} This file is used by Code Analysis to maintain SuppressMessage {0} attributes that are applied to this project. {0} Project-level suppressions either have no target or are given {0} a specific target and scoped to a namespace, type, member, etc. "; protected AbstractSuppressionCodeFixProvider() { } public FixAllProvider GetFixAllProvider() => SuppressionFixAllProvider.Instance; public bool IsFixableDiagnostic(Diagnostic diagnostic) => SuppressionHelpers.CanBeSuppressed(diagnostic) || SuppressionHelpers.CanBeUnsuppressed(diagnostic); protected abstract SyntaxTriviaList CreatePragmaDisableDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine); protected abstract SyntaxTriviaList CreatePragmaRestoreDirectiveTrivia(Diagnostic diagnostic, Func<SyntaxNode, SyntaxNode> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine); protected abstract SyntaxNode AddGlobalSuppressMessageAttribute( SyntaxNode newRoot, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic, Workspace workspace, Compilation compilation, IAddImportsService addImportsService, CancellationToken cancellationToken); protected abstract SyntaxNode AddLocalSuppressMessageAttribute( SyntaxNode targetNode, ISymbol targetSymbol, INamedTypeSymbol suppressMessageAttribute, Diagnostic diagnostic); protected abstract string DefaultFileExtension { get; } protected abstract string SingleLineCommentStart { get; } protected abstract bool IsAttributeListWithAssemblyAttributes(SyntaxNode node); protected abstract bool IsEndOfLine(SyntaxTrivia trivia); protected abstract bool IsEndOfFileToken(SyntaxToken token); protected abstract bool IsSingleAttributeInAttributeList(SyntaxNode attribute); protected abstract bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds); protected abstract SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia); protected string GlobalSuppressionsFileHeaderComment { get { return string.Format(s_suppressionsFileCommentTemplate, SingleLineCommentStart); } } protected static string GetOrMapDiagnosticId(Diagnostic diagnostic, out bool includeTitle) { if (diagnostic.Id == IDEDiagnosticIds.FormattingDiagnosticId) { includeTitle = false; return FormattingDiagnosticIds.FormatDocumentControlDiagnosticId; } includeTitle = true; return diagnostic.Id; } protected abstract SyntaxNode GetContainingStatement(SyntaxToken token); protected abstract bool TokenHasTrailingLineContinuationChar(SyntaxToken token); protected SyntaxToken GetAdjustedTokenForPragmaDisable(SyntaxToken token, SyntaxNode root, TextLineCollection lines) { var containingStatement = GetContainingStatement(token); // The containing statement might not start on the same line as the token, but we don't want to split // a statement in the middle, so we actually want to use the first token on the line that has the first token // of the statement. // // eg, given: public void M() { int x = 1; } // // When trying to suppress an "unused local" for x, token would be "x", the first token // of the containing statement is "int", but we want the pragma before "public". if (containingStatement is not null && containingStatement.GetFirstToken() != token) { var indexOfLine = lines.IndexOf(containingStatement.GetFirstToken().SpanStart); var line = lines[indexOfLine]; token = root.FindToken(line.Start); } return token; } private SyntaxToken GetAdjustedTokenForPragmaRestore(SyntaxToken token, SyntaxNode root, TextLineCollection lines, int indexOfLine) { var containingStatement = GetContainingStatement(token); // As per above, the last token of the statement might not be the last token on the line if (containingStatement is not null && containingStatement.GetLastToken() != token) { indexOfLine = lines.IndexOf(containingStatement.GetLastToken().SpanStart); } var line = lines[indexOfLine]; token = root.FindToken(line.End); // VB has line continuation characters that can explicitly extend the line beyond the last // token, so allow for that by just skipping over them while (TokenHasTrailingLineContinuationChar(token)) { indexOfLine = indexOfLine + 1; token = root.FindToken(lines[indexOfLine].End, findInsideTrivia: true); } return token; } public Task<ImmutableArray<CodeFix>> GetFixesAsync( Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { return GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken); } internal async Task<ImmutableArray<PragmaWarningCodeAction>> GetPragmaSuppressionsAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { var codeFixes = await GetSuppressionsAsync(document, span, diagnostics, skipSuppressMessage: true, skipUnsuppress: true, cancellationToken: cancellationToken).ConfigureAwait(false); return codeFixes.SelectMany(fix => fix.Action.NestedCodeActions) .OfType<PragmaWarningCodeAction>() .ToImmutableArray(); } private async Task<ImmutableArray<CodeFix>> GetSuppressionsAsync( Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, bool skipSuppressMessage, bool skipUnsuppress, CancellationToken cancellationToken) { var suppressionTargetInfo = await GetSuppressionTargetInfoAsync(document, span, cancellationToken).ConfigureAwait(false); if (suppressionTargetInfo == null) { return ImmutableArray<CodeFix>.Empty; } return await GetSuppressionsAsync( documentOpt: document, project: document.Project, diagnostics: diagnostics, suppressionTargetInfo: suppressionTargetInfo, skipSuppressMessage: skipSuppressMessage, skipUnsuppress: skipUnsuppress, cancellationToken: cancellationToken).ConfigureAwait(false); } public async Task<ImmutableArray<CodeFix>> GetFixesAsync( Project project, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken) { if (!project.SupportsCompilation) { return ImmutableArray<CodeFix>.Empty; } var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var suppressionTargetInfo = new SuppressionTargetInfo() { TargetSymbol = compilation.Assembly }; return await GetSuppressionsAsync( documentOpt: null, project: project, diagnostics: diagnostics, suppressionTargetInfo: suppressionTargetInfo, skipSuppressMessage: false, skipUnsuppress: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<CodeFix>> GetSuppressionsAsync( Document documentOpt, Project project, IEnumerable<Diagnostic> diagnostics, SuppressionTargetInfo suppressionTargetInfo, bool skipSuppressMessage, bool skipUnsuppress, CancellationToken cancellationToken) { // We only care about diagnostics that can be suppressed/unsuppressed. diagnostics = diagnostics.Where(IsFixableDiagnostic); if (diagnostics.IsEmpty()) { return ImmutableArray<CodeFix>.Empty; } INamedTypeSymbol suppressMessageAttribute = null; if (!skipSuppressMessage) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); suppressMessageAttribute = compilation.SuppressMessageAttributeType(); skipSuppressMessage = suppressMessageAttribute == null || !suppressMessageAttribute.IsAttribute(); } var result = ArrayBuilder<CodeFix>.GetInstance(); foreach (var diagnostic in diagnostics) { if (!diagnostic.IsSuppressed) { var nestedActions = ArrayBuilder<NestedSuppressionCodeAction>.GetInstance(); if (diagnostic.Location.IsInSource && documentOpt != null) { // pragma warning disable. nestedActions.Add(PragmaWarningCodeAction.Create(suppressionTargetInfo, documentOpt, diagnostic, this)); } // SuppressMessageAttribute suppression is not supported for compiler diagnostics. if (!skipSuppressMessage && SuppressionHelpers.CanBeSuppressedWithAttribute(diagnostic)) { // global assembly-level suppress message attribute. nestedActions.Add(new GlobalSuppressMessageCodeAction( suppressionTargetInfo.TargetSymbol, suppressMessageAttribute, project, diagnostic, this)); // local suppress message attribute // please note that in order to avoid issues with existing unit tests referencing the code fix // by their index this needs to be the last added to nestedActions if (suppressionTargetInfo.TargetMemberNode != null && suppressionTargetInfo.TargetSymbol.Kind != SymbolKind.Namespace) { nestedActions.Add(new LocalSuppressMessageCodeAction( this, suppressionTargetInfo.TargetSymbol, suppressMessageAttribute, suppressionTargetInfo.TargetMemberNode, documentOpt, diagnostic)); } } if (nestedActions.Count > 0) { var codeAction = new TopLevelSuppressionCodeAction( diagnostic, nestedActions.ToImmutableAndFree()); result.Add(new CodeFix(project, codeAction, diagnostic)); } } else if (!skipUnsuppress) { var codeAction = await RemoveSuppressionCodeAction.CreateAsync(suppressionTargetInfo, documentOpt, project, diagnostic, this, cancellationToken).ConfigureAwait(false); if (codeAction != null) { result.Add(new CodeFix(project, codeAction, diagnostic)); } } } return result.ToImmutableAndFree(); } internal class SuppressionTargetInfo { public ISymbol TargetSymbol { get; set; } public SyntaxToken StartToken { get; set; } public SyntaxToken EndToken { get; set; } public SyntaxNode NodeWithTokens { get; set; } public SyntaxNode TargetMemberNode { get; set; } } private async Task<SuppressionTargetInfo> GetSuppressionTargetInfoAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.GetLineVisibility(span.Start, cancellationToken) == LineVisibility.Hidden) { return null; } // Find the start token to attach leading pragma disable warning directive. var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var lines = syntaxTree.GetText(cancellationToken).Lines; var indexOfLine = lines.IndexOf(span.Start); var lineAtPos = lines[indexOfLine]; var startToken = root.FindToken(lineAtPos.Start); startToken = GetAdjustedTokenForPragmaDisable(startToken, root, lines); // Find the end token to attach pragma restore warning directive. var spanEnd = Math.Max(startToken.Span.End, span.End); indexOfLine = lines.IndexOf(spanEnd); lineAtPos = lines[indexOfLine]; var endToken = root.FindToken(lineAtPos.End); endToken = GetAdjustedTokenForPragmaRestore(endToken, root, lines, indexOfLine); var nodeWithTokens = GetNodeWithTokens(startToken, endToken, root); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); ISymbol targetSymbol = null; var targetMemberNode = syntaxFacts.GetContainingMemberDeclaration(root, nodeWithTokens.SpanStart); if (targetMemberNode != null) { targetSymbol = semanticModel.GetDeclaredSymbol(targetMemberNode, cancellationToken); if (targetSymbol == null) { var analyzerDriverService = document.GetLanguageService<IAnalyzerDriverService>(); // targetMemberNode could be a declaration node with multiple decls (e.g. field declaration defining multiple variables). // Let us compute all the declarations intersecting the span. var declsBuilder = ArrayBuilder<DeclarationInfo>.GetInstance(); analyzerDriverService.ComputeDeclarationsInSpan(semanticModel, span, true, declsBuilder, cancellationToken); var decls = declsBuilder.ToImmutableAndFree(); if (!decls.IsEmpty) { var containedDecls = decls.Where(d => span.Contains(d.DeclaredNode.Span)); if (containedDecls.Count() == 1) { // Single containing declaration, use this symbol. var decl = containedDecls.Single(); targetSymbol = decl.DeclaredSymbol; } else { // Otherwise, use the most enclosing declaration. TextSpan? minContainingSpan = null; foreach (var decl in decls) { var declSpan = decl.DeclaredNode.Span; if (declSpan.Contains(span) && (!minContainingSpan.HasValue || minContainingSpan.Value.Contains(declSpan))) { minContainingSpan = declSpan; targetSymbol = decl.DeclaredSymbol; } } } } } } if (targetSymbol == null) { // Outside of a member declaration, suppress diagnostic for the entire assembly. targetSymbol = semanticModel.Compilation.Assembly; } return new SuppressionTargetInfo() { TargetSymbol = targetSymbol, NodeWithTokens = nodeWithTokens, StartToken = startToken, EndToken = endToken, TargetMemberNode = targetMemberNode }; } internal SyntaxNode GetNodeWithTokens(SyntaxToken startToken, SyntaxToken endToken, SyntaxNode root) { if (IsEndOfFileToken(endToken)) { return root; } else { return startToken.GetCommonRoot(endToken); } } protected static string GetScopeString(SymbolKind targetSymbolKind) { switch (targetSymbolKind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: return "member"; case SymbolKind.NamedType: return "type"; case SymbolKind.Namespace: return "namespace"; default: return null; } } protected static string GetTargetString(ISymbol targetSymbol) => "~" + DocumentationCommentId.CreateDeclarationId(targetSymbol); } }
1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/VisualBasic/Portable/CodeFixes/Suppression/VisualBasicSuppressionCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression <ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSuppressionCodeFixProvider Inherits AbstractSuppressionCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CreatePragmaRestoreDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.EnableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Protected Overrides Function CreatePragmaDisableDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.DisableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Private Shared Function GetErrorCodes(diagnostic As Diagnostic, ByRef includeTitle As Boolean) As SeparatedSyntaxList(Of IdentifierNameSyntax) Dim text = GetOrMapDiagnosticId(diagnostic, includeTitle) If SyntaxFacts.GetKeywordKind(text) <> SyntaxKind.None Then text = "[" & text & "]" End If Return New SeparatedSyntaxList(Of IdentifierNameSyntax)().Add(SyntaxFactory.IdentifierName(text)) End Function Private Shared Function CreatePragmaDirectiveTrivia(enableOrDisablePragmaDirective As StructuredTriviaSyntax, includeTitle As Boolean, diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList enableOrDisablePragmaDirective = CType(formatNode(enableOrDisablePragmaDirective), StructuredTriviaSyntax) Dim pragmaDirectiveTrivia = SyntaxFactory.Trivia(enableOrDisablePragmaDirective) Dim endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Dim triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia) Dim title = If(includeTitle, diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture), Nothing) If Not String.IsNullOrWhiteSpace(title) Then Dim titleComment = SyntaxFactory.CommentTrivia(String.Format(" ' {0}", title)).WithAdditionalAnnotations(Formatter.Annotation) triviaList = triviaList.Add(titleComment) End If If needsLeadingEndOfLine Then triviaList = triviaList.Insert(0, endOfLineTrivia) End If If needsTrailingEndOfLine Then triviaList = triviaList.Add(endOfLineTrivia) End If Return triviaList End Function Protected Overrides Function GetAdjustedTokenForPragmaDisable(token As SyntaxToken, root As SyntaxNode, lines As TextLineCollection, indexOfLine As Integer) As SyntaxToken Dim containingStatement = token.GetAncestor(Of StatementSyntax) If containingStatement IsNot Nothing AndAlso containingStatement.GetFirstToken() <> token Then indexOfLine = lines.IndexOf(containingStatement.GetFirstToken().SpanStart) Dim line = lines(indexOfLine) token = root.FindToken(line.Start) End If Return token End Function Protected Overrides Function GetAdjustedTokenForPragmaRestore(token As SyntaxToken, root As SyntaxNode, lines As TextLineCollection, indexOfLine As Integer) As SyntaxToken Dim containingStatement = token.GetAncestor(Of StatementSyntax) While True If TokenHasTrailingLineContinuationChar(token) Then indexOfLine = indexOfLine + 1 ElseIf containingStatement IsNot Nothing AndAlso containingStatement.GetLastToken() <> token Then indexOfLine = lines.IndexOf(containingStatement.GetLastToken().SpanStart) containingStatement = Nothing Else Exit While End If Dim line = lines(indexOfLine) token = root.FindToken(line.End) End While Return token End Function Private Shared Function TokenHasTrailingLineContinuationChar(token As SyntaxToken) As Boolean Return token.TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) End Function Protected Overrides ReadOnly Property DefaultFileExtension() As String Get Return ".vb" End Get End Property Protected Overrides ReadOnly Property SingleLineCommentStart() As String Get Return "'" End Get End Property Protected Overrides Function IsAttributeListWithAssemblyAttributes(node As SyntaxNode) As Boolean Dim attributesStatement = TryCast(node, AttributesStatementSyntax) Return attributesStatement IsNot Nothing AndAlso attributesStatement.AttributeLists.All(Function(attributeList) attributeList.Attributes.All(Function(a) a.Target.AttributeModifier.Kind() = SyntaxKind.AssemblyKeyword)) End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsEndOfFileToken(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.EndOfFileToken End Function Protected Overrides Function AddGlobalSuppressMessageAttribute( newRoot As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic, workspace As Workspace, compilation As Compilation, addImportsService As IAddImportsService, cancellationToken As CancellationToken) As SyntaxNode Dim compilationRoot = DirectCast(newRoot, CompilationUnitSyntax) Dim isFirst = Not compilationRoot.Attributes.Any() Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=True) Dim attributeStatement = SyntaxFactory.AttributesStatement(New SyntaxList(Of AttributeListSyntax)().Add(attributeList)) If Not isFirst Then Dim trailingTrivia = compilationRoot.Attributes.Last().GetTrailingTrivia() Dim lastTrivia = If(trailingTrivia.IsEmpty, Nothing, trailingTrivia(trailingTrivia.Count - 1)) If Not IsEndOfLine(lastTrivia) Then ' Add leading end of line trivia to attribute statement attributeStatement = attributeStatement.WithLeadingTrivia(attributeStatement.GetLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed)) End If End If attributeStatement = CType(Formatter.Format(attributeStatement, workspace, cancellationToken:=cancellationToken), AttributesStatementSyntax) Dim leadingTrivia = If(isFirst AndAlso Not compilationRoot.HasLeadingTrivia, SyntaxFactory.TriviaList(SyntaxFactory.CommentTrivia(GlobalSuppressionsFileHeaderComment)), Nothing) leadingTrivia = leadingTrivia.AddRange(compilationRoot.GetLeadingTrivia()) compilationRoot = compilationRoot.WithoutLeadingTrivia() Return compilationRoot.AddAttributes(attributeStatement).WithLeadingTrivia(leadingTrivia) End Function Protected Overrides Function AddLocalSuppressMessageAttribute( targetNode As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic) As SyntaxNode Dim memberNode = DirectCast(targetNode, StatementSyntax) Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=False) Dim leadingTrivia = memberNode.GetLeadingTrivia() memberNode = memberNode.WithoutLeadingTrivia() Return memberNode.AddAttributeLists(attributeList).WithLeadingTrivia(leadingTrivia) End Function Private Shared Function CreateAttributeList( targetSymbol As ISymbol, attributeName As NameSyntax, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As AttributeListSyntax Dim attributeTarget = If(isAssemblyAttribute, SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)), Nothing) Dim attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute) Dim attribute As AttributeSyntax = SyntaxFactory.Attribute(attributeTarget, attributeName, attributeArguments) Return SyntaxFactory.AttributeList().AddAttributes(attribute) End Function Private Shared Function CreateAttributeArguments(targetSymbol As ISymbol, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As ArgumentListSyntax ' SuppressMessage("Rule Category", "Rule Id", Justification := "Justification", Scope := "Scope", Target := "Target") Dim category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)) Dim categoryArgument = SyntaxFactory.SimpleArgument(category) Dim title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) Dim ruleIdText = If(String.IsNullOrWhiteSpace(title), diagnostic.Id, String.Format("{0}:{1}", diagnostic.Id, title)) Dim ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)) Dim ruleIdArgument = SyntaxFactory.SimpleArgument(ruleId) Dim justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)) Dim justificationArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Justification")), expression:=justificationExpr) Dim attributeArgumentList = SyntaxFactory.ArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument) Dim scopeString = GetScopeString(targetSymbol.Kind) If isAssemblyAttribute Then If scopeString IsNot Nothing Then Dim scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)) Dim scopeArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Scope")), expression:=scopeExpr) Dim targetString = GetTargetString(targetSymbol) Dim targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)) Dim targetArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Target")), expression:=targetExpr) attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument) End If End If Return attributeArgumentList End Function Protected Overrides Function IsSingleAttributeInAttributeList(attribute As SyntaxNode) As Boolean Dim attributeSyntax = TryCast(attribute, AttributeSyntax) If attributeSyntax IsNot Nothing Then Dim attributeList = TryCast(attributeSyntax.Parent, AttributeListSyntax) Return attributeList IsNot Nothing AndAlso attributeList.Attributes.Count = 1 End If Return False End Function Protected Overrides Function IsAnyPragmaDirectiveForId(trivia As SyntaxTrivia, id As String, ByRef enableDirective As Boolean, ByRef hasMultipleIds As Boolean) As Boolean Dim errorCodes As SeparatedSyntaxList(Of IdentifierNameSyntax) Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = False Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = True Case Else enableDirective = False hasMultipleIds = False Return False End Select hasMultipleIds = errorCodes.Count > 1 Return errorCodes.Any(Function(node) node.ToString = id) End Function Protected Overrides Function TogglePragmaDirective(trivia As SyntaxTrivia) As SyntaxTrivia Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) Dim disabledKeyword = pragmaWarning.DisableKeyword Dim enabledKeyword = SyntaxFactory.Token(disabledKeyword.LeadingTrivia, SyntaxKind.EnableKeyword, disabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.EnableWarningDirectiveTrivia(pragmaWarning.HashToken, enabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) Dim enabledKeyword = pragmaWarning.EnableKeyword Dim disabledKeyword = SyntaxFactory.Token(enabledKeyword.LeadingTrivia, SyntaxKind.DisableKeyword, enabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.DisableWarningDirectiveTrivia(pragmaWarning.HashToken, disabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case Else throw ExceptionUtilities.UnexpectedValue(trivia.Kind()) End Select End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.AddImports Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.Suppression Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression <ExportConfigurationFixProvider(PredefinedConfigurationFixProviderNames.Suppression, LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicSuppressionCodeFixProvider Inherits AbstractSuppressionCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function CreatePragmaRestoreDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.EnableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Protected Overrides Function CreatePragmaDisableDirectiveTrivia(diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList Dim includeTitle As Boolean Dim errorCodes = GetErrorCodes(diagnostic, includeTitle) Dim pragmaDirective = SyntaxFactory.DisableWarningDirectiveTrivia(errorCodes) Return CreatePragmaDirectiveTrivia(pragmaDirective, includeTitle, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine) End Function Private Shared Function GetErrorCodes(diagnostic As Diagnostic, ByRef includeTitle As Boolean) As SeparatedSyntaxList(Of IdentifierNameSyntax) Dim text = GetOrMapDiagnosticId(diagnostic, includeTitle) If SyntaxFacts.GetKeywordKind(text) <> SyntaxKind.None Then text = "[" & text & "]" End If Return New SeparatedSyntaxList(Of IdentifierNameSyntax)().Add(SyntaxFactory.IdentifierName(text)) End Function Private Shared Function CreatePragmaDirectiveTrivia(enableOrDisablePragmaDirective As StructuredTriviaSyntax, includeTitle As Boolean, diagnostic As Diagnostic, formatNode As Func(Of SyntaxNode, SyntaxNode), needsLeadingEndOfLine As Boolean, needsTrailingEndOfLine As Boolean) As SyntaxTriviaList enableOrDisablePragmaDirective = CType(formatNode(enableOrDisablePragmaDirective), StructuredTriviaSyntax) Dim pragmaDirectiveTrivia = SyntaxFactory.Trivia(enableOrDisablePragmaDirective) Dim endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed Dim triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia) Dim title = If(includeTitle, diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture), Nothing) If Not String.IsNullOrWhiteSpace(title) Then Dim titleComment = SyntaxFactory.CommentTrivia(String.Format(" ' {0}", title)).WithAdditionalAnnotations(Formatter.Annotation) triviaList = triviaList.Add(titleComment) End If If needsLeadingEndOfLine Then triviaList = triviaList.Insert(0, endOfLineTrivia) End If If needsTrailingEndOfLine Then triviaList = triviaList.Add(endOfLineTrivia) End If Return triviaList End Function Protected Overrides Function GetContainingStatement(token As SyntaxToken) As SyntaxNode Return token.GetAncestor(Of StatementSyntax)() End Function Protected Overrides Function TokenHasTrailingLineContinuationChar(token As SyntaxToken) As Boolean Return token.TrailingTrivia.Any(Function(t) t.Kind = SyntaxKind.LineContinuationTrivia) End Function Protected Overrides ReadOnly Property DefaultFileExtension() As String Get Return ".vb" End Get End Property Protected Overrides ReadOnly Property SingleLineCommentStart() As String Get Return "'" End Get End Property Protected Overrides Function IsAttributeListWithAssemblyAttributes(node As SyntaxNode) As Boolean Dim attributesStatement = TryCast(node, AttributesStatementSyntax) Return attributesStatement IsNot Nothing AndAlso attributesStatement.AttributeLists.All(Function(attributeList) attributeList.Attributes.All(Function(a) a.Target.AttributeModifier.Kind() = SyntaxKind.AssemblyKeyword)) End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsEndOfFileToken(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.EndOfFileToken End Function Protected Overrides Function AddGlobalSuppressMessageAttribute( newRoot As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic, workspace As Workspace, compilation As Compilation, addImportsService As IAddImportsService, cancellationToken As CancellationToken) As SyntaxNode Dim compilationRoot = DirectCast(newRoot, CompilationUnitSyntax) Dim isFirst = Not compilationRoot.Attributes.Any() Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=True) Dim attributeStatement = SyntaxFactory.AttributesStatement(New SyntaxList(Of AttributeListSyntax)().Add(attributeList)) If Not isFirst Then Dim trailingTrivia = compilationRoot.Attributes.Last().GetTrailingTrivia() Dim lastTrivia = If(trailingTrivia.IsEmpty, Nothing, trailingTrivia(trailingTrivia.Count - 1)) If Not IsEndOfLine(lastTrivia) Then ' Add leading end of line trivia to attribute statement attributeStatement = attributeStatement.WithLeadingTrivia(attributeStatement.GetLeadingTrivia.Add(SyntaxFactory.ElasticCarriageReturnLineFeed)) End If End If attributeStatement = CType(Formatter.Format(attributeStatement, workspace, cancellationToken:=cancellationToken), AttributesStatementSyntax) Dim leadingTrivia = If(isFirst AndAlso Not compilationRoot.HasLeadingTrivia, SyntaxFactory.TriviaList(SyntaxFactory.CommentTrivia(GlobalSuppressionsFileHeaderComment)), Nothing) leadingTrivia = leadingTrivia.AddRange(compilationRoot.GetLeadingTrivia()) compilationRoot = compilationRoot.WithoutLeadingTrivia() Return compilationRoot.AddAttributes(attributeStatement).WithLeadingTrivia(leadingTrivia) End Function Protected Overrides Function AddLocalSuppressMessageAttribute( targetNode As SyntaxNode, targetSymbol As ISymbol, suppressMessageAttribute As INamedTypeSymbol, diagnostic As Diagnostic) As SyntaxNode Dim memberNode = DirectCast(targetNode, StatementSyntax) Dim attributeName = DirectCast(suppressMessageAttribute.GenerateTypeSyntax(), NameSyntax) Dim attributeList = CreateAttributeList(targetSymbol, attributeName, diagnostic, isAssemblyAttribute:=False) Dim leadingTrivia = memberNode.GetLeadingTrivia() memberNode = memberNode.WithoutLeadingTrivia() Return memberNode.AddAttributeLists(attributeList).WithLeadingTrivia(leadingTrivia) End Function Private Shared Function CreateAttributeList( targetSymbol As ISymbol, attributeName As NameSyntax, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As AttributeListSyntax Dim attributeTarget = If(isAssemblyAttribute, SyntaxFactory.AttributeTarget(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)), Nothing) Dim attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic, isAssemblyAttribute) Dim attribute As AttributeSyntax = SyntaxFactory.Attribute(attributeTarget, attributeName, attributeArguments) Return SyntaxFactory.AttributeList().AddAttributes(attribute) End Function Private Shared Function CreateAttributeArguments(targetSymbol As ISymbol, diagnostic As Diagnostic, isAssemblyAttribute As Boolean) As ArgumentListSyntax ' SuppressMessage("Rule Category", "Rule Id", Justification := "Justification", Scope := "Scope", Target := "Target") Dim category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)) Dim categoryArgument = SyntaxFactory.SimpleArgument(category) Dim title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture) Dim ruleIdText = If(String.IsNullOrWhiteSpace(title), diagnostic.Id, String.Format("{0}:{1}", diagnostic.Id, title)) Dim ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)) Dim ruleIdArgument = SyntaxFactory.SimpleArgument(ruleId) Dim justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)) Dim justificationArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Justification")), expression:=justificationExpr) Dim attributeArgumentList = SyntaxFactory.ArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument) Dim scopeString = GetScopeString(targetSymbol.Kind) If isAssemblyAttribute Then If scopeString IsNot Nothing Then Dim scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)) Dim scopeArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Scope")), expression:=scopeExpr) Dim targetString = GetTargetString(targetSymbol) Dim targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)) Dim targetArgument = SyntaxFactory.SimpleArgument(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("Target")), expression:=targetExpr) attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument) End If End If Return attributeArgumentList End Function Protected Overrides Function IsSingleAttributeInAttributeList(attribute As SyntaxNode) As Boolean Dim attributeSyntax = TryCast(attribute, AttributeSyntax) If attributeSyntax IsNot Nothing Then Dim attributeList = TryCast(attributeSyntax.Parent, AttributeListSyntax) Return attributeList IsNot Nothing AndAlso attributeList.Attributes.Count = 1 End If Return False End Function Protected Overrides Function IsAnyPragmaDirectiveForId(trivia As SyntaxTrivia, id As String, ByRef enableDirective As Boolean, ByRef hasMultipleIds As Boolean) As Boolean Dim errorCodes As SeparatedSyntaxList(Of IdentifierNameSyntax) Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = False Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) errorCodes = pragmaWarning.ErrorCodes enableDirective = True Case Else enableDirective = False hasMultipleIds = False Return False End Select hasMultipleIds = errorCodes.Count > 1 Return errorCodes.Any(Function(node) node.ToString = id) End Function Protected Overrides Function TogglePragmaDirective(trivia As SyntaxTrivia) As SyntaxTrivia Select Case trivia.Kind() Case SyntaxKind.DisableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), DisableWarningDirectiveTriviaSyntax) Dim disabledKeyword = pragmaWarning.DisableKeyword Dim enabledKeyword = SyntaxFactory.Token(disabledKeyword.LeadingTrivia, SyntaxKind.EnableKeyword, disabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.EnableWarningDirectiveTrivia(pragmaWarning.HashToken, enabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case SyntaxKind.EnableWarningDirectiveTrivia Dim pragmaWarning = DirectCast(trivia.GetStructure(), EnableWarningDirectiveTriviaSyntax) Dim enabledKeyword = pragmaWarning.EnableKeyword Dim disabledKeyword = SyntaxFactory.Token(enabledKeyword.LeadingTrivia, SyntaxKind.DisableKeyword, enabledKeyword.TrailingTrivia) Dim newPragmaWarning = SyntaxFactory.DisableWarningDirectiveTrivia(pragmaWarning.HashToken, disabledKeyword, pragmaWarning.WarningKeyword, pragmaWarning.ErrorCodes) _ .WithLeadingTrivia(pragmaWarning.GetLeadingTrivia) _ .WithTrailingTrivia(pragmaWarning.GetTrailingTrivia) Return SyntaxFactory.Trivia(newPragmaWarning) Case Else throw ExceptionUtilities.UnexpectedValue(trivia.Kind()) End Select End Function End Class End Namespace
1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/EditorConfig/IEditorConfigStorageLocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Options { internal interface IEditorConfigStorageLocation { bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object? value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Options { internal interface IEditorConfigStorageLocation { bool TryGetOption(IReadOnlyDictionary<string, string?> rawOptions, Type type, out object? value); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/Helpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { internal static class CodeFixHelpers { /// <summary> /// Creates an `^expr` index expression from a given `expr`. /// </summary> public static PrefixUnaryExpressionSyntax IndexExpression(ExpressionSyntax expr) => SyntaxFactory.PrefixUnaryExpression( SyntaxKind.IndexExpression, expr.Parenthesize()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { internal static class CodeFixHelpers { /// <summary> /// Creates an `^expr` index expression from a given `expr`. /// </summary> public static PrefixUnaryExpressionSyntax IndexExpression(ExpressionSyntax expr) => SyntaxFactory.PrefixUnaryExpression( SyntaxKind.IndexExpression, expr.Parenthesize()); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/CSharp/Test/Syntax/Parsing/PatternParsingTests2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests2 : ParsingTests { private new void UsingExpression(string text, params DiagnosticDescription[] expectedErrors) { UsingExpression(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), expectedErrors); } public PatternParsingTests2(ITestOutputHelper output) : base(output) { } [Fact] public void ExtendedPropertySubpattern_01() { UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular10); verify(); UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular9, // (1,8): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // e is { a.b.c: p } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a.b.c").WithArguments("extended property patterns", "10.0").WithLocation(1, 8)); verify(); void verify() { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } } [Fact] public void ExtendedPropertySubpattern_02() { UsingExpression(@"e is { {}: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_03() { UsingExpression(@"e is { name<T>: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "name"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_04() { UsingExpression(@"e is { name[0]: p }", // (1,15): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 15), // (1,17): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 17)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "name"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseBracketToken); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_05() { UsingExpression(@"e is { a?.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_06() { UsingExpression(@"e is { a->c: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.PointerMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.MinusGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_07() { UsingExpression(@"e is { [0]: p }", // (1,8): error CS1001: Identifier expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,13): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 13)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_08() { UsingExpression(@"e is { not a: p }", // (1,13): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 13), // (1,15): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 15)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_09() { UsingExpression(@"e is { x or y: p }", // (1,14): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 14), // (1,16): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 16)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_10() { UsingExpression(@"e is { 1: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_11() { UsingExpression(@"e is { >1: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_12() { UsingExpression(@"e is { a!.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SuppressNullableWarningExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ExclamationToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_13() { UsingExpression(@"e is { a[0].b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_14() { UsingExpression(@"e is { [0].b: p }", // (1,8): error CS1001: Identifier expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "b").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_15() { UsingExpression(@"e is { (c?a:b): p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_InPositionalPattern() { UsingExpression(@"e is ( a.b.c: p )"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.Patterns)] public class PatternParsingTests2 : ParsingTests { private new void UsingExpression(string text, params DiagnosticDescription[] expectedErrors) { UsingExpression(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview), expectedErrors); } public PatternParsingTests2(ITestOutputHelper output) : base(output) { } [Fact] public void ExtendedPropertySubpattern_01() { UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular10); verify(); UsingExpression(@"e is { a.b.c: p }", TestOptions.Regular9, // (1,8): error CS8773: Feature 'extended property patterns' is not available in C# 9.0. Please use language version 10.0 or greater. // e is { a.b.c: p } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a.b.c").WithArguments("extended property patterns", "10.0").WithLocation(1, 8)); verify(); void verify() { N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } } [Fact] public void ExtendedPropertySubpattern_02() { UsingExpression(@"e is { {}: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { {}: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_03() { UsingExpression(@"e is { name<T>: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "name"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_04() { UsingExpression(@"e is { name[0]: p }", // (1,15): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 15), // (1,17): error CS1003: Syntax error, ',' expected // e is { name[0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 17)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.TypePattern); { N(SyntaxKind.ArrayType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "name"); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseBracketToken); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_05() { UsingExpression(@"e is { a?.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_06() { UsingExpression(@"e is { a->c: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.PointerMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.MinusGreaterThanToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_07() { UsingExpression(@"e is { [0]: p }", // (1,8): error CS1001: Identifier expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,13): error CS1003: Syntax error, ',' expected // e is { [0]: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 13)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_08() { UsingExpression(@"e is { not a: p }", // (1,13): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 13), // (1,15): error CS1003: Syntax error, ',' expected // e is { not a: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 15)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NotPattern); { N(SyntaxKind.NotKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_09() { UsingExpression(@"e is { x or y: p }", // (1,14): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 14), // (1,16): error CS1003: Syntax error, ',' expected // e is { x or y: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 16)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.OrPattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.OrKeyword); N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_10() { UsingExpression(@"e is { 1: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_11() { UsingExpression(@"e is { >1: p }", // (1,10): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { >1: p } Diagnostic(ErrorCode.ERR_SyntaxError, "p").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.RelationalPattern); { N(SyntaxKind.GreaterThanToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_12() { UsingExpression(@"e is { a!.b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SuppressNullableWarningExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ExclamationToken); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_13() { UsingExpression(@"e is { a[0].b: p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_14() { UsingExpression(@"e is { [0].b: p }", // (1,8): error CS1001: Identifier expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_IdentifierExpected, "[").WithLocation(1, 8), // (1,10): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "]").WithArguments(",", "]").WithLocation(1, 10), // (1,12): error CS1003: Syntax error, ',' expected // e is { [0].b: p } Diagnostic(ErrorCode.ERR_SyntaxError, "b").WithArguments(",", "").WithLocation(1, 12)); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ConstantPattern); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } M(SyntaxKind.CommaToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_15() { UsingExpression(@"e is { (c?a:b): p }"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PropertyPatternClause); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseBraceToken); } } } EOF(); } [Fact] public void ExtendedPropertySubpattern_InPositionalPattern() { UsingExpression(@"e is ( a.b.c: p )"); N(SyntaxKind.IsPatternExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "e"); } N(SyntaxKind.IsKeyword); N(SyntaxKind.RecursivePattern); { N(SyntaxKind.PositionalPatternClause); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Subpattern); { N(SyntaxKind.ExpressionColon); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } N(SyntaxKind.ColonToken); } N(SyntaxKind.ConstantPattern); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "p"); } } } N(SyntaxKind.CloseParenToken); } } } EOF(); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/VisualStudio/Core/Test/Completion/TestCSharpSnippetInfoService.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Snippets Imports Microsoft.VisualStudio.LanguageServices.CSharp.Snippets Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion <ExportLanguageService(GetType(ISnippetInfoService), LanguageNames.CSharp, ServiceLayer.Test), [Shared], PartNotDiscoverable> Friend Class TestCSharpSnippetInfoService Inherits CSharpSnippetInfoService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext, listenerProvider As IAsynchronousOperationListenerProvider) MyBase.New(threadingContext, Nothing, listenerProvider) End Sub Friend Sub SetSnippetShortcuts(newSnippetShortcuts As String()) SyncLock cacheGuard snippets = newSnippetShortcuts.Select(Function(shortcut) New SnippetInfo(shortcut, "title", "description", "path")).ToImmutableArray() snippetShortcuts = GetShortcutsHashFromSnippets(snippets) End SyncLock End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Snippets Imports Microsoft.VisualStudio.LanguageServices.CSharp.Snippets Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Completion <ExportLanguageService(GetType(ISnippetInfoService), LanguageNames.CSharp, ServiceLayer.Test), [Shared], PartNotDiscoverable> Friend Class TestCSharpSnippetInfoService Inherits CSharpSnippetInfoService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext, listenerProvider As IAsynchronousOperationListenerProvider) MyBase.New(threadingContext, Nothing, listenerProvider) End Sub Friend Sub SetSnippetShortcuts(newSnippetShortcuts As String()) SyncLock cacheGuard snippets = newSnippetShortcuts.Select(Function(shortcut) New SnippetInfo(shortcut, "title", "description", "path")).ToImmutableArray() snippetShortcuts = GetShortcutsHashFromSnippets(snippets) End SyncLock End Sub End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/VisualBasic/Portable/Symbols/AnonymousTypes/PublicSymbols/AnonymousType_TypePublicSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Friend NotInheritable Class AnonymousTypePublicSymbol Inherits AnonymousTypeOrDelegatePublicSymbol Private ReadOnly _properties As ImmutableArray(Of AnonymousTypePropertyPublicSymbol) Private ReadOnly _members As ImmutableArray(Of Symbol) Private ReadOnly _interfaces As ImmutableArray(Of NamedTypeSymbol) Public Sub New(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) MyBase.New(manager, typeDescr) Dim fieldsCount As Integer = typeDescr.Fields.Length Dim methodMembersBuilder = ArrayBuilder(Of Symbol).GetInstance() Dim otherMembersBuilder = ArrayBuilder(Of Symbol).GetInstance() ' The array storing property symbols to be used in ' generation of constructor and other methods Dim propertiesArray = New AnonymousTypePropertyPublicSymbol(fieldsCount - 1) {} ' Anonymous types with at least one Key field are being generated slightly different Dim hasAtLeastOneKeyField As Boolean = False ' Process fields For fieldIndex = 0 To fieldsCount - 1 Dim field As AnonymousTypeField = typeDescr.Fields(fieldIndex) If field.IsKey Then hasAtLeastOneKeyField = True End If ' Add a property Dim [property] As New AnonymousTypePropertyPublicSymbol(Me, fieldIndex) propertiesArray(fieldIndex) = [property] ' Property related symbols otherMembersBuilder.Add([property]) methodMembersBuilder.Add([property].GetMethod) If [property].SetMethod IsNot Nothing Then methodMembersBuilder.Add([property].SetMethod) End If Next _properties = propertiesArray.AsImmutableOrNull() ' Add a constructor methodMembersBuilder.Add(CreateConstructorSymbol()) ' Add 'ToString' methodMembersBuilder.Add(CreateToStringMethod()) ' Add optional members If hasAtLeastOneKeyField AndAlso Me.Manager.System_IEquatable_T_Equals IsNot Nothing Then ' Add 'GetHashCode' methodMembersBuilder.Add(CreateGetHashCodeMethod()) ' Add optional 'Inherits IEquatable' Dim equatableInterface As NamedTypeSymbol = Me.Manager.System_IEquatable_T.Construct(ImmutableArray.Create(Of TypeSymbol)(Me)) Me._interfaces = ImmutableArray.Create(Of NamedTypeSymbol)(equatableInterface) ' Add 'IEquatable.Equals' Dim method As Symbol = DirectCast(equatableInterface, SubstitutedNamedType).GetMemberForDefinition(Me.Manager.System_IEquatable_T_Equals) methodMembersBuilder.Add(CreateIEquatableEqualsMethod(DirectCast(method, MethodSymbol))) ' Add 'Equals' methodMembersBuilder.Add(CreateEqualsMethod()) Else _interfaces = ImmutableArray(Of NamedTypeSymbol).Empty End If methodMembersBuilder.AddRange(otherMembersBuilder) otherMembersBuilder.Free() _members = methodMembersBuilder.ToImmutableAndFree() End Sub Private Function CreateConstructorSymbol() As MethodSymbol Dim constructor As New SynthesizedSimpleConstructorSymbol(Me) Dim fieldsCount As Integer = Me._properties.Length Dim paramsArr = New ParameterSymbol(fieldsCount - 1) {} For index = 0 To fieldsCount - 1 Dim [property] As PropertySymbol = Me._properties(index) paramsArr(index) = New SynthesizedParameterSimpleSymbol(constructor, [property].Type, index, [property].Name) Next constructor.SetParameters(paramsArr.AsImmutableOrNull()) Return constructor End Function Private Function CreateEqualsMethod() As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectEquals, Me.Manager.System_Boolean, overriddenMethod:=Me.Manager.System_Object__Equals, isOverloads:=True) method.SetParameters(ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSimpleSymbol(method, Me.Manager.System_Object, 0, "obj") )) Return method End Function Private Function CreateIEquatableEqualsMethod(iEquatableEquals As MethodSymbol) As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectEquals, Me.Manager.System_Boolean, interfaceMethod:=iEquatableEquals, isOverloads:=True) method.SetParameters(ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSimpleSymbol(method, Me, 0, "val") )) Return method End Function Private Function CreateGetHashCodeMethod() As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectGetHashCode, Me.Manager.System_Int32, overriddenMethod:=Me.Manager.System_Object__GetHashCode) method.SetParameters(ImmutableArray(Of ParameterSymbol).Empty) Return method End Function Private Function CreateToStringMethod() As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectToString, Me.Manager.System_String, overriddenMethod:=Me.Manager.System_Object__ToString) method.SetParameters(ImmutableArray(Of ParameterSymbol).Empty) Return method End Function Public Overrides ReadOnly Property TypeKind As TypeKind Get Return TypeKind.Class End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return False End Get End Property Public ReadOnly Property Properties As ImmutableArray(Of AnonymousTypePropertyPublicSymbol) Get Return Me._properties End Get End Property Friend Overrides Function InternalSubstituteTypeParameters(substitution As TypeSubstitution) As TypeWithModifiers Dim newDescriptor As New AnonymousTypeDescriptor If Not Me.TypeDescriptor.SubstituteTypeParametersIfNeeded(substitution, newDescriptor) Then Return New TypeWithModifiers(Me) End If Return New TypeWithModifiers(Me.Manager.ConstructAnonymousTypeSymbol(newDescriptor)) End Function Public Overrides Function GetMembers() As ImmutableArray(Of Symbol) Return _members End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return Me.Manager.System_Object End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return _interfaces End Function Public Overrides Function MapToImplementationSymbol() As NamedTypeSymbol Return Me.Manager.ConstructAnonymousTypeImplementationSymbol(Me) End Function Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of AnonymousObjectCreationExpressionSyntax)(Me.Locations) End Get End Property End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Partial Friend NotInheritable Class AnonymousTypeManager Friend NotInheritable Class AnonymousTypePublicSymbol Inherits AnonymousTypeOrDelegatePublicSymbol Private ReadOnly _properties As ImmutableArray(Of AnonymousTypePropertyPublicSymbol) Private ReadOnly _members As ImmutableArray(Of Symbol) Private ReadOnly _interfaces As ImmutableArray(Of NamedTypeSymbol) Public Sub New(manager As AnonymousTypeManager, typeDescr As AnonymousTypeDescriptor) MyBase.New(manager, typeDescr) Dim fieldsCount As Integer = typeDescr.Fields.Length Dim methodMembersBuilder = ArrayBuilder(Of Symbol).GetInstance() Dim otherMembersBuilder = ArrayBuilder(Of Symbol).GetInstance() ' The array storing property symbols to be used in ' generation of constructor and other methods Dim propertiesArray = New AnonymousTypePropertyPublicSymbol(fieldsCount - 1) {} ' Anonymous types with at least one Key field are being generated slightly different Dim hasAtLeastOneKeyField As Boolean = False ' Process fields For fieldIndex = 0 To fieldsCount - 1 Dim field As AnonymousTypeField = typeDescr.Fields(fieldIndex) If field.IsKey Then hasAtLeastOneKeyField = True End If ' Add a property Dim [property] As New AnonymousTypePropertyPublicSymbol(Me, fieldIndex) propertiesArray(fieldIndex) = [property] ' Property related symbols otherMembersBuilder.Add([property]) methodMembersBuilder.Add([property].GetMethod) If [property].SetMethod IsNot Nothing Then methodMembersBuilder.Add([property].SetMethod) End If Next _properties = propertiesArray.AsImmutableOrNull() ' Add a constructor methodMembersBuilder.Add(CreateConstructorSymbol()) ' Add 'ToString' methodMembersBuilder.Add(CreateToStringMethod()) ' Add optional members If hasAtLeastOneKeyField AndAlso Me.Manager.System_IEquatable_T_Equals IsNot Nothing Then ' Add 'GetHashCode' methodMembersBuilder.Add(CreateGetHashCodeMethod()) ' Add optional 'Inherits IEquatable' Dim equatableInterface As NamedTypeSymbol = Me.Manager.System_IEquatable_T.Construct(ImmutableArray.Create(Of TypeSymbol)(Me)) Me._interfaces = ImmutableArray.Create(Of NamedTypeSymbol)(equatableInterface) ' Add 'IEquatable.Equals' Dim method As Symbol = DirectCast(equatableInterface, SubstitutedNamedType).GetMemberForDefinition(Me.Manager.System_IEquatable_T_Equals) methodMembersBuilder.Add(CreateIEquatableEqualsMethod(DirectCast(method, MethodSymbol))) ' Add 'Equals' methodMembersBuilder.Add(CreateEqualsMethod()) Else _interfaces = ImmutableArray(Of NamedTypeSymbol).Empty End If methodMembersBuilder.AddRange(otherMembersBuilder) otherMembersBuilder.Free() _members = methodMembersBuilder.ToImmutableAndFree() End Sub Private Function CreateConstructorSymbol() As MethodSymbol Dim constructor As New SynthesizedSimpleConstructorSymbol(Me) Dim fieldsCount As Integer = Me._properties.Length Dim paramsArr = New ParameterSymbol(fieldsCount - 1) {} For index = 0 To fieldsCount - 1 Dim [property] As PropertySymbol = Me._properties(index) paramsArr(index) = New SynthesizedParameterSimpleSymbol(constructor, [property].Type, index, [property].Name) Next constructor.SetParameters(paramsArr.AsImmutableOrNull()) Return constructor End Function Private Function CreateEqualsMethod() As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectEquals, Me.Manager.System_Boolean, overriddenMethod:=Me.Manager.System_Object__Equals, isOverloads:=True) method.SetParameters(ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSimpleSymbol(method, Me.Manager.System_Object, 0, "obj") )) Return method End Function Private Function CreateIEquatableEqualsMethod(iEquatableEquals As MethodSymbol) As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectEquals, Me.Manager.System_Boolean, interfaceMethod:=iEquatableEquals, isOverloads:=True) method.SetParameters(ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSimpleSymbol(method, Me, 0, "val") )) Return method End Function Private Function CreateGetHashCodeMethod() As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectGetHashCode, Me.Manager.System_Int32, overriddenMethod:=Me.Manager.System_Object__GetHashCode) method.SetParameters(ImmutableArray(Of ParameterSymbol).Empty) Return method End Function Private Function CreateToStringMethod() As MethodSymbol Dim method As New SynthesizedSimpleMethodSymbol(Me, WellKnownMemberNames.ObjectToString, Me.Manager.System_String, overriddenMethod:=Me.Manager.System_Object__ToString) method.SetParameters(ImmutableArray(Of ParameterSymbol).Empty) Return method End Function Public Overrides ReadOnly Property TypeKind As TypeKind Get Return TypeKind.Class End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return False End Get End Property Public ReadOnly Property Properties As ImmutableArray(Of AnonymousTypePropertyPublicSymbol) Get Return Me._properties End Get End Property Friend Overrides Function InternalSubstituteTypeParameters(substitution As TypeSubstitution) As TypeWithModifiers Dim newDescriptor As New AnonymousTypeDescriptor If Not Me.TypeDescriptor.SubstituteTypeParametersIfNeeded(substitution, newDescriptor) Then Return New TypeWithModifiers(Me) End If Return New TypeWithModifiers(Me.Manager.ConstructAnonymousTypeSymbol(newDescriptor)) End Function Public Overrides Function GetMembers() As ImmutableArray(Of Symbol) Return _members End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return Me.Manager.System_Object End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return _interfaces End Function Public Overrides Function MapToImplementationSymbol() As NamedTypeSymbol Return Me.Manager.ConstructAnonymousTypeImplementationSymbol(Me) End Function Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(Of AnonymousObjectCreationExpressionSyntax)(Me.Locations) End Get End Property End Class End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/StackAllocKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class StackAllocKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public StackAllocKeywordRecommender() : base(SyntaxKind.StackAllocKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // Beginning with C# 8.0, stackalloc expression can be used inside other expressions // whenever a Span<T> or ReadOnlySpan<T> variable is allowed. return (context.IsAnyExpressionContext && !context.IsConstantExpressionContext) || context.IsStatementContext || context.IsGlobalStatementContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class StackAllocKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public StackAllocKeywordRecommender() : base(SyntaxKind.StackAllocKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // Beginning with C# 8.0, stackalloc expression can be used inside other expressions // whenever a Span<T> or ReadOnlySpan<T> variable is allowed. return (context.IsAnyExpressionContext && !context.IsConstantExpressionContext) || context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/VisualBasic/Portable/Binding/SpeculativeStatementBinder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Provides context for binding statements in speculative code. ''' </summary> Friend NotInheritable Class SpeculativeStatementBinder Inherits ExecutableCodeBinder ''' <summary> ''' Create binder for binding statements in speculative code. ''' </summary> Public Sub New(root As VisualBasicSyntaxNode, containingBinder As Binder) MyBase.New(root, containingBinder) End Sub Public Overrides ReadOnly Property IsSemanticModelBinder As Boolean Get Return True End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.RuntimeMembers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Utilities Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Provides context for binding statements in speculative code. ''' </summary> Friend NotInheritable Class SpeculativeStatementBinder Inherits ExecutableCodeBinder ''' <summary> ''' Create binder for binding statements in speculative code. ''' </summary> Public Sub New(root As VisualBasicSyntaxNode, containingBinder As Binder) MyBase.New(root, containingBinder) End Sub Public Overrides ReadOnly Property IsSemanticModelBinder As Boolean Get Return True End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/VisualBasic/Portable/Utilities/IntrinsicOperators/GetXmlNamespaceExpressionDocumentation.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class GetXmlNamespaceExpressionDocumentation Inherits AbstractIntrinsicOperatorDocumentation Public Overrides Function GetParameterDisplayParts(index As Integer) As IList(Of SymbolDisplayPart) Select Case index Case 0 Return { New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "["), New SymbolDisplayPart(SymbolDisplayPartKind.ParameterName, Nothing, GetParameterName(index)), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "]") } Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterDocumentation(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterName(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.xmlNamespacePrefix Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return { New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "GetXmlNamespace"), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(") } End Get End Property Public Overrides ReadOnly Property IncludeAsType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnTypeMetadataName As String Get Return "System.Xml.Linq.XNamespace" End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Friend NotInheritable Class GetXmlNamespaceExpressionDocumentation Inherits AbstractIntrinsicOperatorDocumentation Public Overrides Function GetParameterDisplayParts(index As Integer) As IList(Of SymbolDisplayPart) Select Case index Case 0 Return { New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "["), New SymbolDisplayPart(SymbolDisplayPartKind.ParameterName, Nothing, GetParameterName(index)), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "]") } Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterDocumentation(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.The_XML_namespace_prefix_to_return_a_System_Xml_Linq_XNamespace_object_for_If_this_is_omitted_the_object_for_the_default_XML_namespace_is_returned Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides Function GetParameterName(index As Integer) As String Select Case index Case 0 Return VBWorkspaceResources.xmlNamespacePrefix Case Else Throw New ArgumentException(NameOf(index)) End Select End Function Public Overrides ReadOnly Property ParameterCount As Integer Get Return 1 End Get End Property Public Overrides ReadOnly Property DocumentationText As String Get Return VBWorkspaceResources.Returns_the_System_Xml_Linq_XNamespace_object_corresponding_to_the_specified_XML_namespace_prefix End Get End Property Public Overrides ReadOnly Property PrefixParts As IList(Of SymbolDisplayPart) Get Return { New SymbolDisplayPart(SymbolDisplayPartKind.Keyword, Nothing, "GetXmlNamespace"), New SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, Nothing, "(") } End Get End Property Public Overrides ReadOnly Property IncludeAsType As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property ReturnTypeMetadataName As String Get Return "System.Xml.Linq.XNamespace" End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/Core/Portable/Syntax/GreenNodeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal static class GreenNodeExtensions { public static TNode WithAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : GreenNode { var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == 0) { newAnnotations.Free(); var existingAnnotations = node.GetAnnotations(); if (existingAnnotations == null || existingAnnotations.Length == 0) { return node; } else { return (TNode)node.SetAnnotations(null); } } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithAdditionalAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); newAnnotations.AddRange(existingAnnotations); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == existingAnnotations.Length) { newAnnotations.Free(); return node; } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithoutAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null || existingAnnotations.Length == 0) { return node; } var removalAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); removalAnnotations.AddRange(annotations); try { if (removalAnnotations.Count == 0) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in existingAnnotations) { if (!removalAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } finally { removalAnnotations.Free(); } } public static TNode WithDiagnosticsGreen<TNode>(this TNode node, DiagnosticInfo[]? diagnostics) where TNode : GreenNode { return (TNode)node.SetDiagnostics(diagnostics); } public static TNode WithoutDiagnosticsGreen<TNode>(this TNode node) where TNode : GreenNode { var current = node.GetDiagnostics(); if (current == null || current.Length == 0) { return node; } return (TNode)node.SetDiagnostics(null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal static class GreenNodeExtensions { public static TNode WithAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation> annotations) where TNode : GreenNode { var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == 0) { newAnnotations.Free(); var existingAnnotations = node.GetAnnotations(); if (existingAnnotations == null || existingAnnotations.Length == 0) { return node; } else { return (TNode)node.SetAnnotations(null); } } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithAdditionalAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); newAnnotations.AddRange(existingAnnotations); foreach (var candidate in annotations) { if (!newAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } if (newAnnotations.Count == existingAnnotations.Length) { newAnnotations.Free(); return node; } else { return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } } public static TNode WithoutAnnotationsGreen<TNode>(this TNode node, IEnumerable<SyntaxAnnotation>? annotations) where TNode : GreenNode { var existingAnnotations = node.GetAnnotations(); if (annotations == null || existingAnnotations.Length == 0) { return node; } var removalAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); removalAnnotations.AddRange(annotations); try { if (removalAnnotations.Count == 0) { return node; } var newAnnotations = ArrayBuilder<SyntaxAnnotation>.GetInstance(); foreach (var candidate in existingAnnotations) { if (!removalAnnotations.Contains(candidate)) { newAnnotations.Add(candidate); } } return (TNode)node.SetAnnotations(newAnnotations.ToArrayAndFree()); } finally { removalAnnotations.Free(); } } public static TNode WithDiagnosticsGreen<TNode>(this TNode node, DiagnosticInfo[]? diagnostics) where TNode : GreenNode { return (TNode)node.SetDiagnostics(diagnostics); } public static TNode WithoutDiagnosticsGreen<TNode>(this TNode node) where TNode : GreenNode { var current = node.GetDiagnostics(); if (current == null || current.Length == 0) { return node; } return (TNode)node.SetDiagnostics(null); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/VisualStudio/Core/Def/Interactive/VsInteractiveWindowPackage.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias InteractiveHost; using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using InteractiveHostFatalError = InteractiveHost::Microsoft.CodeAnalysis.ErrorReporting.FatalError; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Interactive { internal abstract partial class VsInteractiveWindowPackage<TVsInteractiveWindowProvider> : AsyncPackage, IVsToolWindowFactory where TVsInteractiveWindowProvider : VsInteractiveWindowProvider { protected abstract void InitializeMenuCommands(OleMenuCommandService menuCommandService); protected abstract Guid LanguageServiceGuid { get; } protected abstract Guid ToolWindowId { get; } private IComponentModel _componentModel; private TVsInteractiveWindowProvider _interactiveWindowProvider; protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var shell = (IVsShell)await GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true); _componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); var menuCommandService = (OleMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true); cancellationToken.ThrowIfCancellationRequested(); Assumes.Present(shell); Assumes.Present(_componentModel); Assumes.Present(menuCommandService); // Set both handlers to non-fatal Watson. Never fail-fast the VS process. // Any exception that is not recovered from shall be propagated. var nonFatalHandler = new Action<Exception>(WatsonReporter.ReportNonFatal); var fatalHandler = nonFatalHandler; InteractiveHostFatalError.Handler = fatalHandler; InteractiveHostFatalError.NonFatalHandler = nonFatalHandler; // Load the Roslyn package so that its FatalError handlers are hooked up. shell.LoadPackage(Guids.RoslynPackageId, out var roslynPackage); // Explicitly set up FatalError handlers for the InteractiveWindowPackage. SetErrorHandlers(typeof(IInteractiveWindow).Assembly, fatalHandler, nonFatalHandler); SetErrorHandlers(typeof(IVsInteractiveWindow).Assembly, fatalHandler, nonFatalHandler); _interactiveWindowProvider = _componentModel.DefaultExportProvider.GetExportedValue<TVsInteractiveWindowProvider>(); InitializeMenuCommands(menuCommandService); } private static void SetErrorHandlers(Assembly assembly, Action<Exception> fatalHandler, Action<Exception> nonFatalHandler) { var type = assembly.GetType("Microsoft.VisualStudio.InteractiveWindow.FatalError", throwOnError: true).GetTypeInfo(); var handlerSetter = type.GetDeclaredMethod("set_Handler"); var nonFatalHandlerSetter = type.GetDeclaredMethod("set_NonFatalHandler"); handlerSetter.Invoke(null, new object[] { fatalHandler }); nonFatalHandlerSetter.Invoke(null, new object[] { nonFatalHandler }); } protected TVsInteractiveWindowProvider InteractiveWindowProvider { get { return _interactiveWindowProvider; } } /// <summary> /// When a VSPackage supports multi-instance tool windows, each window uses the same rguidPersistenceSlot. /// The dwToolWindowId parameter is used to differentiate between the various instances of the tool window. /// </summary> int IVsToolWindowFactory.CreateToolWindow(ref Guid rguidPersistenceSlot, uint id) { if (rguidPersistenceSlot == ToolWindowId) { _interactiveWindowProvider.Create((int)id); return VSConstants.S_OK; } return VSConstants.E_FAIL; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable extern alias InteractiveHost; using System; using System.ComponentModel.Design; using System.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Shell; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using InteractiveHostFatalError = InteractiveHost::Microsoft.CodeAnalysis.ErrorReporting.FatalError; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Interactive { internal abstract partial class VsInteractiveWindowPackage<TVsInteractiveWindowProvider> : AsyncPackage, IVsToolWindowFactory where TVsInteractiveWindowProvider : VsInteractiveWindowProvider { protected abstract void InitializeMenuCommands(OleMenuCommandService menuCommandService); protected abstract Guid LanguageServiceGuid { get; } protected abstract Guid ToolWindowId { get; } private IComponentModel _componentModel; private TVsInteractiveWindowProvider _interactiveWindowProvider; protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress).ConfigureAwait(true); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var shell = (IVsShell)await GetServiceAsync(typeof(SVsShell)).ConfigureAwait(true); _componentModel = (IComponentModel)await GetServiceAsync(typeof(SComponentModel)).ConfigureAwait(true); var menuCommandService = (OleMenuCommandService)await GetServiceAsync(typeof(IMenuCommandService)).ConfigureAwait(true); cancellationToken.ThrowIfCancellationRequested(); Assumes.Present(shell); Assumes.Present(_componentModel); Assumes.Present(menuCommandService); // Set both handlers to non-fatal Watson. Never fail-fast the VS process. // Any exception that is not recovered from shall be propagated. var nonFatalHandler = new Action<Exception>(WatsonReporter.ReportNonFatal); var fatalHandler = nonFatalHandler; InteractiveHostFatalError.Handler = fatalHandler; InteractiveHostFatalError.NonFatalHandler = nonFatalHandler; // Load the Roslyn package so that its FatalError handlers are hooked up. shell.LoadPackage(Guids.RoslynPackageId, out var roslynPackage); // Explicitly set up FatalError handlers for the InteractiveWindowPackage. SetErrorHandlers(typeof(IInteractiveWindow).Assembly, fatalHandler, nonFatalHandler); SetErrorHandlers(typeof(IVsInteractiveWindow).Assembly, fatalHandler, nonFatalHandler); _interactiveWindowProvider = _componentModel.DefaultExportProvider.GetExportedValue<TVsInteractiveWindowProvider>(); InitializeMenuCommands(menuCommandService); } private static void SetErrorHandlers(Assembly assembly, Action<Exception> fatalHandler, Action<Exception> nonFatalHandler) { var type = assembly.GetType("Microsoft.VisualStudio.InteractiveWindow.FatalError", throwOnError: true).GetTypeInfo(); var handlerSetter = type.GetDeclaredMethod("set_Handler"); var nonFatalHandlerSetter = type.GetDeclaredMethod("set_NonFatalHandler"); handlerSetter.Invoke(null, new object[] { fatalHandler }); nonFatalHandlerSetter.Invoke(null, new object[] { nonFatalHandler }); } protected TVsInteractiveWindowProvider InteractiveWindowProvider { get { return _interactiveWindowProvider; } } /// <summary> /// When a VSPackage supports multi-instance tool windows, each window uses the same rguidPersistenceSlot. /// The dwToolWindowId parameter is used to differentiate between the various instances of the tool window. /// </summary> int IVsToolWindowFactory.CreateToolWindow(ref Guid rguidPersistenceSlot, uint id) { if (rguidPersistenceSlot == ToolWindowId) { _interactiveWindowProvider.Create((int)id); return VSConstants.S_OK; } return VSConstants.E_FAIL; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.Utilities Imports IVsTextBufferCoordinator = Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferCoordinator Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Friend Class VisualBasicContainedLanguage Inherits ContainedLanguage Implements IVsContainedLanguageStaticEventBinding Public Sub New(bufferCoordinator As IVsTextBufferCoordinator, componentModel As IComponentModel, project As VisualStudioProject, hierarchy As IVsHierarchy, itemid As UInteger, languageServiceGuid As Guid) MyBase.New( bufferCoordinator, componentModel, componentModel.GetService(Of VisualStudioWorkspace)(), project.Id, project, ContainedLanguage.GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, VisualBasicHelperFormattingRule.Instance) End Sub Public Function AddStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.AddStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=False, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.AddStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Public Function EnsureStaticEventHandler(pszClassName As String, pszObjectTypeName As String, pszObjectName As String, pszNameOfEvent As String, pszEventHandlerName As String, itemidInsertionPoint As UInteger, ByRef pbstrUniqueMemberID As String, ByRef pbstrEventBody As String, pSpanInsertionPoint() As VsTextSpan) As Integer Implements IVsContainedLanguageStaticEventBinding.EnsureStaticEventHandler Dim thisDocument = GetThisDocument() Dim targetDocumentId = Me.ContainedDocument.FindProjectDocumentIdWithItemId(itemidInsertionPoint) Dim targetDocument = thisDocument.Project.Solution.GetDocument(targetDocumentId) If targetDocument Is Nothing Then Throw New InvalidOperationException("Can't generate into that itemid") End If Dim idBodyAndInsertionPoint = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument, targetDocument, pszClassName, pszObjectName, pszObjectTypeName, pszNameOfEvent, pszEventHandlerName, itemidInsertionPoint, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) pbstrUniqueMemberID = idBodyAndInsertionPoint.Item1 pbstrEventBody = idBodyAndInsertionPoint.Item2 pSpanInsertionPoint(0) = idBodyAndInsertionPoint.Item3 Return VSConstants.S_OK End Function Public Function GetStaticEventBindingsForObject(pszClassName As String, pszObjectName As String, ByRef pcMembers As Integer, ppbstrEventNames As IntPtr, ppbstrDisplayNames As IntPtr, ppbstrMemberIDs As IntPtr) As Integer Implements IVsContainedLanguageStaticEventBinding.GetStaticEventBindingsForObject Dim members As Integer Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim eventNamesAndMemberNamesAndIds = ContainedLanguageStaticEventBinding.GetStaticEventBindings( GetThisDocument(), pszClassName, pszObjectName, c.UserCancellationToken) members = eventNamesAndMemberNamesAndIds.Count() CreateBSTRArray(ppbstrEventNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item1)) CreateBSTRArray(ppbstrDisplayNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item2)) CreateBSTRArray(ppbstrMemberIDs, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item3)) End Sub) pcMembers = members Return VSConstants.S_OK End Function Public Function RemoveStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.RemoveStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.RemoveStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Private Class VisualBasicHelperFormattingRule Inherits CompatAbstractFormattingRule Public Shared Shadows Instance As AbstractFormattingRule = New VisualBasicHelperFormattingRule() Public Overrides Sub AddIndentBlockOperationsSlow(list As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextOperation As NextIndentBlockOperationAction) ' we need special behavior for VB due to @Helper code generation weird-ness. ' this will looking for code gen specific style to make it not so expansive If IsEndHelperPattern(node) Then Return End If Dim multiLineLambda = TryCast(node, MultiLineLambdaExpressionSyntax) If multiLineLambda IsNot Nothing AndAlso IsHelperSubLambda(multiLineLambda) Then Return End If MyBase.AddIndentBlockOperationsSlow(list, node, nextOperation) End Sub Private Shared Function IsHelperSubLambda(multiLineLambda As MultiLineLambdaExpressionSyntax) As Boolean If multiLineLambda.Kind <> SyntaxKind.MultiLineSubLambdaExpression Then Return False End If If multiLineLambda.SubOrFunctionHeader Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters.Count <> 1 OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters(0).Identifier.Identifier.Text <> "__razor_helper_writer" Then Return False End If Return True End Function Private Shared Function IsEndHelperPattern(node As SyntaxNode) As Boolean If Not node.HasStructuredTrivia Then Return False End If Dim method = TryCast(node, MethodBlockSyntax) If method Is Nothing OrElse method.Statements.Count <> 2 Then Return False End If Dim statementWithEndHelper = method.Statements(0) Dim endToken = statementWithEndHelper.GetFirstToken() If endToken.Kind <> SyntaxKind.EndKeyword Then Return False End If Dim helperToken = endToken.GetNextToken(includeSkipped:=True) If helperToken.Kind <> SyntaxKind.IdentifierToken OrElse Not String.Equals(helperToken.Text, "Helper", StringComparison.OrdinalIgnoreCase) Then Return False End If Dim asToken = helperToken.GetNextToken(includeSkipped:=True) If asToken.Kind <> SyntaxKind.AsKeyword Then Return False End If Return True End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus Imports Microsoft.VisualStudio.Shell.Interop Imports Microsoft.VisualStudio.Utilities Imports IVsTextBufferCoordinator = Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferCoordinator Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus Friend Class VisualBasicContainedLanguage Inherits ContainedLanguage Implements IVsContainedLanguageStaticEventBinding Public Sub New(bufferCoordinator As IVsTextBufferCoordinator, componentModel As IComponentModel, project As VisualStudioProject, hierarchy As IVsHierarchy, itemid As UInteger, languageServiceGuid As Guid) MyBase.New( bufferCoordinator, componentModel, componentModel.GetService(Of VisualStudioWorkspace)(), project.Id, project, ContainedLanguage.GetFilePathFromHierarchyAndItemId(hierarchy, itemid), languageServiceGuid, VisualBasicHelperFormattingRule.Instance) End Sub Public Function AddStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.AddStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=False, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.AddStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Public Function EnsureStaticEventHandler(pszClassName As String, pszObjectTypeName As String, pszObjectName As String, pszNameOfEvent As String, pszEventHandlerName As String, itemidInsertionPoint As UInteger, ByRef pbstrUniqueMemberID As String, ByRef pbstrEventBody As String, pSpanInsertionPoint() As VsTextSpan) As Integer Implements IVsContainedLanguageStaticEventBinding.EnsureStaticEventHandler Dim thisDocument = GetThisDocument() Dim targetDocumentId = Me.ContainedDocument.FindProjectDocumentIdWithItemId(itemidInsertionPoint) Dim targetDocument = thisDocument.Project.Solution.GetDocument(targetDocumentId) If targetDocument Is Nothing Then Throw New InvalidOperationException("Can't generate into that itemid") End If Dim idBodyAndInsertionPoint = ContainedLanguageCodeSupport.EnsureEventHandler( thisDocument, targetDocument, pszClassName, pszObjectName, pszObjectTypeName, pszNameOfEvent, pszEventHandlerName, itemidInsertionPoint, useHandlesClause:=True, additionalFormattingRule:=LineAdjustmentFormattingRule.Instance, cancellationToken:=Nothing) pbstrUniqueMemberID = idBodyAndInsertionPoint.Item1 pbstrEventBody = idBodyAndInsertionPoint.Item2 pSpanInsertionPoint(0) = idBodyAndInsertionPoint.Item3 Return VSConstants.S_OK End Function Public Function GetStaticEventBindingsForObject(pszClassName As String, pszObjectName As String, ByRef pcMembers As Integer, ppbstrEventNames As IntPtr, ppbstrDisplayNames As IntPtr, ppbstrMemberIDs As IntPtr) As Integer Implements IVsContainedLanguageStaticEventBinding.GetStaticEventBindingsForObject Dim members As Integer Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim eventNamesAndMemberNamesAndIds = ContainedLanguageStaticEventBinding.GetStaticEventBindings( GetThisDocument(), pszClassName, pszObjectName, c.UserCancellationToken) members = eventNamesAndMemberNamesAndIds.Count() CreateBSTRArray(ppbstrEventNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item1)) CreateBSTRArray(ppbstrDisplayNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item2)) CreateBSTRArray(ppbstrMemberIDs, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item3)) End Sub) pcMembers = members Return VSConstants.S_OK End Function Public Function RemoveStaticEventBinding(pszClassName As String, pszUniqueMemberID As String, pszObjectName As String, pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.RemoveStaticEventBinding Me.ComponentModel.GetService(Of IUIThreadOperationExecutor)().Execute( BasicVSResources.IntelliSense, defaultDescription:="", allowCancellation:=False, showProgress:=Nothing, action:=Sub(c) Dim visualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Dim document = GetThisDocument() ContainedLanguageStaticEventBinding.RemoveStaticEventBinding( document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.UserCancellationToken) End Sub) Return VSConstants.S_OK End Function Private Class VisualBasicHelperFormattingRule Inherits CompatAbstractFormattingRule Public Shared Shadows Instance As AbstractFormattingRule = New VisualBasicHelperFormattingRule() Public Overrides Sub AddIndentBlockOperationsSlow(list As List(Of IndentBlockOperation), node As SyntaxNode, ByRef nextOperation As NextIndentBlockOperationAction) ' we need special behavior for VB due to @Helper code generation weird-ness. ' this will looking for code gen specific style to make it not so expansive If IsEndHelperPattern(node) Then Return End If Dim multiLineLambda = TryCast(node, MultiLineLambdaExpressionSyntax) If multiLineLambda IsNot Nothing AndAlso IsHelperSubLambda(multiLineLambda) Then Return End If MyBase.AddIndentBlockOperationsSlow(list, node, nextOperation) End Sub Private Shared Function IsHelperSubLambda(multiLineLambda As MultiLineLambdaExpressionSyntax) As Boolean If multiLineLambda.Kind <> SyntaxKind.MultiLineSubLambdaExpression Then Return False End If If multiLineLambda.SubOrFunctionHeader Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList Is Nothing OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters.Count <> 1 OrElse multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters(0).Identifier.Identifier.Text <> "__razor_helper_writer" Then Return False End If Return True End Function Private Shared Function IsEndHelperPattern(node As SyntaxNode) As Boolean If Not node.HasStructuredTrivia Then Return False End If Dim method = TryCast(node, MethodBlockSyntax) If method Is Nothing OrElse method.Statements.Count <> 2 Then Return False End If Dim statementWithEndHelper = method.Statements(0) Dim endToken = statementWithEndHelper.GetFirstToken() If endToken.Kind <> SyntaxKind.EndKeyword Then Return False End If Dim helperToken = endToken.GetNextToken(includeSkipped:=True) If helperToken.Kind <> SyntaxKind.IdentifierToken OrElse Not String.Equals(helperToken.Text, "Helper", StringComparison.OrdinalIgnoreCase) Then Return False End If Dim asToken = helperToken.GetNextToken(includeSkipped:=True) If asToken.Kind <> SyntaxKind.AsKeyword Then Return False End If Return True End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedParametersTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Public Class RemoveUnusedParametersTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), New VisualBasicRemoveUnusedValuesCodeFixProvider()) End Function ' Ensure that we explicitly test missing UnusedParameterDiagnosticId, which has no corresponding code fix (non-fixable diagnostic). Private Overloads Function TestDiagnosticMissingAsync(initialMarkup As String) As Task Return TestDiagnosticMissingAsync(initialMarkup, New TestParameters(retainNonFixableDiagnostics:=True)) End Function Private Shared Function Diagnostic(id As String) As DiagnosticDescription Return TestHelpers.Diagnostic(id) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_Used() As Task Await TestDiagnosticMissingAsync( $"Class C Sub M([|p|] As Integer) Dim x = p End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_Unused() As Task Await TestDiagnosticsAsync( $"Class C Sub M([|p|] As Integer) End Sub End Class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_WrittenOnly() As Task Await TestDiagnosticsAsync( $"Class C Sub M([|p|] As Integer) p = 1 End Sub End Class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_WrittenThenRead() As Task Await TestDiagnosticsAsync( $"Class C Function M([|p|] As Integer) As Integer p = 1 Return p End Function End Class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function ParameterOfMethodThatHandlesEvent() As Task Await TestDiagnosticMissingAsync( $"Public Class C Public Event E(p As Integer) Dim WithEvents field As New C Public Sub M([|p|] As Integer) Handles field.E End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_ConditionalDirective() As Task Await TestDiagnosticMissingAsync( $"Public Class C Public Sub M([|p|] As Integer) #If DEBUG Then System.Console.WriteLine(p) #End If End Sub End Class") End Function <WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_Unused_SpecialNames() As Task Await TestDiagnosticMissingAsync( $"Class C [|Sub M(_0 As Integer, _1 As Char, _3 As C)|] End Sub End Class") End Function <WorkItem(36816, "https://github.com/dotnet/roslyn/issues/36816")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function PartialMethodParameter_NoDiagnostic() As Task Await TestDiagnosticMissingAsync( $"Class C [|Partial Private Sub M(str As String)|] End Sub End Class Partial Class C Private Sub M(str As String) Dim x = str.ToString() End Sub End Class") End Function <WorkItem(37988, "https://github.com/dotnet/roslyn/issues/37988")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function XmlLiteral_NoDiagnostic() As Task Await TestDiagnosticMissingAsync( $"Public Class C Sub M([|param|] As System.Xml.Linq.XElement) Dim a = param.<Test> Dim b = param.@Test Dim c = param...<Test> End Sub End Class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_NoDiagnostic1() As Task Await TestDiagnosticMissingAsync( "imports system class C private sub Goo([|i|] as integer) throw new NotImplementedException() end sub end class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_NoDiagnostic2() As Task Await TestDiagnosticMissingAsync( "imports system class C private function Goo([|i|] as integer) as integer throw new NotImplementedException() end function end class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_NoDiagnostic3() As Task Await TestDiagnosticMissingAsync( "imports system class C public sub new([|i|] as integer) throw new NotImplementedException() end sub end class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_MultipleStatements1() As Task Await TestDiagnosticsAsync( "imports system class C private sub Goo([|i|] as integer) throw new NotImplementedException() return end sub end class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_MultipleStatements2() As Task Await TestMissingAsync( "imports system class C private sub Goo([|i|] as integer) if (true) throw new NotImplementedException() end sub end class") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Public Class RemoveUnusedParametersTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), New VisualBasicRemoveUnusedValuesCodeFixProvider()) End Function ' Ensure that we explicitly test missing UnusedParameterDiagnosticId, which has no corresponding code fix (non-fixable diagnostic). Private Overloads Function TestDiagnosticMissingAsync(initialMarkup As String) As Task Return TestDiagnosticMissingAsync(initialMarkup, New TestParameters(retainNonFixableDiagnostics:=True)) End Function Private Shared Function Diagnostic(id As String) As DiagnosticDescription Return TestHelpers.Diagnostic(id) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_Used() As Task Await TestDiagnosticMissingAsync( $"Class C Sub M([|p|] As Integer) Dim x = p End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_Unused() As Task Await TestDiagnosticsAsync( $"Class C Sub M([|p|] As Integer) End Sub End Class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_WrittenOnly() As Task Await TestDiagnosticsAsync( $"Class C Sub M([|p|] As Integer) p = 1 End Sub End Class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_WrittenThenRead() As Task Await TestDiagnosticsAsync( $"Class C Function M([|p|] As Integer) As Integer p = 1 Return p End Function End Class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function ParameterOfMethodThatHandlesEvent() As Task Await TestDiagnosticMissingAsync( $"Public Class C Public Event E(p As Integer) Dim WithEvents field As New C Public Sub M([|p|] As Integer) Handles field.E End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_ConditionalDirective() As Task Await TestDiagnosticMissingAsync( $"Public Class C Public Sub M([|p|] As Integer) #If DEBUG Then System.Console.WriteLine(p) #End If End Sub End Class") End Function <WorkItem(32851, "https://github.com/dotnet/roslyn/issues/32851")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function Parameter_Unused_SpecialNames() As Task Await TestDiagnosticMissingAsync( $"Class C [|Sub M(_0 As Integer, _1 As Char, _3 As C)|] End Sub End Class") End Function <WorkItem(36816, "https://github.com/dotnet/roslyn/issues/36816")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function PartialMethodParameter_NoDiagnostic() As Task Await TestDiagnosticMissingAsync( $"Class C [|Partial Private Sub M(str As String)|] End Sub End Class Partial Class C Private Sub M(str As String) Dim x = str.ToString() End Sub End Class") End Function <WorkItem(37988, "https://github.com/dotnet/roslyn/issues/37988")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function XmlLiteral_NoDiagnostic() As Task Await TestDiagnosticMissingAsync( $"Public Class C Sub M([|param|] As System.Xml.Linq.XElement) Dim a = param.<Test> Dim b = param.@Test Dim c = param...<Test> End Sub End Class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_NoDiagnostic1() As Task Await TestDiagnosticMissingAsync( "imports system class C private sub Goo([|i|] as integer) throw new NotImplementedException() end sub end class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_NoDiagnostic2() As Task Await TestDiagnosticMissingAsync( "imports system class C private function Goo([|i|] as integer) as integer throw new NotImplementedException() end function end class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_NoDiagnostic3() As Task Await TestDiagnosticMissingAsync( "imports system class C public sub new([|i|] as integer) throw new NotImplementedException() end sub end class") End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_MultipleStatements1() As Task Await TestDiagnosticsAsync( "imports system class C private sub Goo([|i|] as integer) throw new NotImplementedException() return end sub end class", parameters:=Nothing, Diagnostic(IDEDiagnosticIds.UnusedParameterDiagnosticId)) End Function <WorkItem(41236, "https://github.com/dotnet/roslyn/issues/41236")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedParameters)> Public Async Function NotImplementedException_MultipleStatements2() As Task Await TestMissingAsync( "imports system class C private sub Goo([|i|] as integer) if (true) throw new NotImplementedException() end sub end class") End Function End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsReportExternalErrors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { private readonly ProjectExternalErrorReporter _externalErrorReporter; int IVsReportExternalErrors.AddNewErrors(IVsEnumExternalErrors pErrors) => _externalErrorReporter.AddNewErrors(pErrors); int IVsReportExternalErrors.ClearAllErrors() => _externalErrorReporter.ClearAllErrors(); int IVsLanguageServiceBuildErrorReporter.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsLanguageServiceBuildErrorReporter2.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsReportExternalErrors.GetErrors(out IVsEnumExternalErrors pErrors) => _externalErrorReporter.GetErrors(out pErrors); int IVsLanguageServiceBuildErrorReporter.ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } int IVsLanguageServiceBuildErrorReporter2.ReportError( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } void IVsLanguageServiceBuildErrorReporter2.ReportError2( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) { _externalErrorReporter.ReportError2( bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { private readonly ProjectExternalErrorReporter _externalErrorReporter; int IVsReportExternalErrors.AddNewErrors(IVsEnumExternalErrors pErrors) => _externalErrorReporter.AddNewErrors(pErrors); int IVsReportExternalErrors.ClearAllErrors() => _externalErrorReporter.ClearAllErrors(); int IVsLanguageServiceBuildErrorReporter.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsLanguageServiceBuildErrorReporter2.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsReportExternalErrors.GetErrors(out IVsEnumExternalErrors pErrors) => _externalErrorReporter.GetErrors(out pErrors); int IVsLanguageServiceBuildErrorReporter.ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } int IVsLanguageServiceBuildErrorReporter2.ReportError( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } void IVsLanguageServiceBuildErrorReporter2.ReportError2( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) { _externalErrorReporter.ReportError2( bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/CSharpTest2/Recommendations/EndIfKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EndIfKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [WorkItem(542971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542971")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIf() { await VerifyKeywordAsync( @"#if goo #$$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class EndIfKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [WorkItem(542971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542971")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIf() { await VerifyKeywordAsync( @"#if goo #$$"); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/Core/Portable/Diagnostic/SeverityFilter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents a set of filtered diagnostic severities. /// Currently, we only support filtering out Hidden and Info severities during build. /// </summary> [Flags] internal enum SeverityFilter { None = 0x00, Hidden = 0x01, Info = 0x10 } internal static class SeverityFilterExtensions { internal static bool Contains(this SeverityFilter severityFilter, ReportDiagnostic severity) { return severity switch { ReportDiagnostic.Hidden => (severityFilter & SeverityFilter.Hidden) != 0, ReportDiagnostic.Info => (severityFilter & SeverityFilter.Info) != 0, _ => false }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Represents a set of filtered diagnostic severities. /// Currently, we only support filtering out Hidden and Info severities during build. /// </summary> [Flags] internal enum SeverityFilter { None = 0x00, Hidden = 0x01, Info = 0x10 } internal static class SeverityFilterExtensions { internal static bool Contains(this SeverityFilter severityFilter, ReportDiagnostic severity) { return severity switch { ReportDiagnostic.Hidden => (severityFilter & SeverityFilter.Hidden) != 0, ReportDiagnostic.Info => (severityFilter & SeverityFilter.Info) != 0, _ => false }; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/Core/Portable/Collections/UnionCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; using System.Diagnostics; using Roslyn.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { /// <summary> /// Implements a readonly collection over a set of existing collections. This can be used to /// prevent having to copy items from one collection over to another (thus bloating space). /// /// Note: this is a *collection*, not a *set*. There is no removal of duplicated elements. This /// allows us to be able to efficiently do operations like CopyTo, Count, etc. in O(c) time /// instead of O(n) (where 'c' is the number of collections and 'n' is the number of elements). /// If you have a few collections with many elements in them, then this is an appropriate /// collection for you. /// </summary> internal class UnionCollection<T> : ICollection<T> { private readonly ImmutableArray<ICollection<T>> _collections; private int _count = -1; public static ICollection<T> Create(ICollection<T> coll1, ICollection<T> coll2) { Debug.Assert(coll1.IsReadOnly && coll2.IsReadOnly); // Often, one of the collections is empty. Avoid allocations in those cases. if (coll1.Count == 0) { return coll2; } if (coll2.Count == 0) { return coll1; } return new UnionCollection<T>(ImmutableArray.Create(coll1, coll2)); } public static ICollection<T> Create<TOrig>(ImmutableArray<TOrig> collections, Func<TOrig, ICollection<T>> selector) { Debug.Assert(collections.All(c => selector(c).IsReadOnly)); switch (collections.Length) { case 0: return SpecializedCollections.EmptyCollection<T>(); case 1: return selector(collections[0]); default: return new UnionCollection<T>(ImmutableArray.CreateRange(collections, selector)); } } private UnionCollection(ImmutableArray<ICollection<T>> collections) { Debug.Assert(!collections.IsDefault); _collections = collections; } public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { // PERF: Expansion of "return collections.Any(c => c.Contains(item));" // to avoid allocating a lambda. foreach (var c in _collections) { if (c.Contains(item)) { return true; } } return false; } public void CopyTo(T[] array, int arrayIndex) { var index = arrayIndex; foreach (var collection in _collections) { collection.CopyTo(array, index); index += collection.Count; } } public int Count { get { if (_count == -1) { _count = _collections.Sum(c => c.Count); } return _count; } } public bool IsReadOnly { get { return true; } } public bool Remove(T item) { throw new NotSupportedException(); } public IEnumerator<T> GetEnumerator() { return _collections.SelectMany(c => c).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; using System.Diagnostics; using Roslyn.Utilities; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis { /// <summary> /// Implements a readonly collection over a set of existing collections. This can be used to /// prevent having to copy items from one collection over to another (thus bloating space). /// /// Note: this is a *collection*, not a *set*. There is no removal of duplicated elements. This /// allows us to be able to efficiently do operations like CopyTo, Count, etc. in O(c) time /// instead of O(n) (where 'c' is the number of collections and 'n' is the number of elements). /// If you have a few collections with many elements in them, then this is an appropriate /// collection for you. /// </summary> internal class UnionCollection<T> : ICollection<T> { private readonly ImmutableArray<ICollection<T>> _collections; private int _count = -1; public static ICollection<T> Create(ICollection<T> coll1, ICollection<T> coll2) { Debug.Assert(coll1.IsReadOnly && coll2.IsReadOnly); // Often, one of the collections is empty. Avoid allocations in those cases. if (coll1.Count == 0) { return coll2; } if (coll2.Count == 0) { return coll1; } return new UnionCollection<T>(ImmutableArray.Create(coll1, coll2)); } public static ICollection<T> Create<TOrig>(ImmutableArray<TOrig> collections, Func<TOrig, ICollection<T>> selector) { Debug.Assert(collections.All(c => selector(c).IsReadOnly)); switch (collections.Length) { case 0: return SpecializedCollections.EmptyCollection<T>(); case 1: return selector(collections[0]); default: return new UnionCollection<T>(ImmutableArray.CreateRange(collections, selector)); } } private UnionCollection(ImmutableArray<ICollection<T>> collections) { Debug.Assert(!collections.IsDefault); _collections = collections; } public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { // PERF: Expansion of "return collections.Any(c => c.Contains(item));" // to avoid allocating a lambda. foreach (var c in _collections) { if (c.Contains(item)) { return true; } } return false; } public void CopyTo(T[] array, int arrayIndex) { var index = arrayIndex; foreach (var collection in _collections) { collection.CopyTo(array, index); index += collection.Count; } } public int Count { get { if (_count == -1) { _count = _collections.Sum(c => c.Count); } return _count; } } public bool IsReadOnly { get { return true; } } public bool Remove(T item) { throw new NotSupportedException(); } public IEnumerator<T> GetEnumerator() { return _collections.SelectMany(c => c).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/ToCountConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Count(). /// </summary> internal sealed class ToCountConverter : AbstractToMethodConverter { public ToCountConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo, selectExpression, modifyingExpression, trivia) { } protected override string MethodName => nameof(Enumerable.Count); // Checks that the expression is "0". protected override bool CanReplaceInitialization( ExpressionSyntax expression, CancellationToken cancellationToken) => expression is LiteralExpressionSyntax literalExpression && literalExpression.Token.ValueText == "0"; /// Input: /// foreach(...) /// { /// ... /// ... /// counter++; /// } /// /// Output: /// counter += queryGenerated.Count(); protected override StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression) => SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.AddAssignmentExpression, expression, CreateInvocationExpression(queryOrLinqInvocationExpression))); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { /// <summary> /// Provides a conversion to query.Count(). /// </summary> internal sealed class ToCountConverter : AbstractToMethodConverter { public ToCountConverter( ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo, ExpressionSyntax selectExpression, ExpressionSyntax modifyingExpression, SyntaxTrivia[] trivia) : base(forEachInfo, selectExpression, modifyingExpression, trivia) { } protected override string MethodName => nameof(Enumerable.Count); // Checks that the expression is "0". protected override bool CanReplaceInitialization( ExpressionSyntax expression, CancellationToken cancellationToken) => expression is LiteralExpressionSyntax literalExpression && literalExpression.Token.ValueText == "0"; /// Input: /// foreach(...) /// { /// ... /// ... /// counter++; /// } /// /// Output: /// counter += queryGenerated.Count(); protected override StatementSyntax CreateDefaultStatement(ExpressionSyntax queryOrLinqInvocationExpression, ExpressionSyntax expression) => SyntaxFactory.ExpressionStatement( SyntaxFactory.AssignmentExpression( SyntaxKind.AddAssignmentExpression, expression, CreateInvocationExpression(queryOrLinqInvocationExpression))); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/CSharp/Test/Semantic/Semantics/NullableTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class NullableSemanticTests : SemanticModelTestBase { [Fact, WorkItem(651624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651624")] public void NestedNullableWithAttemptedConversion() { var src = @"using System; class C { public void Main() { Nullable<Nullable<int>> x = null; Nullable<int> y = null; Console.WriteLine(x == y); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,16): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>' // Nullable<Nullable<int>> x = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Nullable<int>").WithArguments("System.Nullable<T>", "T", "int?"), // (7,25): error CS0019: Operator '==' cannot be applied to operands of type 'int??' and 'int?' // Console.WriteLine(x == y); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == y").WithArguments("==", "int??", "int?")); } [Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")] public void TestBug12347() { string source = @" using System; class C { static void Main() { string? s1 = null; Nullable<string> s2 = null; Console.WriteLine(s1.ToString() + s2.ToString()); } }"; var expected = new[] { // (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // string? s1 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 11), // (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // Nullable<string> s2 = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? s1 = null; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 11), // (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // Nullable<string> s2 = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14)); } [Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")] public void TestBug12347_CSharp8() { string source = @" using System; class C { static void Main() { string? s1 = null; Nullable<string> s2 = null; Console.WriteLine(s1.ToString() + s2.ToString()); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? s1 = null; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 15), // (8,18): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // Nullable<string> s2 = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 18) ); } [Fact, WorkItem(529269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529269")] public void TestLiftedIncrementOperatorBreakingChanges01() { // The native compiler not only *allows* this to compile, it lowers to: // // C temp1 = c; // int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1); // c = temp2.HasValue ? // C.op_Implicit_Nullable_Int_To_C(new short?((short)(temp2.GetValueOrDefault() + 1))) : // null; // // !!! // // Not only does the native compiler silently insert a data-losing conversion from int to short, // if the result of the initial conversion to int? is null, the result is a null *C*, not // an implicit conversion from a null *int?* to C. // // This should simply be disallowed. The increment on int? produces int?, and there is no implicit // conversion from int? to S. string source1 = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } public static implicit operator C(short? s) { return new C(s); } static void Main() { C c = new C(null); c++; System.Console.WriteLine(object.ReferenceEquals(c, null)); } }"; var comp = CreateCompilation(source1); comp.VerifyDiagnostics( // (11,5): error CS0266: Cannot implicitly convert type 'int?' to 'C'. An explicit conversion exists (are you missing a cast?) // c++; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c++").WithArguments("int?", "C") ); } [Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")] public void TestLiftedIncrementOperatorBreakingChanges02() { // Now here we have a case where the compilation *should* succeed, and does, but // the native compiler and Roslyn produce opposite behavior. Again, the native // compiler lowers this to: // // C temp1 = c; // int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1); // c = temp2.HasValue ? // C.op_Implicit_Nullable_Int_To_C(new int?(temp2.GetValueOrDefault() + 1)) : // null; // // And therefore produces "True". The correct lowering, performed by Roslyn, is: // // C temp1 = c; // int? temp2 = C.op_Implicit_C_To_Nullable_Int( temp1 ); // int? temp3 = temp2.HasValue ? // new int?(temp2.GetValueOrDefault() + 1)) : // default(int?); // c = C.op_Implicit_Nullable_Int_To_C(temp3); // // and therefore should produce "False". string source2 = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } public static implicit operator C(int? s) { return new C(s); } static void Main() { C c = new C(null); c++; System.Console.WriteLine(object.ReferenceEquals(c, null) ? 1 : 0); } }"; var verifier = CompileAndVerify(source: source2, expectedOutput: "0"); verifier = CompileAndVerify(source: source2, expectedOutput: "0"); // And in fact, this should work if there is an implicit conversion from the result of the addition // to the type: string source3 = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } // There is an implicit conversion from int? to long? and therefore from int? to S. public static implicit operator C(long? s) { return new C((int?)s); } static void Main() { C c1 = new C(null); c1++; C c2 = new C(123); c2++; System.Console.WriteLine(!object.ReferenceEquals(c1, null) && c2.i.Value == 124 ? 1 : 0); } }"; verifier = CompileAndVerify(source: source3, expectedOutput: "1", verify: Verification.Fails); verifier = CompileAndVerify(source: source3, expectedOutput: "1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); } [Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")] public void TestLiftedIncrementOperatorBreakingChanges03() { // Let's in fact verify that this works correctly for all possible conversions to built-in types: string source4 = @" using System; class C { public readonly TYPE? i; public C(TYPE? i) { this.i = i; } public static implicit operator TYPE?(C c) { return c.i; } public static implicit operator C(TYPE? s) { return new C(s); } static void Main() { TYPE q = 10; C x = new C(10); T(1, x.i.Value == q); T(2, (x++).i.Value == (q++)); T(3, x.i.Value == q); T(4, (++x).i.Value == (++q)); T(5, x.i.Value == q); T(6, (x--).i.Value == (q--)); T(7, x.i.Value == q); T(8, (--x).i.Value == (--q)); T(9, x.i.Value == q); C xn = new C(null); F(11, xn.i.HasValue); F(12, (xn++).i.HasValue); F(13, xn.i.HasValue); F(14, (++xn).i.HasValue); F(15, xn.i.HasValue); F(16, (xn--).i.HasValue); F(17, xn.i.HasValue); F(18, (--xn).i.HasValue); F(19, xn.i.HasValue); System.Console.WriteLine(0); } static void T(int line, bool b) { if (!b) throw new Exception(""TYPE"" + line.ToString()); } static void F(int line, bool b) { if (b) throw new Exception(""TYPE"" + line.ToString()); } } "; foreach (string type in new[] { "int", "ushort", "byte", "long", "float", "decimal" }) { CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", verify: Verification.Fails); CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); } } [Fact] public void TestLiftedBuiltInIncrementOperators() { string source = @" using System; class C { static void Main() { TYPE q = 10; TYPE? x = 10; T(1, x.Value == q); T(2, (x++).Value == (q++)); T(3, x.Value == q); T(4, (++x).Value == (++q)); T(5, x.Value == q); T(6, (x--).Value == (q--)); T(7, x.Value == q); T(8, (--x).Value == (--q)); T(9, x.Value == q); int? xn = null; F(11, xn.HasValue); F(12, (xn++).HasValue); F(13, xn.HasValue); F(14, (++xn).HasValue); F(15, xn.HasValue); F(16, (xn--).HasValue); F(17, xn.HasValue); F(18, (--xn).HasValue); F(19, xn.HasValue); System.Console.WriteLine(0); } static void T(int line, bool b) { if (!b) throw new Exception(""TYPE"" + line.ToString()); } static void F(int line, bool b) { if (b) throw new Exception(""TYPE"" + line.ToString()); } }"; foreach (string type in new[] { "uint", "short", "sbyte", "ulong", "double", "decimal" }) { string expected = "0"; var verifier = CompileAndVerify(source: source.Replace("TYPE", type), expectedOutput: expected); } } [Fact] public void TestLiftedUserDefinedIncrementOperators() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(1, n.Value.x == s.x); T(2, (n++).Value.x == (s++).x); T(3, n.Value.x == s.x); T(4, (n--).Value.x == (s--).x); T(5, n.Value.x == s.x); T(6, (++n).Value.x == (++s).x); T(7, n.Value.x == s.x); T(8, (--n).Value.x == (--s).x); T(9, n.Value.x == s.x); n = null; F(11, n.HasValue); F(12, (n++).HasValue); F(13, n.HasValue); F(14, (n--).HasValue); F(15, n.HasValue); F(16, (++n).HasValue); F(17, n.HasValue); F(18, (--n).HasValue); F(19, n.HasValue); Console.WriteLine(1); } static void T(int line, bool b) { if (!b) throw new Exception(line.ToString()); } static void F(int line, bool b) { if (b) throw new Exception(line.ToString()); } } "; var verifier = CompileAndVerify(source: source, expectedOutput: "1"); } [Fact] public void TestNullableBuiltInUnaryOperator() { string source = @" using System; class C { static void Main() { Console.Write('!'); bool? bf = false; bool? bt = true; bool? bn = null; Test((!bf).HasValue); Test((!bf).Value); Test((!bt).HasValue); Test((!bt).Value); Test((!bn).HasValue); Console.WriteLine(); Console.Write('-'); int? i32 = -1; int? i32n = null; Test((-i32).HasValue); Test((-i32) == 1); Test((-i32) == -1); Test((-i32n).HasValue); Console.Write(1); long? i64 = -1; long? i64n = null; Test((-i64).HasValue); Test((-i64) == 1); Test((-i64) == -1); Test((-i64n).HasValue); Console.Write(2); float? r32 = -1.5f; float? r32n = null; Test((-r32).HasValue); Test((-r32) == 1.5f); Test((-r32) == -1.5f); Test((-r32n).HasValue); Console.Write(3); double? r64 = -1.5; double? r64n = null; Test((-r64).HasValue); Test((-r64) == 1.5); Test((-r64) == -1.5); Test((-r64n).HasValue); Console.Write(4); decimal? d = -1.5m; decimal? dn = null; Test((-d).HasValue); Test((-d) == 1.5m); Test((-d) == -1.5m); Test((-dn).HasValue); Console.WriteLine(); Console.Write('+'); Test((+i32).HasValue); Test((+i32) == 1); Test((+i32) == -1); Test((+i32n).HasValue); Console.Write(1); uint? ui32 = 1; uint? ui32n = null; Test((+ui32).HasValue); Test((+ui32) == 1); Test((+ui32n).HasValue); Console.Write(2); Test((+i64).HasValue); Test((+i64) == 1); Test((+i64) == -1); Test((+i64n).HasValue); Console.Write(3); ulong? ui64 = 1; ulong? ui64n = null; Test((+ui64).HasValue); Test((+ui64) == 1); Test((+ui64n).HasValue); Console.Write(4); Test((+r32).HasValue); Test((+r32) == 1.5f); Test((+r32) == -1.5f); Test((+r32n).HasValue); Console.Write(5); Test((+r64).HasValue); Test((+r64) == 1.5); Test((+r64) == -1.5); Test((+r64n).HasValue); Console.Write(6); Test((+d).HasValue); Test((+d) == 1.5m); Test((+d) == -1.5m); Test((+dn).HasValue); Console.WriteLine(); Console.Write('~'); i32 = 1; Test((~i32).HasValue); Test((~i32) == -2); Test((~i32n).HasValue); Console.Write(1); Test((~ui32).HasValue); Test((~ui32) == 0xFFFFFFFE); Test((~ui32n).HasValue); Console.Write(2); i64 = 1; Test((~i64).HasValue); Test((~i64) == -2L); Test((~i64n).HasValue); Console.Write(3); Test((~ui64).HasValue); Test((~ui64) == 0xFFFFFFFFFFFFFFFE); Test((~ui64n).HasValue); Console.Write(4); Base64FormattingOptions? e = Base64FormattingOptions.InsertLineBreaks; Base64FormattingOptions? en = null; Test((~e).HasValue); Test((~e) == (Base64FormattingOptions)(-2)); Test((~en).HasValue); } static void Test(bool b) { Console.Write(b ? 'T' : 'F'); } }"; string expected = @"!TTTFF -TTFF1TTFF2TTFF3TTFF4TTFF +TFTF1TTF2TFTF3TTF4TFTF5TFTF6TFTF ~TTF1TTF2TTF3TTF4TTF"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestNullableUserDefinedUnary() { string source = @" using System; struct S { public S(char c) { this.str = c.ToString(); } public S(string str) { this.str = str; } public string str; public static S operator !(S s) { return new S('!' + s.str); } public static S operator ~(S s) { return new S('~' + s.str); } public static S operator -(S s) { return new S('-' + s.str); } public static S operator +(S s) { return new S('+' + s.str); } } class C { static void Main() { S? s = new S('x'); S? sn = null; Test((~s).HasValue); Test((~sn).HasValue); Console.WriteLine((~s).Value.str); Test((!s).HasValue); Test((!sn).HasValue); Console.WriteLine((!s).Value.str); Test((+s).HasValue); Test((+sn).HasValue); Console.WriteLine((+s).Value.str); Test((-s).HasValue); Test((-sn).HasValue); Console.WriteLine((-s).Value.str); } static void Test(bool b) { Console.Write(b ? 'T' : 'F'); } }"; string expected = @"TF~x TF!x TF+x TF-x"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7803")] public void TestLiftedComparison() { TestNullableComparison("==", "FFTFF1FTFFTF2FFTFFT3TFFTFF4FTFFTF5FFTFFT", "int", "short", "byte", "long", "double", "decimal", "char", "Base64FormattingOptions", "S", "bool"); TestNullableComparison("!=", "TTFTT1TFTTFT2TTFTTF3FTTFTT4TFTTFT5TTFTTF", "uint", "ushort", "sbyte", "ulong", "float", "decimal", "char", "Base64FormattingOptions", "S", "bool"); TestNullableComparison("<", "FFFFF1FFTFFT2FFFFFF3FFFFFF4FFTFFT5FFFFFF", "uint", "sbyte", "float", "decimal", "Base64FormattingOptions", "S"); TestNullableComparison("<=", "FFFFF1FTTFTT2FFTFFT3FFFFFF4FTTFTT5FFTFFT", "int", "byte", "double", "decimal", "char"); TestNullableComparison(">", "FFFFF1FFFFFF2FTFFTF3FFFFFF4FFFFFF5FTFFTF", "ushort", "ulong", "decimal"); TestNullableComparison(">=", "FFFFF1FTFFTF2FTTFTT3FFFFFF4FTFFTF5FTTFTT", "short", "long", "decimal"); } private void TestNullableComparison( string oper, string expected, params string[] types) { string source = @" using System; struct S { public int i; public S(int i) { this.i = i; } public static bool operator ==(S x, S y) { return x.i == y.i; } public static bool operator !=(S x, S y) { return x.i != y.i; } public static bool operator <(S x, S y) { return x.i < y.i; } public static bool operator <=(S x, S y) { return x.i <= y.i; } public static bool operator >(S x, S y) { return x.i > y.i; } public static bool operator >=(S x, S y) { return x.i >= y.i; } } class C { static void Main() { TYPE? xn0 = ZERO; TYPE? xn1 = ONE; TYPE? xnn = null; TYPE x0 = ZERO; TYPE x1 = ONE; TYPE? yn0 = ZERO; TYPE? yn1 = ONE; TYPE? ynn = null; TYPE y0 = ZERO; TYPE y1 = ONE; Test(null OP yn0); Test(null OP yn1); Test(null OP ynn); Test(null OP y0); Test(null OP y1); Console.Write('1'); Test(xn0 OP null); Test(xn0 OP yn0); Test(xn0 OP yn1); Test(xn0 OP ynn); Test(xn0 OP y0); Test(xn0 OP y1); Console.Write('2'); Test(xn1 OP null); Test(xn1 OP yn0); Test(xn1 OP yn1); Test(xn1 OP ynn); Test(xn1 OP y0); Test(xn1 OP y1); Console.Write('3'); Test(xnn OP null); Test(xnn OP yn0); Test(xnn OP yn1); Test(xnn OP ynn); Test(xnn OP y0); Test(xnn OP y1); Console.Write('4'); Test(x0 OP null); Test(x0 OP yn0); Test(x0 OP yn1); Test(x0 OP ynn); Test(x0 OP y0); Test(x0 OP y1); Console.Write('5'); Test(x1 OP null); Test(x1 OP yn0); Test(x1 OP yn1); Test(x1 OP ynn); Test(x1 OP y0); Test(x1 OP y1); } static void Test(bool b) { Console.Write(b ? 'T' : 'F'); } } "; var zeros = new Dictionary<string, string>() { { "int", "0" }, { "uint", "0" }, { "short", "0" }, { "ushort", "0" }, { "byte", "0" }, { "sbyte", "0" }, { "long", "0" }, { "ulong", "0" }, { "double", "0" }, { "float", "0" }, { "decimal", "0" }, { "char", "'a'" }, { "bool", "false" }, { "Base64FormattingOptions", "Base64FormattingOptions.None" }, { "S", "new S(0)" } }; var ones = new Dictionary<string, string>() { { "int", "1" }, { "uint", "1" }, { "short", "1" }, { "ushort", "1" }, { "byte", "1" }, { "sbyte", "1" }, { "long", "1" }, { "ulong", "1" }, { "double", "1" }, { "float", "1" }, { "decimal", "1" }, { "char", "'b'" }, { "bool", "true" }, { "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" }, { "S", "new S(1)" } }; foreach (string t in types) { string s = source.Replace("TYPE", t).Replace("OP", oper).Replace("ZERO", zeros[t]).Replace("ONE", ones[t]); var verifier = CompileAndVerify(source: s, expectedOutput: expected); } } [Fact] public void TestLiftedBuiltInBinaryArithmetic() { string[,] enumAddition = { //{ "sbyte", "Base64FormattingOptions"}, { "byte", "Base64FormattingOptions"}, //{ "short", "Base64FormattingOptions"}, { "ushort", "Base64FormattingOptions"}, //{ "int", "Base64FormattingOptions"}, //{ "uint", "Base64FormattingOptions"}, //{ "long", "Base64FormattingOptions"}, //{ "ulong", "Base64FormattingOptions"}, { "char", "Base64FormattingOptions"}, //{ "decimal", "Base64FormattingOptions"}, //{ "double", "Base64FormattingOptions"}, //{ "float", "Base64FormattingOptions"}, { "Base64FormattingOptions", "sbyte" }, { "Base64FormattingOptions", "byte" }, { "Base64FormattingOptions", "short" }, { "Base64FormattingOptions", "ushort" }, { "Base64FormattingOptions", "int" }, //{ "Base64FormattingOptions", "uint" }, //{ "Base64FormattingOptions", "long" }, //{ "Base64FormattingOptions", "ulong" }, { "Base64FormattingOptions", "char" }, //{ "Base64FormattingOptions", "decimal" }, //{ "Base64FormattingOptions", "double" }, //{ "Base64FormattingOptions", "float" }, //{ "Base64FormattingOptions", "Base64FormattingOptions"}, }; string[,] enumSubtraction = { { "Base64FormattingOptions", "sbyte" }, //{ "Base64FormattingOptions", "byte" }, { "Base64FormattingOptions", "short" }, { "Base64FormattingOptions", "ushort" }, { "Base64FormattingOptions", "int" }, //{ "Base64FormattingOptions", "uint" }, //{ "Base64FormattingOptions", "long" }, //{ "Base64FormattingOptions", "ulong" }, //{ "Base64FormattingOptions", "char" }, //{ "Base64FormattingOptions", "decimal" }, //{ "Base64FormattingOptions", "double" }, //{ "Base64FormattingOptions", "float" }, { "Base64FormattingOptions", "Base64FormattingOptions"}, }; string[,] numerics1 = { { "sbyte", "sbyte" }, { "sbyte", "byte" }, //{ "sbyte", "short" }, { "sbyte", "ushort" }, //{ "sbyte", "int" }, { "sbyte", "uint" }, //{ "sbyte", "long" }, //{ "sbyte", "ulong" }, //{ "sbyte", "char" }, { "sbyte", "decimal" }, { "sbyte", "double" }, //{ "sbyte", "float" }, //{ "byte", "sbyte" }, { "byte", "byte" }, //{ "byte", "short" }, { "byte", "ushort" }, //{ "byte", "int" }, { "byte", "uint" }, //{ "byte", "long" }, { "byte", "ulong" }, //{ "byte", "char" }, { "byte", "decimal" }, //{ "byte", "double" }, { "byte", "float" }, { "short", "sbyte" }, { "short", "byte" }, { "short", "short" }, //{ "short", "ushort" }, { "short", "int" }, //{ "short", "uint" }, { "short", "long" }, //{ "short", "ulong" }, //{ "short", "char" }, { "short", "decimal" }, //{ "short", "double" }, { "short", "float" }, }; string[,] numerics2 = { //{ "ushort", "sbyte" }, //{ "ushort", "byte" }, { "ushort", "short" }, { "ushort", "ushort" }, //{ "ushort", "int" }, { "ushort", "uint" }, { "ushort", "long" }, //{ "ushort", "ulong" }, //{ "ushort", "char" }, //{ "ushort", "decimal" }, //{ "ushort", "double" }, { "ushort", "float" }, { "int", "sbyte" }, { "int", "byte" }, //{ "int", "short" }, { "int", "ushort" }, { "int", "int" }, //{ "int", "uint" }, { "int", "long" }, // { "int", "ulong" }, { "int", "char" }, //{ "int", "decimal" }, { "int", "double" }, //{ "int", "float" }, //{ "uint", "sbyte" }, //{ "uint", "byte" }, { "uint", "short" }, //{ "uint", "ushort" }, { "uint", "int" }, { "uint", "uint" }, { "uint", "long" }, //{ "uint", "ulong" }, { "uint", "char" }, //{ "uint", "decimal" }, //{ "uint", "double" }, { "uint", "float" }, }; string[,] numerics3 = { { "long", "sbyte" }, { "long", "byte" }, //{ "long", "short" }, //{ "long", "ushort" }, //{ "long", "int" }, //{ "long", "uint" }, { "long", "long" }, // { "long", "ulong" }, { "long", "char" }, //{ "long", "decimal" }, //{ "long", "double" }, { "long", "float" }, //{ "ulong", "sbyte" }, //{ "ulong", "byte" }, //{ "ulong", "short" }, { "ulong", "ushort" }, //{ "ulong", "int" }, { "ulong", "uint" }, //{ "ulong", "long" }, { "ulong", "ulong" }, //{ "ulong", "char" }, { "ulong", "decimal" }, { "ulong", "double" }, //{ "ulong", "float" }, }; string[,] numerics4 = { { "char", "sbyte" }, { "char", "byte" }, { "char", "short" }, { "char", "ushort" }, //{ "char", "int" }, //{ "char", "uint" }, //{ "char", "long" }, { "char", "ulong" }, { "char", "char" }, //{ "char", "decimal" }, //{ "char", "double" }, { "char", "float" }, //{ "decimal", "sbyte" }, //{ "decimal", "byte" }, //{ "decimal", "short" }, { "decimal", "ushort" }, { "decimal", "int" }, { "decimal", "uint" }, { "decimal", "long" }, //{ "decimal", "ulong" }, { "decimal", "char" }, { "decimal", "decimal" }, //{ "decimal", "double" }, //{ "decimal", "float" }, }; string[,] numerics5 = { //{ "double", "sbyte" }, { "double", "byte" }, { "double", "short" }, { "double", "ushort" }, //{ "double", "int" }, { "double", "uint" }, { "double", "long" }, //{ "double", "ulong" }, { "double", "char" }, //{ "double", "decimal" }, { "double", "double" }, { "double", "float" }, { "float", "sbyte" }, //{ "float", "byte" }, //{ "float", "short" }, //{ "float", "ushort" }, { "float", "int" }, //{ "float", "uint" }, //{ "float", "long" }, { "float", "ulong" }, //{ "float", "char" }, //{ "float", "decimal" }, //{ "float", "double" }, { "float", "float" }, }; string[,] shift1 = { { "sbyte", "sbyte" }, { "sbyte", "byte" }, { "sbyte", "short" }, { "sbyte", "ushort" }, { "sbyte", "int" }, { "sbyte", "char" }, { "byte", "sbyte" }, { "byte", "byte" }, { "byte", "short" }, { "byte", "ushort" }, { "byte", "int" }, { "byte", "char" }, { "short", "sbyte" }, { "short", "byte" }, { "short", "short" }, { "short", "ushort" }, { "short", "int" }, { "short", "char" }, { "ushort", "sbyte" }, { "ushort", "byte" }, { "ushort", "short" }, { "ushort", "ushort" }, { "ushort", "int" }, { "ushort", "char" }, }; string[,] shift2 = { { "int", "sbyte" }, { "int", "byte" }, { "int", "short" }, { "int", "ushort" }, { "int", "int" }, { "int", "char" }, { "uint", "sbyte" }, { "uint", "byte" }, { "uint", "short" }, { "uint", "ushort" }, { "uint", "int" }, { "uint", "char" }, { "long", "sbyte" }, { "long", "byte" }, { "long", "short" }, { "long", "ushort" }, { "long", "int" }, { "long", "char" }, { "ulong", "sbyte" }, { "ulong", "byte" }, { "ulong", "short" }, { "ulong", "ushort" }, { "ulong", "int" }, { "ulong", "char" }, { "char", "sbyte" }, { "char", "byte" }, { "char", "short" }, { "char", "ushort" }, { "char", "int" }, { "char", "char" }, }; string[,] logical1 = { { "sbyte", "sbyte" }, //{ "sbyte", "byte" }, { "sbyte", "short" }, { "sbyte", "ushort" }, { "sbyte", "int" }, //{ "sbyte", "uint" }, { "sbyte", "long" }, //{ "sbyte", "ulong" }, //{ "sbyte", "char" }, { "byte", "sbyte" }, { "byte", "byte" }, //{ "byte", "short" }, { "byte", "ushort" }, //{ "byte", "int" }, { "byte", "uint" }, //{ "byte", "long" }, //{ "byte", "ulong" }, { "byte", "char" }, { "short", "sbyte" }, { "short", "byte" }, { "short", "short" }, //{ "short", "ushort" }, { "short", "int" }, //{ "short", "uint" }, { "short", "long" }, //{ "short", "ulong" }, { "short", "char" }, }; string[,] logical2 = { //{ "ushort", "sbyte" }, { "ushort", "byte" }, { "ushort", "short" }, { "ushort", "ushort" }, //{ "ushort", "int" }, { "ushort", "uint" }, //{ "ushort", "long" }, //{ "ushort", "ulong" }, //{ "ushort", "char" }, //{ "int", "sbyte" }, { "int", "byte" }, //{ "int", "short" }, { "int", "ushort" }, { "int", "int" }, //{ "int", "uint" }, { "int", "long" }, //{ "int", "ulong" }, //{ "int", "char" }, { "uint", "sbyte" }, //{ "uint", "byte" }, { "uint", "short" }, //{ "uint", "ushort" }, { "uint", "int" }, { "uint", "uint" }, //{ "uint", "long" }, //{ "uint", "ulong" }, { "uint", "char" }, }; string[,] logical3 = { //{ "long", "sbyte" }, { "long", "byte" }, //{ "long", "short" }, { "long", "ushort" }, //{ "long", "int" }, { "long", "uint" }, { "long", "long" }, // { "long", "ulong" }, { "long", "char" }, //{ "ulong", "sbyte" }, { "ulong", "byte" }, //{ "ulong", "short" }, { "ulong", "ushort" }, //{ "ulong", "int" }, { "ulong", "uint" }, //{ "ulong", "long" }, { "ulong", "ulong" }, //{ "ulong", "char" }, { "char", "sbyte" }, //{ "char", "byte" }, //{ "char", "short" }, { "char", "ushort" }, { "char", "int" }, //{ "char", "uint" }, //{ "char", "long" }, { "char", "ulong" }, { "char", "char" }, { "Base64FormattingOptions", "Base64FormattingOptions"}, }; // Use 2 instead of 0 so that we don't get divide by zero errors. var twos = new Dictionary<string, string>() { { "int", "2" }, { "uint", "2" }, { "short", "2" }, { "ushort", "2" }, { "byte", "2" }, { "sbyte", "2" }, { "long", "2" }, { "ulong", "2" }, { "double", "2" }, { "float", "2" }, { "decimal", "2" }, { "char", "'\\u0002'" }, { "Base64FormattingOptions", "Base64FormattingOptions.None" }, }; var ones = new Dictionary<string, string>() { { "int", "1" }, { "uint", "1" }, { "short", "1" }, { "ushort", "1" }, { "byte", "1" }, { "sbyte", "1" }, { "long", "1" }, { "ulong", "1" }, { "double", "1" }, { "float", "1" }, { "decimal", "1" }, { "char", "'\\u0001'" }, { "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" }, }; var names = new Dictionary<string, string>() { { "+", "plus" }, { "-", "minus" }, { "*", "times" }, { "/", "divide" }, { "%", "remainder" }, { ">>", "rshift" }, { "<<", "lshift" }, { "&", "and" }, { "|", "or" }, { "^", "xor" } }; var source = new StringBuilder(@" using System; class C { static void T(int x, bool b) { if (!b) throw new Exception(x.ToString()); } static void F(int x, bool b) { if (b) throw new Exception(x.ToString()); } "); string main = "static void Main() {"; string method = @" static void METHOD_TYPEX_NAME_TYPEY() { TYPEX? xn0 = TWOX; TYPEX? xn1 = ONEX; TYPEX? xnn = null; TYPEX x0 = TWOX; TYPEX x1 = ONEX; TYPEY? yn0 = TWOY; TYPEY? yn1 = ONEY; TYPEY? ynn = null; TYPEY y0 = TWOY; TYPEY y1 = ONEY; F(1, (null OP yn0).HasValue); F(2, (null OP yn1).HasValue); F(3, (null OP ynn).HasValue); F(4, (null OP y0).HasValue); F(5, (null OP y1).HasValue); F(6, (xn0 OP null).HasValue); T(7, (xn0 OP yn0).Value == (x0 OP y0)); T(8, (xn0 OP yn1).Value == (x0 OP y1)); F(9, (xn0 OP ynn).HasValue); T(10, (xn0 OP y0).Value == (x0 OP y0)); T(11, (xn0 OP y1).Value == (x0 OP y1)); F(12, (xn1 OP null).HasValue); T(13, (xn1 OP yn0).Value == (x1 OP y0)); T(14, (xn1 OP yn1).Value == (x1 OP y1)); F(15, (xn1 OP ynn).HasValue); T(16, (xn1 OP y0).Value == (x1 OP y0)); T(17, (xn1 OP y1).Value == (x1 OP y1)); F(18, (xnn OP null).HasValue); F(19, (xnn OP yn0).HasValue); F(20, (xnn OP yn1).HasValue); F(21, (xnn OP ynn).HasValue); F(22, (xnn OP y0).HasValue); F(23, (xnn OP y1).HasValue); F(24, (x0 OP null).HasValue); T(25, (x0 OP yn0).Value == (x0 OP y0)); T(26, (x0 OP yn1).Value == (x0 OP y1)); F(27, (x0 OP ynn).HasValue); F(28, (x1 OP null).HasValue); T(29, (x1 OP yn0).Value == (x1 OP y0)); T(30, (x1 OP yn1).Value == (x1 OP y1)); F(31, (x1 OP ynn).HasValue); }"; List<Tuple<string, string[,]>> items = new List<Tuple<string, string[,]>>() { Tuple.Create("*", numerics1), Tuple.Create("/", numerics2), Tuple.Create("%", numerics3), Tuple.Create("+", numerics4), Tuple.Create("+", enumAddition), Tuple.Create("-", numerics5), // UNDONE: Overload resolution of "enum - null" , // UNDONE: so this test is disabled: // UNDONE: Tuple.Create("-", enumSubtraction), Tuple.Create(">>", shift1), Tuple.Create("<<", shift2), Tuple.Create("&", logical1), Tuple.Create("|", logical2), Tuple.Create("^", logical3) }; int m = 0; foreach (var item in items) { string oper = item.Item1; string[,] types = item.Item2; for (int i = 0; i < types.GetLength(0); ++i) { ++m; string typeX = types[i, 0]; string typeY = types[i, 1]; source.Append(method .Replace("METHOD", "M" + m) .Replace("TYPEX", typeX) .Replace("TYPEY", typeY) .Replace("OP", oper) .Replace("NAME", names[oper]) .Replace("TWOX", twos[typeX]) .Replace("ONEX", ones[typeX]) .Replace("TWOY", twos[typeY]) .Replace("ONEY", ones[typeY])); main += "M" + m + "_" + typeX + "_" + names[oper] + "_" + typeY + "();\n"; } } source.Append(main); source.Append("} }"); var verifier = CompileAndVerify(source: source.ToString(), expectedOutput: ""); } [Fact] public void TestLiftedUserDefinedBinaryArithmetic() { string source = @" using System; struct SX { public string str; public SX(string str) { this.str = str; } public SX(char c) { this.str = c.ToString(); } public static SZ operator +(SX sx, SY sy) { return new SZ(sx.str + '+' + sy.str); } public static SZ operator -(SX sx, SY sy) { return new SZ(sx.str + '-' + sy.str); } public static SZ operator *(SX sx, SY sy) { return new SZ(sx.str + '*' + sy.str); } public static SZ operator /(SX sx, SY sy) { return new SZ(sx.str + '/' + sy.str); } public static SZ operator %(SX sx, SY sy) { return new SZ(sx.str + '%' + sy.str); } public static SZ operator &(SX sx, SY sy) { return new SZ(sx.str + '&' + sy.str); } public static SZ operator |(SX sx, SY sy) { return new SZ(sx.str + '|' + sy.str); } public static SZ operator ^(SX sx, SY sy) { return new SZ(sx.str + '^' + sy.str); } public static SZ operator >>(SX sx, int i) { return new SZ(sx.str + '>' + '>' + i.ToString()); } public static SZ operator <<(SX sx, int i) { return new SZ(sx.str + '<' + '<' + i.ToString()); } } struct SY { public string str; public SY(string str) { this.str = str; } public SY(char c) { this.str = c.ToString(); } } struct SZ { public string str; public SZ(string str) { this.str = str; } public SZ(char c) { this.str = c.ToString(); } public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } public static bool operator !=(SZ sz1, SZ sz2) { return sz1.str != sz2.str; } public override bool Equals(object x) { return true; } public override int GetHashCode() { return 0; } } class C { static void T(bool b) { if (!b) throw new Exception(); } static void F(bool b) { if (b) throw new Exception(); } static void Main() { SX sx = new SX('a'); SX? sxn = sx; SX? sxnn = null; SY sy = new SY('b'); SY? syn = sy; SY? synn = null; int i1 = 1; int? i1n = 1; int? i1nn = null; "; source += @" T((sx + syn).Value == (sx + sy)); F((sx - synn).HasValue); F((sx * null).HasValue); T((sxn % sy).Value == (sx % sy)); T((sxn / syn).Value == (sx / sy)); F((sxn ^ synn).HasValue); F((sxn & null).HasValue); F((sxnn | sy).HasValue); F((sxnn ^ syn).HasValue); F((sxnn + synn).HasValue); F((sxnn - null).HasValue);"; source += @" T((sx << i1n).Value == (sx << i1)); F((sx >> i1nn).HasValue); F((sx << null).HasValue); T((sxn >> i1).Value == (sx >> i1)); T((sxn << i1n).Value == (sx << i1)); F((sxn >> i1nn).HasValue); F((sxn << null).HasValue); F((sxnn >> i1).HasValue); F((sxnn << i1n).HasValue); F((sxnn >> i1nn).HasValue); F((sxnn << null).HasValue);"; source += "}}"; var verifier = CompileAndVerify(source: source, expectedOutput: ""); } [Fact] public void TestLiftedBoolLogicOperators() { string source = @" using System; class C { static void T(int x, bool? b) { if (!(b.HasValue && b.Value)) throw new Exception(x.ToString()); } static void F(int x, bool? b) { if (!(b.HasValue && !b.Value)) throw new Exception(x.ToString()); } static void N(int x, bool? b) { if (b.HasValue) throw new Exception(x.ToString()); } static void Main() { bool bt = true; bool bf = false; bool? bnt = bt; bool? bnf = bf; bool? bnn = null; T(1, true & bnt); T(2, true & bnt); F(3, true & bnf); N(4, true & null); N(5, true & bnn); T(6, bt & bnt); T(7, bt & bnt); F(8, bt & bnf); N(9, bt & null); N(10, bt & bnn); T(11, bnt & true); T(12, bnt & bt); T(13, bnt & bnt); F(14, bnt & false); F(15, bnt & bf); F(16, bnt & bnf); N(17, bnt & null); N(18, bnt & bnn); F(19, false & bnt); F(20, false & bnf); F(21, false & null); F(22, false & bnn); F(23, bf & bnt); F(24, bf & bnf); F(25, bf & null); F(26, bf & bnn); F(27, bnf & true); F(28, bnf & bt); F(29, bnf & bnt); F(30, bnf & false); F(31, bnf & bf); F(32, bnf & bnf); F(33, bnf & null); F(34, bnf & bnn); N(35, null & true); N(36, null & bt); N(37, null & bnt); F(38, null & false); F(39, null & bf); F(40, null & bnf); N(41, null & bnn); N(42, bnn & true); N(43, bnn & bt); N(44, bnn & bnt); F(45, bnn & false); F(46, bnn & bf); F(47, bnn & bnf); N(48, bnn & null); N(49, bnn & bnn); T(51, true | bnt); T(52, true | bnt); T(53, true | bnf); T(54, true | null); T(55, true | bnn); T(56, bt | bnt); T(57, bt | bnt); T(58, bt | bnf); T(59, bt | null); T(60, bt | bnn); T(61, bnt | true); T(62, bnt | bt); T(63, bnt | bnt); T(64, bnt | false); T(65, bnt | bf); T(66, bnt | bnf); T(67, bnt | null); T(68, bnt | bnn); T(69, false | bnt); F(70, false | bnf); N(71, false | null); N(72, false | bnn); T(73, bf | bnt); F(74, bf | bnf); N(75, bf | null); N(76, bf | bnn); T(77, bnf | true); T(78, bnf | bt); T(79, bnf | bnt); F(80, bnf | false); F(81, bnf | bf); F(82, bnf | bnf); N(83, bnf | null); N(84, bnf | bnn); T(85, null | true); T(86, null | bt); T(87, null | bnt); N(88, null | false); N(89, null | bf); N(90, null | bnf); N(91, null | bnn); T(92, bnn | true); T(93, bnn | bt); T(94, bnn | bnt); N(95, bnn | false); N(96, bnn | bf); N(97, bnn | bnf); N(98, bnn | null); N(99, bnn | bnn); F(101, true ^ bnt); F(102, true ^ bnt); T(103, true ^ bnf); N(104, true ^ null); N(105, true ^ bnn); F(106, bt ^ bnt); F(107, bt ^ bnt); T(108, bt ^ bnf); N(109, bt ^ null); N(110, bt ^ bnn); F(111, bnt ^ true); F(112, bnt ^ bt); F(113, bnt ^ bnt); T(114, bnt ^ false); T(115, bnt ^ bf); T(116, bnt ^ bnf); N(117, bnt ^ null); N(118, bnt ^ bnn); T(119, false ^ bnt); F(120, false ^ bnf); N(121, false ^ null); N(122, false ^ bnn); T(123, bf ^ bnt); F(124, bf ^ bnf); N(125, bf ^ null); N(126, bf ^ bnn); T(127, bnf ^ true); T(128, bnf ^ bt); T(129, bnf ^ bnt); F(130, bnf ^ false); F(131, bnf ^ bf); F(132, bnf ^ bnf); N(133, bnf ^ null); N(134, bnf ^ bnn); N(135, null ^ true); N(136, null ^ bt); N(137, null ^ bnt); N(138, null ^ false); N(139, null ^ bf); N(140, null ^ bnf); N(141, null ^ bnn); N(142, bnn ^ true); N(143, bnn ^ bt); N(144, bnn ^ bnt); N(145, bnn ^ false); N(146, bnn ^ bf); N(147, bnn ^ bnf); N(148, bnn ^ null); N(149, bnn ^ bnn); } }"; var verifier = CompileAndVerify(source: source, expectedOutput: ""); } [Fact] public void TestLiftedCompoundAssignment() { string source = @" using System; class C { static void Main() { int? n = 1; int a = 2; int? b = 3; short c = 4; short? d = 5; int? e = null; n += a; T(1, n == 3); n += b; T(2, n == 6); n += c; T(3, n == 10); n += d; T(4, n == 15); n += e; F(5, n.HasValue); n += a; F(6, n.HasValue); n += b; F(7, n.HasValue); n += c; F(8, n.HasValue); n += d; F(9, n.HasValue); Console.WriteLine(123); } static void T(int x, bool b) { if (!b) throw new Exception(x.ToString()); } static void F(int x, bool b) { if (b) throw new Exception(x.ToString()); } }"; var verifier = CompileAndVerify(source: source, expectedOutput: "123"); } #region "Regression" [Fact, WorkItem(543837, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543837")] public void Test11827() { string source2 = @" using System; class Program { static void Main() { Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; Console.WriteLine(0); } }"; var verifier = CompileAndVerify(source: source2, expectedOutput: "0"); } [Fact, WorkItem(544001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544001")] public void NullableUsedInUsingStatement() { string source = @" using System; struct S : IDisposable { public void Dispose() { Console.WriteLine(123); } static void Main() { using (S? r = new S()) { Console.Write(r); } } } "; CompileAndVerify(source: source, expectedOutput: @"S123"); } [Fact, WorkItem(544002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544002")] public void NullableUserDefinedUnary02() { string source = @" using System; struct S { public static int operator +(S s) { return 1; } public static int operator +(S? s) { return s.HasValue ? 10 : -10; } public static int operator -(S s) { return 2; } public static int operator -(S? s) { return s.HasValue ? 20 : -20; } public static int operator !(S s) { return 3; } public static int operator !(S? s) { return s.HasValue ? 30 : -30; } public static int operator ~(S s) { return 4; } public static int operator ~(S? s) { return s.HasValue ? 40 : -40; } public static void Main() { S? sq = new S(); Console.Write(+sq); Console.Write(-sq); Console.Write(!sq); Console.Write(~sq); sq = null; Console.Write(+sq); Console.Write(-sq); Console.Write(!sq); Console.Write(~sq); } } "; CompileAndVerify(source: source, expectedOutput: @"10203040-10-20-30-40"); } [Fact, WorkItem(544005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544005")] public void NoNullableValueFromOptionalParam() { string source = @" class Test { static void M( double? d0 = null, double? d1 = 1.11, double? d2 = 2, double? d3 = default(double?), double d4 = 4, double d5 = default(double), string s6 = ""6"", string s7 = null, string s8 = default(string)) { System.Console.WriteLine(""0:{0} 1:{1} 2:{2} 3:{3} 4:{4} 5:{5} 6:{6} 7:{7} 8:{8}"", d0, d1.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), d2, d3, d4, d5, s6, s7, s8); } static void Main() { M(); } } "; string expected = @"0: 1:1.11 2:2 3: 4:4 5:0 6:6 7: 8:"; var verifier = CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(544006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544006")] public void ConflictImportedMethodWithNullableOptionalParam() { string source = @" public class Parent { public int Goo(int? d = 0) { return (int)d; } } "; string source2 = @" public class Parent { public int Goo(int? d = 0) { return (int)d; } } public class Test { public static void Main() { Parent p = new Parent(); System.Console.Write(p.Goo(0)); } } "; var complib = CreateCompilation( source, options: TestOptions.ReleaseDll, assemblyName: "TestDLL"); var comp = CreateCompilation( source2, references: new MetadataReference[] { complib.EmitToImageReference() }, options: TestOptions.ReleaseExe, assemblyName: "TestEXE"); comp.VerifyDiagnostics( // (11,9): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Parent p = new Parent(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent"), // (11,24): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Parent p = new Parent(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent") ); CompileAndVerify(comp, expectedOutput: @"0"); } [Fact, WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")] public void BindDelegateToObjectMethods() { string source = @" using System; public class Test { delegate int I(); static void Main() { int? x = 123; Func<string> d1 = x.ToString; I d2 = x.GetHashCode; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(544909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544909")] public void OperationOnEnumNullable() { string source = @" using System; public class NullableTest { public enum E : short { Zero = 0, One = 1, Max = System.Int16.MaxValue, Min = System.Int16.MinValue } static E? NULL = null; public static void Main() { E? nub = 0; Test(nub.HasValue); // t nub = NULL; Test(nub.HasValue); // f nub = ~nub; Test(nub.HasValue); // f nub = NULL++; Test(nub.HasValue); // f nub = 0; nub++; Test(nub.HasValue); // t Test(nub.GetValueOrDefault() == E.One); // t nub = E.Max; nub++; Test(nub.GetValueOrDefault() == E.Min); // t } static void Test(bool b) { Console.Write(b ? 't' : 'f'); } } "; CompileAndVerify(source, expectedOutput: "tfffttt"); } [Fact, WorkItem(544583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544583")] public void ShortCircuitOperatorsOnNullable() { string source = @" class A { static void Main() { bool? b1 = true, b2 = false; var bb = b1 && b2; bb = b1 || b2; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,18): error CS0019: Operator '&&' cannot be applied to operands of type 'bool?' and 'bool?' // var bb = b1 && b2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 && b2").WithArguments("&&", "bool?", "bool?"), // (8,14): error CS0019: Operator '||' cannot be applied to operands of type 'bool?' and 'bool?' // bb = b1 || b2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 || b2").WithArguments("||", "bool?", "bool?") ); } [Fact] public void ShortCircuitLiftedUserDefinedOperators() { // This test illustrates a bug in the native compiler which Roslyn fixes. // The native compiler disallows a *lifted* & operator from being used as an && // operator, but allows a *nullable* & operator to be used as an && operator. // There is no good reason for this discrepancy; either both should be legal // (because we can obviously generate good code that does what the user wants) // or we should disallow both. string source = @" using System; struct C { public bool b; public C(bool b) { this.b = b; } public static C operator &(C c1, C c2) { return new C(c1.b & c2.b); } public static C operator |(C c1, C c2) { return new C(c1.b | c2.b); } // null is false public static bool operator true(C? c) { return c == null ? false : c.Value.b; } public static bool operator false(C? c) { return c == null ? true : !c.Value.b; } public static C? True() { Console.Write('t'); return new C(true); } public static C? False() { Console.Write('f'); return new C(false); } public static C? Null() { Console.Write('n'); return new C?(); } } struct D { public bool b; public D(bool b) { this.b = b; } public static D? operator &(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b & d2.Value.b)) : (D?)null; } public static D? operator |(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b | d2.Value.b)) : (D?)null; } // null is false public static bool operator true(D? d) { return d == null ? false : d.Value.b; } public static bool operator false(D? d) { return d == null ? true : !d.Value.b; } public static D? True() { Console.Write('t'); return new D(true); } public static D? False() { Console.Write('f'); return new D(false); } public static D? Null() { Console.Write('n'); return new D?(); } } class P { static void Main() { D?[] results1 = { D.True() && D.True(), // tt --> t D.True() && D.False(), // tf --> f D.True() && D.Null(), // tn --> n D.False() && D.True(), // f --> f D.False() && D.False(), // f --> f D.False() && D.Null(), // f --> f D.Null() && D.True(), // n --> n D.Null() && D.False(), // n --> n D.Null() && D.Null() // n --> n }; Console.WriteLine(); foreach(D? r in results1) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); Console.WriteLine(); C?[] results2 = { C.True() && C.True(), C.True() && C.False(), C.True() && C.Null(), C.False() && C.True(), C.False() && C.False(), C.False() && C.Null(), C.Null() && C.True(), C.Null() && C.False(), C.Null() && C.Null() }; Console.WriteLine(); foreach(C? r in results2) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); Console.WriteLine(); D?[] results3 = { D.True() || D.True(), // t --> t D.True() || D.False(), // t --> t D.True() || D.Null(), // t --> t D.False() || D.True(), // ft --> t D.False() || D.False(), // ff --> f D.False() || D.Null(), // fn --> n D.Null() || D.True(), // nt --> n D.Null() || D.False(), // nf --> n D.Null() || D.Null() // nn --> n }; Console.WriteLine(); foreach(D? r in results3) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); Console.WriteLine(); C?[] results4 = { C.True() || C.True(), C.True() || C.False(), C.True() || C.Null(), C.False() || C.True(), C.False() || C.False(), C.False() || C.Null(), C.Null() || C.True(), C.Null() || C.False(), C.Null() || C.Null() }; Console.WriteLine(); foreach(C? r in results4) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); } } "; string expected = @"tttftnfffnnn tfnfffnnn tttftnfffnnn tfnfffnnn tttftfffnntnfnn ttttfnnnn tttftfffnntnfnn ttttfnnnn"; CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(529530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529530"), WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")] public void NullableEnumMinusNull() { var source = @" using System; class Program { static void Main(string[] args) { Base64FormattingOptions? xn0 = Base64FormattingOptions.None; Console.WriteLine((xn0 - null).HasValue); } }"; CompileAndVerify(source, expectedOutput: "False").VerifyDiagnostics( // (9,28): warning CS0458: The result of the expression is always 'null' of type 'int?' // Console.WriteLine((xn0 - null).HasValue); Diagnostic(ErrorCode.WRN_AlwaysNull, "xn0 - null").WithArguments("int?").WithLocation(9, 28) ); } [Fact] public void NullableNullEquality() { var source = @" using System; public struct S { public static void Main() { S? s = new S(); Console.WriteLine(null == s); } }"; CompileAndVerify(source, expectedOutput: "False"); } [Fact, WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")] public void Op_ExplicitImplicitOnNullable() { var source = @" using System; class Test { static void Main() { var x = (int?).op_Explicit(1); var y = (Nullable<int>).op_Implicit(2); } } "; // VB now allow these syntax, but C# does NOT (spec said) // Dev11 & Roslyn: (8,23): error CS1525: Invalid expression term '.' // --- // Dev11: error CS0118: 'int?' is a 'type' but is used like a 'variable' // Roslyn: (9,18): error CS0119: 'int?' is a type, which is not valid in the given context // Roslyn: (9,33): error CS0571: 'int?.implicit operator int?(int)': cannot explicitly call operator or accessor CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidExprTerm, ".").WithArguments("."), Diagnostic(ErrorCode.ERR_BadSKunknown, "Nullable<int>").WithArguments("int?", "type"), Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Implicit").WithArguments("int?.implicit operator int?(int)") ); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class NullableSemanticTests : SemanticModelTestBase { [Fact, WorkItem(651624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651624")] public void NestedNullableWithAttemptedConversion() { var src = @"using System; class C { public void Main() { Nullable<Nullable<int>> x = null; Nullable<int> y = null; Console.WriteLine(x == y); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,16): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>' // Nullable<Nullable<int>> x = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Nullable<int>").WithArguments("System.Nullable<T>", "T", "int?"), // (7,25): error CS0019: Operator '==' cannot be applied to operands of type 'int??' and 'int?' // Console.WriteLine(x == y); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == y").WithArguments("==", "int??", "int?")); } [Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")] public void TestBug12347() { string source = @" using System; class C { static void Main() { string? s1 = null; Nullable<string> s2 = null; Console.WriteLine(s1.ToString() + s2.ToString()); } }"; var expected = new[] { // (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // string? s1 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 11), // (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // Nullable<string> s2 = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? s1 = null; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 11), // (8,14): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // Nullable<string> s2 = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 14)); } [Fact, WorkItem(544152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544152")] public void TestBug12347_CSharp8() { string source = @" using System; class C { static void Main() { string? s1 = null; Nullable<string> s2 = null; Console.WriteLine(s1.ToString() + s2.ToString()); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? s1 = null; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 15), // (8,18): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // Nullable<string> s2 = null; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("System.Nullable<T>", "T", "string").WithLocation(8, 18) ); } [Fact, WorkItem(529269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529269")] public void TestLiftedIncrementOperatorBreakingChanges01() { // The native compiler not only *allows* this to compile, it lowers to: // // C temp1 = c; // int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1); // c = temp2.HasValue ? // C.op_Implicit_Nullable_Int_To_C(new short?((short)(temp2.GetValueOrDefault() + 1))) : // null; // // !!! // // Not only does the native compiler silently insert a data-losing conversion from int to short, // if the result of the initial conversion to int? is null, the result is a null *C*, not // an implicit conversion from a null *int?* to C. // // This should simply be disallowed. The increment on int? produces int?, and there is no implicit // conversion from int? to S. string source1 = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } public static implicit operator C(short? s) { return new C(s); } static void Main() { C c = new C(null); c++; System.Console.WriteLine(object.ReferenceEquals(c, null)); } }"; var comp = CreateCompilation(source1); comp.VerifyDiagnostics( // (11,5): error CS0266: Cannot implicitly convert type 'int?' to 'C'. An explicit conversion exists (are you missing a cast?) // c++; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c++").WithArguments("int?", "C") ); } [Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")] public void TestLiftedIncrementOperatorBreakingChanges02() { // Now here we have a case where the compilation *should* succeed, and does, but // the native compiler and Roslyn produce opposite behavior. Again, the native // compiler lowers this to: // // C temp1 = c; // int? temp2 = C.op_Implicit_C_To_Nullable_Int(temp1); // c = temp2.HasValue ? // C.op_Implicit_Nullable_Int_To_C(new int?(temp2.GetValueOrDefault() + 1)) : // null; // // And therefore produces "True". The correct lowering, performed by Roslyn, is: // // C temp1 = c; // int? temp2 = C.op_Implicit_C_To_Nullable_Int( temp1 ); // int? temp3 = temp2.HasValue ? // new int?(temp2.GetValueOrDefault() + 1)) : // default(int?); // c = C.op_Implicit_Nullable_Int_To_C(temp3); // // and therefore should produce "False". string source2 = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } public static implicit operator C(int? s) { return new C(s); } static void Main() { C c = new C(null); c++; System.Console.WriteLine(object.ReferenceEquals(c, null) ? 1 : 0); } }"; var verifier = CompileAndVerify(source: source2, expectedOutput: "0"); verifier = CompileAndVerify(source: source2, expectedOutput: "0"); // And in fact, this should work if there is an implicit conversion from the result of the addition // to the type: string source3 = @" class C { public readonly int? i; public C(int? i) { this.i = i; } public static implicit operator int?(C c) { return c.i; } // There is an implicit conversion from int? to long? and therefore from int? to S. public static implicit operator C(long? s) { return new C((int?)s); } static void Main() { C c1 = new C(null); c1++; C c2 = new C(123); c2++; System.Console.WriteLine(!object.ReferenceEquals(c1, null) && c2.i.Value == 124 ? 1 : 0); } }"; verifier = CompileAndVerify(source: source3, expectedOutput: "1", verify: Verification.Fails); verifier = CompileAndVerify(source: source3, expectedOutput: "1", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); } [Fact, WorkItem(543954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543954")] public void TestLiftedIncrementOperatorBreakingChanges03() { // Let's in fact verify that this works correctly for all possible conversions to built-in types: string source4 = @" using System; class C { public readonly TYPE? i; public C(TYPE? i) { this.i = i; } public static implicit operator TYPE?(C c) { return c.i; } public static implicit operator C(TYPE? s) { return new C(s); } static void Main() { TYPE q = 10; C x = new C(10); T(1, x.i.Value == q); T(2, (x++).i.Value == (q++)); T(3, x.i.Value == q); T(4, (++x).i.Value == (++q)); T(5, x.i.Value == q); T(6, (x--).i.Value == (q--)); T(7, x.i.Value == q); T(8, (--x).i.Value == (--q)); T(9, x.i.Value == q); C xn = new C(null); F(11, xn.i.HasValue); F(12, (xn++).i.HasValue); F(13, xn.i.HasValue); F(14, (++xn).i.HasValue); F(15, xn.i.HasValue); F(16, (xn--).i.HasValue); F(17, xn.i.HasValue); F(18, (--xn).i.HasValue); F(19, xn.i.HasValue); System.Console.WriteLine(0); } static void T(int line, bool b) { if (!b) throw new Exception(""TYPE"" + line.ToString()); } static void F(int line, bool b) { if (b) throw new Exception(""TYPE"" + line.ToString()); } } "; foreach (string type in new[] { "int", "ushort", "byte", "long", "float", "decimal" }) { CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", verify: Verification.Fails); CompileAndVerify(source: source4.Replace("TYPE", type), expectedOutput: "0", parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature()); } } [Fact] public void TestLiftedBuiltInIncrementOperators() { string source = @" using System; class C { static void Main() { TYPE q = 10; TYPE? x = 10; T(1, x.Value == q); T(2, (x++).Value == (q++)); T(3, x.Value == q); T(4, (++x).Value == (++q)); T(5, x.Value == q); T(6, (x--).Value == (q--)); T(7, x.Value == q); T(8, (--x).Value == (--q)); T(9, x.Value == q); int? xn = null; F(11, xn.HasValue); F(12, (xn++).HasValue); F(13, xn.HasValue); F(14, (++xn).HasValue); F(15, xn.HasValue); F(16, (xn--).HasValue); F(17, xn.HasValue); F(18, (--xn).HasValue); F(19, xn.HasValue); System.Console.WriteLine(0); } static void T(int line, bool b) { if (!b) throw new Exception(""TYPE"" + line.ToString()); } static void F(int line, bool b) { if (b) throw new Exception(""TYPE"" + line.ToString()); } }"; foreach (string type in new[] { "uint", "short", "sbyte", "ulong", "double", "decimal" }) { string expected = "0"; var verifier = CompileAndVerify(source: source.Replace("TYPE", type), expectedOutput: expected); } } [Fact] public void TestLiftedUserDefinedIncrementOperators() { string source = @" using System; struct S { public int x; public S(int x) { this.x = x; } public static S operator ++(S s) { return new S(s.x + 1); } public static S operator --(S s) { return new S(s.x - 1); } } class C { static void Main() { S? n = new S(1); S s = new S(1); T(1, n.Value.x == s.x); T(2, (n++).Value.x == (s++).x); T(3, n.Value.x == s.x); T(4, (n--).Value.x == (s--).x); T(5, n.Value.x == s.x); T(6, (++n).Value.x == (++s).x); T(7, n.Value.x == s.x); T(8, (--n).Value.x == (--s).x); T(9, n.Value.x == s.x); n = null; F(11, n.HasValue); F(12, (n++).HasValue); F(13, n.HasValue); F(14, (n--).HasValue); F(15, n.HasValue); F(16, (++n).HasValue); F(17, n.HasValue); F(18, (--n).HasValue); F(19, n.HasValue); Console.WriteLine(1); } static void T(int line, bool b) { if (!b) throw new Exception(line.ToString()); } static void F(int line, bool b) { if (b) throw new Exception(line.ToString()); } } "; var verifier = CompileAndVerify(source: source, expectedOutput: "1"); } [Fact] public void TestNullableBuiltInUnaryOperator() { string source = @" using System; class C { static void Main() { Console.Write('!'); bool? bf = false; bool? bt = true; bool? bn = null; Test((!bf).HasValue); Test((!bf).Value); Test((!bt).HasValue); Test((!bt).Value); Test((!bn).HasValue); Console.WriteLine(); Console.Write('-'); int? i32 = -1; int? i32n = null; Test((-i32).HasValue); Test((-i32) == 1); Test((-i32) == -1); Test((-i32n).HasValue); Console.Write(1); long? i64 = -1; long? i64n = null; Test((-i64).HasValue); Test((-i64) == 1); Test((-i64) == -1); Test((-i64n).HasValue); Console.Write(2); float? r32 = -1.5f; float? r32n = null; Test((-r32).HasValue); Test((-r32) == 1.5f); Test((-r32) == -1.5f); Test((-r32n).HasValue); Console.Write(3); double? r64 = -1.5; double? r64n = null; Test((-r64).HasValue); Test((-r64) == 1.5); Test((-r64) == -1.5); Test((-r64n).HasValue); Console.Write(4); decimal? d = -1.5m; decimal? dn = null; Test((-d).HasValue); Test((-d) == 1.5m); Test((-d) == -1.5m); Test((-dn).HasValue); Console.WriteLine(); Console.Write('+'); Test((+i32).HasValue); Test((+i32) == 1); Test((+i32) == -1); Test((+i32n).HasValue); Console.Write(1); uint? ui32 = 1; uint? ui32n = null; Test((+ui32).HasValue); Test((+ui32) == 1); Test((+ui32n).HasValue); Console.Write(2); Test((+i64).HasValue); Test((+i64) == 1); Test((+i64) == -1); Test((+i64n).HasValue); Console.Write(3); ulong? ui64 = 1; ulong? ui64n = null; Test((+ui64).HasValue); Test((+ui64) == 1); Test((+ui64n).HasValue); Console.Write(4); Test((+r32).HasValue); Test((+r32) == 1.5f); Test((+r32) == -1.5f); Test((+r32n).HasValue); Console.Write(5); Test((+r64).HasValue); Test((+r64) == 1.5); Test((+r64) == -1.5); Test((+r64n).HasValue); Console.Write(6); Test((+d).HasValue); Test((+d) == 1.5m); Test((+d) == -1.5m); Test((+dn).HasValue); Console.WriteLine(); Console.Write('~'); i32 = 1; Test((~i32).HasValue); Test((~i32) == -2); Test((~i32n).HasValue); Console.Write(1); Test((~ui32).HasValue); Test((~ui32) == 0xFFFFFFFE); Test((~ui32n).HasValue); Console.Write(2); i64 = 1; Test((~i64).HasValue); Test((~i64) == -2L); Test((~i64n).HasValue); Console.Write(3); Test((~ui64).HasValue); Test((~ui64) == 0xFFFFFFFFFFFFFFFE); Test((~ui64n).HasValue); Console.Write(4); Base64FormattingOptions? e = Base64FormattingOptions.InsertLineBreaks; Base64FormattingOptions? en = null; Test((~e).HasValue); Test((~e) == (Base64FormattingOptions)(-2)); Test((~en).HasValue); } static void Test(bool b) { Console.Write(b ? 'T' : 'F'); } }"; string expected = @"!TTTFF -TTFF1TTFF2TTFF3TTFF4TTFF +TFTF1TTF2TFTF3TTF4TFTF5TFTF6TFTF ~TTF1TTF2TTF3TTF4TTF"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestNullableUserDefinedUnary() { string source = @" using System; struct S { public S(char c) { this.str = c.ToString(); } public S(string str) { this.str = str; } public string str; public static S operator !(S s) { return new S('!' + s.str); } public static S operator ~(S s) { return new S('~' + s.str); } public static S operator -(S s) { return new S('-' + s.str); } public static S operator +(S s) { return new S('+' + s.str); } } class C { static void Main() { S? s = new S('x'); S? sn = null; Test((~s).HasValue); Test((~sn).HasValue); Console.WriteLine((~s).Value.str); Test((!s).HasValue); Test((!sn).HasValue); Console.WriteLine((!s).Value.str); Test((+s).HasValue); Test((+sn).HasValue); Console.WriteLine((+s).Value.str); Test((-s).HasValue); Test((-sn).HasValue); Console.WriteLine((-s).Value.str); } static void Test(bool b) { Console.Write(b ? 'T' : 'F'); } }"; string expected = @"TF~x TF!x TF+x TF-x"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7803")] public void TestLiftedComparison() { TestNullableComparison("==", "FFTFF1FTFFTF2FFTFFT3TFFTFF4FTFFTF5FFTFFT", "int", "short", "byte", "long", "double", "decimal", "char", "Base64FormattingOptions", "S", "bool"); TestNullableComparison("!=", "TTFTT1TFTTFT2TTFTTF3FTTFTT4TFTTFT5TTFTTF", "uint", "ushort", "sbyte", "ulong", "float", "decimal", "char", "Base64FormattingOptions", "S", "bool"); TestNullableComparison("<", "FFFFF1FFTFFT2FFFFFF3FFFFFF4FFTFFT5FFFFFF", "uint", "sbyte", "float", "decimal", "Base64FormattingOptions", "S"); TestNullableComparison("<=", "FFFFF1FTTFTT2FFTFFT3FFFFFF4FTTFTT5FFTFFT", "int", "byte", "double", "decimal", "char"); TestNullableComparison(">", "FFFFF1FFFFFF2FTFFTF3FFFFFF4FFFFFF5FTFFTF", "ushort", "ulong", "decimal"); TestNullableComparison(">=", "FFFFF1FTFFTF2FTTFTT3FFFFFF4FTFFTF5FTTFTT", "short", "long", "decimal"); } private void TestNullableComparison( string oper, string expected, params string[] types) { string source = @" using System; struct S { public int i; public S(int i) { this.i = i; } public static bool operator ==(S x, S y) { return x.i == y.i; } public static bool operator !=(S x, S y) { return x.i != y.i; } public static bool operator <(S x, S y) { return x.i < y.i; } public static bool operator <=(S x, S y) { return x.i <= y.i; } public static bool operator >(S x, S y) { return x.i > y.i; } public static bool operator >=(S x, S y) { return x.i >= y.i; } } class C { static void Main() { TYPE? xn0 = ZERO; TYPE? xn1 = ONE; TYPE? xnn = null; TYPE x0 = ZERO; TYPE x1 = ONE; TYPE? yn0 = ZERO; TYPE? yn1 = ONE; TYPE? ynn = null; TYPE y0 = ZERO; TYPE y1 = ONE; Test(null OP yn0); Test(null OP yn1); Test(null OP ynn); Test(null OP y0); Test(null OP y1); Console.Write('1'); Test(xn0 OP null); Test(xn0 OP yn0); Test(xn0 OP yn1); Test(xn0 OP ynn); Test(xn0 OP y0); Test(xn0 OP y1); Console.Write('2'); Test(xn1 OP null); Test(xn1 OP yn0); Test(xn1 OP yn1); Test(xn1 OP ynn); Test(xn1 OP y0); Test(xn1 OP y1); Console.Write('3'); Test(xnn OP null); Test(xnn OP yn0); Test(xnn OP yn1); Test(xnn OP ynn); Test(xnn OP y0); Test(xnn OP y1); Console.Write('4'); Test(x0 OP null); Test(x0 OP yn0); Test(x0 OP yn1); Test(x0 OP ynn); Test(x0 OP y0); Test(x0 OP y1); Console.Write('5'); Test(x1 OP null); Test(x1 OP yn0); Test(x1 OP yn1); Test(x1 OP ynn); Test(x1 OP y0); Test(x1 OP y1); } static void Test(bool b) { Console.Write(b ? 'T' : 'F'); } } "; var zeros = new Dictionary<string, string>() { { "int", "0" }, { "uint", "0" }, { "short", "0" }, { "ushort", "0" }, { "byte", "0" }, { "sbyte", "0" }, { "long", "0" }, { "ulong", "0" }, { "double", "0" }, { "float", "0" }, { "decimal", "0" }, { "char", "'a'" }, { "bool", "false" }, { "Base64FormattingOptions", "Base64FormattingOptions.None" }, { "S", "new S(0)" } }; var ones = new Dictionary<string, string>() { { "int", "1" }, { "uint", "1" }, { "short", "1" }, { "ushort", "1" }, { "byte", "1" }, { "sbyte", "1" }, { "long", "1" }, { "ulong", "1" }, { "double", "1" }, { "float", "1" }, { "decimal", "1" }, { "char", "'b'" }, { "bool", "true" }, { "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" }, { "S", "new S(1)" } }; foreach (string t in types) { string s = source.Replace("TYPE", t).Replace("OP", oper).Replace("ZERO", zeros[t]).Replace("ONE", ones[t]); var verifier = CompileAndVerify(source: s, expectedOutput: expected); } } [Fact] public void TestLiftedBuiltInBinaryArithmetic() { string[,] enumAddition = { //{ "sbyte", "Base64FormattingOptions"}, { "byte", "Base64FormattingOptions"}, //{ "short", "Base64FormattingOptions"}, { "ushort", "Base64FormattingOptions"}, //{ "int", "Base64FormattingOptions"}, //{ "uint", "Base64FormattingOptions"}, //{ "long", "Base64FormattingOptions"}, //{ "ulong", "Base64FormattingOptions"}, { "char", "Base64FormattingOptions"}, //{ "decimal", "Base64FormattingOptions"}, //{ "double", "Base64FormattingOptions"}, //{ "float", "Base64FormattingOptions"}, { "Base64FormattingOptions", "sbyte" }, { "Base64FormattingOptions", "byte" }, { "Base64FormattingOptions", "short" }, { "Base64FormattingOptions", "ushort" }, { "Base64FormattingOptions", "int" }, //{ "Base64FormattingOptions", "uint" }, //{ "Base64FormattingOptions", "long" }, //{ "Base64FormattingOptions", "ulong" }, { "Base64FormattingOptions", "char" }, //{ "Base64FormattingOptions", "decimal" }, //{ "Base64FormattingOptions", "double" }, //{ "Base64FormattingOptions", "float" }, //{ "Base64FormattingOptions", "Base64FormattingOptions"}, }; string[,] enumSubtraction = { { "Base64FormattingOptions", "sbyte" }, //{ "Base64FormattingOptions", "byte" }, { "Base64FormattingOptions", "short" }, { "Base64FormattingOptions", "ushort" }, { "Base64FormattingOptions", "int" }, //{ "Base64FormattingOptions", "uint" }, //{ "Base64FormattingOptions", "long" }, //{ "Base64FormattingOptions", "ulong" }, //{ "Base64FormattingOptions", "char" }, //{ "Base64FormattingOptions", "decimal" }, //{ "Base64FormattingOptions", "double" }, //{ "Base64FormattingOptions", "float" }, { "Base64FormattingOptions", "Base64FormattingOptions"}, }; string[,] numerics1 = { { "sbyte", "sbyte" }, { "sbyte", "byte" }, //{ "sbyte", "short" }, { "sbyte", "ushort" }, //{ "sbyte", "int" }, { "sbyte", "uint" }, //{ "sbyte", "long" }, //{ "sbyte", "ulong" }, //{ "sbyte", "char" }, { "sbyte", "decimal" }, { "sbyte", "double" }, //{ "sbyte", "float" }, //{ "byte", "sbyte" }, { "byte", "byte" }, //{ "byte", "short" }, { "byte", "ushort" }, //{ "byte", "int" }, { "byte", "uint" }, //{ "byte", "long" }, { "byte", "ulong" }, //{ "byte", "char" }, { "byte", "decimal" }, //{ "byte", "double" }, { "byte", "float" }, { "short", "sbyte" }, { "short", "byte" }, { "short", "short" }, //{ "short", "ushort" }, { "short", "int" }, //{ "short", "uint" }, { "short", "long" }, //{ "short", "ulong" }, //{ "short", "char" }, { "short", "decimal" }, //{ "short", "double" }, { "short", "float" }, }; string[,] numerics2 = { //{ "ushort", "sbyte" }, //{ "ushort", "byte" }, { "ushort", "short" }, { "ushort", "ushort" }, //{ "ushort", "int" }, { "ushort", "uint" }, { "ushort", "long" }, //{ "ushort", "ulong" }, //{ "ushort", "char" }, //{ "ushort", "decimal" }, //{ "ushort", "double" }, { "ushort", "float" }, { "int", "sbyte" }, { "int", "byte" }, //{ "int", "short" }, { "int", "ushort" }, { "int", "int" }, //{ "int", "uint" }, { "int", "long" }, // { "int", "ulong" }, { "int", "char" }, //{ "int", "decimal" }, { "int", "double" }, //{ "int", "float" }, //{ "uint", "sbyte" }, //{ "uint", "byte" }, { "uint", "short" }, //{ "uint", "ushort" }, { "uint", "int" }, { "uint", "uint" }, { "uint", "long" }, //{ "uint", "ulong" }, { "uint", "char" }, //{ "uint", "decimal" }, //{ "uint", "double" }, { "uint", "float" }, }; string[,] numerics3 = { { "long", "sbyte" }, { "long", "byte" }, //{ "long", "short" }, //{ "long", "ushort" }, //{ "long", "int" }, //{ "long", "uint" }, { "long", "long" }, // { "long", "ulong" }, { "long", "char" }, //{ "long", "decimal" }, //{ "long", "double" }, { "long", "float" }, //{ "ulong", "sbyte" }, //{ "ulong", "byte" }, //{ "ulong", "short" }, { "ulong", "ushort" }, //{ "ulong", "int" }, { "ulong", "uint" }, //{ "ulong", "long" }, { "ulong", "ulong" }, //{ "ulong", "char" }, { "ulong", "decimal" }, { "ulong", "double" }, //{ "ulong", "float" }, }; string[,] numerics4 = { { "char", "sbyte" }, { "char", "byte" }, { "char", "short" }, { "char", "ushort" }, //{ "char", "int" }, //{ "char", "uint" }, //{ "char", "long" }, { "char", "ulong" }, { "char", "char" }, //{ "char", "decimal" }, //{ "char", "double" }, { "char", "float" }, //{ "decimal", "sbyte" }, //{ "decimal", "byte" }, //{ "decimal", "short" }, { "decimal", "ushort" }, { "decimal", "int" }, { "decimal", "uint" }, { "decimal", "long" }, //{ "decimal", "ulong" }, { "decimal", "char" }, { "decimal", "decimal" }, //{ "decimal", "double" }, //{ "decimal", "float" }, }; string[,] numerics5 = { //{ "double", "sbyte" }, { "double", "byte" }, { "double", "short" }, { "double", "ushort" }, //{ "double", "int" }, { "double", "uint" }, { "double", "long" }, //{ "double", "ulong" }, { "double", "char" }, //{ "double", "decimal" }, { "double", "double" }, { "double", "float" }, { "float", "sbyte" }, //{ "float", "byte" }, //{ "float", "short" }, //{ "float", "ushort" }, { "float", "int" }, //{ "float", "uint" }, //{ "float", "long" }, { "float", "ulong" }, //{ "float", "char" }, //{ "float", "decimal" }, //{ "float", "double" }, { "float", "float" }, }; string[,] shift1 = { { "sbyte", "sbyte" }, { "sbyte", "byte" }, { "sbyte", "short" }, { "sbyte", "ushort" }, { "sbyte", "int" }, { "sbyte", "char" }, { "byte", "sbyte" }, { "byte", "byte" }, { "byte", "short" }, { "byte", "ushort" }, { "byte", "int" }, { "byte", "char" }, { "short", "sbyte" }, { "short", "byte" }, { "short", "short" }, { "short", "ushort" }, { "short", "int" }, { "short", "char" }, { "ushort", "sbyte" }, { "ushort", "byte" }, { "ushort", "short" }, { "ushort", "ushort" }, { "ushort", "int" }, { "ushort", "char" }, }; string[,] shift2 = { { "int", "sbyte" }, { "int", "byte" }, { "int", "short" }, { "int", "ushort" }, { "int", "int" }, { "int", "char" }, { "uint", "sbyte" }, { "uint", "byte" }, { "uint", "short" }, { "uint", "ushort" }, { "uint", "int" }, { "uint", "char" }, { "long", "sbyte" }, { "long", "byte" }, { "long", "short" }, { "long", "ushort" }, { "long", "int" }, { "long", "char" }, { "ulong", "sbyte" }, { "ulong", "byte" }, { "ulong", "short" }, { "ulong", "ushort" }, { "ulong", "int" }, { "ulong", "char" }, { "char", "sbyte" }, { "char", "byte" }, { "char", "short" }, { "char", "ushort" }, { "char", "int" }, { "char", "char" }, }; string[,] logical1 = { { "sbyte", "sbyte" }, //{ "sbyte", "byte" }, { "sbyte", "short" }, { "sbyte", "ushort" }, { "sbyte", "int" }, //{ "sbyte", "uint" }, { "sbyte", "long" }, //{ "sbyte", "ulong" }, //{ "sbyte", "char" }, { "byte", "sbyte" }, { "byte", "byte" }, //{ "byte", "short" }, { "byte", "ushort" }, //{ "byte", "int" }, { "byte", "uint" }, //{ "byte", "long" }, //{ "byte", "ulong" }, { "byte", "char" }, { "short", "sbyte" }, { "short", "byte" }, { "short", "short" }, //{ "short", "ushort" }, { "short", "int" }, //{ "short", "uint" }, { "short", "long" }, //{ "short", "ulong" }, { "short", "char" }, }; string[,] logical2 = { //{ "ushort", "sbyte" }, { "ushort", "byte" }, { "ushort", "short" }, { "ushort", "ushort" }, //{ "ushort", "int" }, { "ushort", "uint" }, //{ "ushort", "long" }, //{ "ushort", "ulong" }, //{ "ushort", "char" }, //{ "int", "sbyte" }, { "int", "byte" }, //{ "int", "short" }, { "int", "ushort" }, { "int", "int" }, //{ "int", "uint" }, { "int", "long" }, //{ "int", "ulong" }, //{ "int", "char" }, { "uint", "sbyte" }, //{ "uint", "byte" }, { "uint", "short" }, //{ "uint", "ushort" }, { "uint", "int" }, { "uint", "uint" }, //{ "uint", "long" }, //{ "uint", "ulong" }, { "uint", "char" }, }; string[,] logical3 = { //{ "long", "sbyte" }, { "long", "byte" }, //{ "long", "short" }, { "long", "ushort" }, //{ "long", "int" }, { "long", "uint" }, { "long", "long" }, // { "long", "ulong" }, { "long", "char" }, //{ "ulong", "sbyte" }, { "ulong", "byte" }, //{ "ulong", "short" }, { "ulong", "ushort" }, //{ "ulong", "int" }, { "ulong", "uint" }, //{ "ulong", "long" }, { "ulong", "ulong" }, //{ "ulong", "char" }, { "char", "sbyte" }, //{ "char", "byte" }, //{ "char", "short" }, { "char", "ushort" }, { "char", "int" }, //{ "char", "uint" }, //{ "char", "long" }, { "char", "ulong" }, { "char", "char" }, { "Base64FormattingOptions", "Base64FormattingOptions"}, }; // Use 2 instead of 0 so that we don't get divide by zero errors. var twos = new Dictionary<string, string>() { { "int", "2" }, { "uint", "2" }, { "short", "2" }, { "ushort", "2" }, { "byte", "2" }, { "sbyte", "2" }, { "long", "2" }, { "ulong", "2" }, { "double", "2" }, { "float", "2" }, { "decimal", "2" }, { "char", "'\\u0002'" }, { "Base64FormattingOptions", "Base64FormattingOptions.None" }, }; var ones = new Dictionary<string, string>() { { "int", "1" }, { "uint", "1" }, { "short", "1" }, { "ushort", "1" }, { "byte", "1" }, { "sbyte", "1" }, { "long", "1" }, { "ulong", "1" }, { "double", "1" }, { "float", "1" }, { "decimal", "1" }, { "char", "'\\u0001'" }, { "Base64FormattingOptions", "Base64FormattingOptions.InsertLineBreaks" }, }; var names = new Dictionary<string, string>() { { "+", "plus" }, { "-", "minus" }, { "*", "times" }, { "/", "divide" }, { "%", "remainder" }, { ">>", "rshift" }, { "<<", "lshift" }, { "&", "and" }, { "|", "or" }, { "^", "xor" } }; var source = new StringBuilder(@" using System; class C { static void T(int x, bool b) { if (!b) throw new Exception(x.ToString()); } static void F(int x, bool b) { if (b) throw new Exception(x.ToString()); } "); string main = "static void Main() {"; string method = @" static void METHOD_TYPEX_NAME_TYPEY() { TYPEX? xn0 = TWOX; TYPEX? xn1 = ONEX; TYPEX? xnn = null; TYPEX x0 = TWOX; TYPEX x1 = ONEX; TYPEY? yn0 = TWOY; TYPEY? yn1 = ONEY; TYPEY? ynn = null; TYPEY y0 = TWOY; TYPEY y1 = ONEY; F(1, (null OP yn0).HasValue); F(2, (null OP yn1).HasValue); F(3, (null OP ynn).HasValue); F(4, (null OP y0).HasValue); F(5, (null OP y1).HasValue); F(6, (xn0 OP null).HasValue); T(7, (xn0 OP yn0).Value == (x0 OP y0)); T(8, (xn0 OP yn1).Value == (x0 OP y1)); F(9, (xn0 OP ynn).HasValue); T(10, (xn0 OP y0).Value == (x0 OP y0)); T(11, (xn0 OP y1).Value == (x0 OP y1)); F(12, (xn1 OP null).HasValue); T(13, (xn1 OP yn0).Value == (x1 OP y0)); T(14, (xn1 OP yn1).Value == (x1 OP y1)); F(15, (xn1 OP ynn).HasValue); T(16, (xn1 OP y0).Value == (x1 OP y0)); T(17, (xn1 OP y1).Value == (x1 OP y1)); F(18, (xnn OP null).HasValue); F(19, (xnn OP yn0).HasValue); F(20, (xnn OP yn1).HasValue); F(21, (xnn OP ynn).HasValue); F(22, (xnn OP y0).HasValue); F(23, (xnn OP y1).HasValue); F(24, (x0 OP null).HasValue); T(25, (x0 OP yn0).Value == (x0 OP y0)); T(26, (x0 OP yn1).Value == (x0 OP y1)); F(27, (x0 OP ynn).HasValue); F(28, (x1 OP null).HasValue); T(29, (x1 OP yn0).Value == (x1 OP y0)); T(30, (x1 OP yn1).Value == (x1 OP y1)); F(31, (x1 OP ynn).HasValue); }"; List<Tuple<string, string[,]>> items = new List<Tuple<string, string[,]>>() { Tuple.Create("*", numerics1), Tuple.Create("/", numerics2), Tuple.Create("%", numerics3), Tuple.Create("+", numerics4), Tuple.Create("+", enumAddition), Tuple.Create("-", numerics5), // UNDONE: Overload resolution of "enum - null" , // UNDONE: so this test is disabled: // UNDONE: Tuple.Create("-", enumSubtraction), Tuple.Create(">>", shift1), Tuple.Create("<<", shift2), Tuple.Create("&", logical1), Tuple.Create("|", logical2), Tuple.Create("^", logical3) }; int m = 0; foreach (var item in items) { string oper = item.Item1; string[,] types = item.Item2; for (int i = 0; i < types.GetLength(0); ++i) { ++m; string typeX = types[i, 0]; string typeY = types[i, 1]; source.Append(method .Replace("METHOD", "M" + m) .Replace("TYPEX", typeX) .Replace("TYPEY", typeY) .Replace("OP", oper) .Replace("NAME", names[oper]) .Replace("TWOX", twos[typeX]) .Replace("ONEX", ones[typeX]) .Replace("TWOY", twos[typeY]) .Replace("ONEY", ones[typeY])); main += "M" + m + "_" + typeX + "_" + names[oper] + "_" + typeY + "();\n"; } } source.Append(main); source.Append("} }"); var verifier = CompileAndVerify(source: source.ToString(), expectedOutput: ""); } [Fact] public void TestLiftedUserDefinedBinaryArithmetic() { string source = @" using System; struct SX { public string str; public SX(string str) { this.str = str; } public SX(char c) { this.str = c.ToString(); } public static SZ operator +(SX sx, SY sy) { return new SZ(sx.str + '+' + sy.str); } public static SZ operator -(SX sx, SY sy) { return new SZ(sx.str + '-' + sy.str); } public static SZ operator *(SX sx, SY sy) { return new SZ(sx.str + '*' + sy.str); } public static SZ operator /(SX sx, SY sy) { return new SZ(sx.str + '/' + sy.str); } public static SZ operator %(SX sx, SY sy) { return new SZ(sx.str + '%' + sy.str); } public static SZ operator &(SX sx, SY sy) { return new SZ(sx.str + '&' + sy.str); } public static SZ operator |(SX sx, SY sy) { return new SZ(sx.str + '|' + sy.str); } public static SZ operator ^(SX sx, SY sy) { return new SZ(sx.str + '^' + sy.str); } public static SZ operator >>(SX sx, int i) { return new SZ(sx.str + '>' + '>' + i.ToString()); } public static SZ operator <<(SX sx, int i) { return new SZ(sx.str + '<' + '<' + i.ToString()); } } struct SY { public string str; public SY(string str) { this.str = str; } public SY(char c) { this.str = c.ToString(); } } struct SZ { public string str; public SZ(string str) { this.str = str; } public SZ(char c) { this.str = c.ToString(); } public static bool operator ==(SZ sz1, SZ sz2) { return sz1.str == sz2.str; } public static bool operator !=(SZ sz1, SZ sz2) { return sz1.str != sz2.str; } public override bool Equals(object x) { return true; } public override int GetHashCode() { return 0; } } class C { static void T(bool b) { if (!b) throw new Exception(); } static void F(bool b) { if (b) throw new Exception(); } static void Main() { SX sx = new SX('a'); SX? sxn = sx; SX? sxnn = null; SY sy = new SY('b'); SY? syn = sy; SY? synn = null; int i1 = 1; int? i1n = 1; int? i1nn = null; "; source += @" T((sx + syn).Value == (sx + sy)); F((sx - synn).HasValue); F((sx * null).HasValue); T((sxn % sy).Value == (sx % sy)); T((sxn / syn).Value == (sx / sy)); F((sxn ^ synn).HasValue); F((sxn & null).HasValue); F((sxnn | sy).HasValue); F((sxnn ^ syn).HasValue); F((sxnn + synn).HasValue); F((sxnn - null).HasValue);"; source += @" T((sx << i1n).Value == (sx << i1)); F((sx >> i1nn).HasValue); F((sx << null).HasValue); T((sxn >> i1).Value == (sx >> i1)); T((sxn << i1n).Value == (sx << i1)); F((sxn >> i1nn).HasValue); F((sxn << null).HasValue); F((sxnn >> i1).HasValue); F((sxnn << i1n).HasValue); F((sxnn >> i1nn).HasValue); F((sxnn << null).HasValue);"; source += "}}"; var verifier = CompileAndVerify(source: source, expectedOutput: ""); } [Fact] public void TestLiftedBoolLogicOperators() { string source = @" using System; class C { static void T(int x, bool? b) { if (!(b.HasValue && b.Value)) throw new Exception(x.ToString()); } static void F(int x, bool? b) { if (!(b.HasValue && !b.Value)) throw new Exception(x.ToString()); } static void N(int x, bool? b) { if (b.HasValue) throw new Exception(x.ToString()); } static void Main() { bool bt = true; bool bf = false; bool? bnt = bt; bool? bnf = bf; bool? bnn = null; T(1, true & bnt); T(2, true & bnt); F(3, true & bnf); N(4, true & null); N(5, true & bnn); T(6, bt & bnt); T(7, bt & bnt); F(8, bt & bnf); N(9, bt & null); N(10, bt & bnn); T(11, bnt & true); T(12, bnt & bt); T(13, bnt & bnt); F(14, bnt & false); F(15, bnt & bf); F(16, bnt & bnf); N(17, bnt & null); N(18, bnt & bnn); F(19, false & bnt); F(20, false & bnf); F(21, false & null); F(22, false & bnn); F(23, bf & bnt); F(24, bf & bnf); F(25, bf & null); F(26, bf & bnn); F(27, bnf & true); F(28, bnf & bt); F(29, bnf & bnt); F(30, bnf & false); F(31, bnf & bf); F(32, bnf & bnf); F(33, bnf & null); F(34, bnf & bnn); N(35, null & true); N(36, null & bt); N(37, null & bnt); F(38, null & false); F(39, null & bf); F(40, null & bnf); N(41, null & bnn); N(42, bnn & true); N(43, bnn & bt); N(44, bnn & bnt); F(45, bnn & false); F(46, bnn & bf); F(47, bnn & bnf); N(48, bnn & null); N(49, bnn & bnn); T(51, true | bnt); T(52, true | bnt); T(53, true | bnf); T(54, true | null); T(55, true | bnn); T(56, bt | bnt); T(57, bt | bnt); T(58, bt | bnf); T(59, bt | null); T(60, bt | bnn); T(61, bnt | true); T(62, bnt | bt); T(63, bnt | bnt); T(64, bnt | false); T(65, bnt | bf); T(66, bnt | bnf); T(67, bnt | null); T(68, bnt | bnn); T(69, false | bnt); F(70, false | bnf); N(71, false | null); N(72, false | bnn); T(73, bf | bnt); F(74, bf | bnf); N(75, bf | null); N(76, bf | bnn); T(77, bnf | true); T(78, bnf | bt); T(79, bnf | bnt); F(80, bnf | false); F(81, bnf | bf); F(82, bnf | bnf); N(83, bnf | null); N(84, bnf | bnn); T(85, null | true); T(86, null | bt); T(87, null | bnt); N(88, null | false); N(89, null | bf); N(90, null | bnf); N(91, null | bnn); T(92, bnn | true); T(93, bnn | bt); T(94, bnn | bnt); N(95, bnn | false); N(96, bnn | bf); N(97, bnn | bnf); N(98, bnn | null); N(99, bnn | bnn); F(101, true ^ bnt); F(102, true ^ bnt); T(103, true ^ bnf); N(104, true ^ null); N(105, true ^ bnn); F(106, bt ^ bnt); F(107, bt ^ bnt); T(108, bt ^ bnf); N(109, bt ^ null); N(110, bt ^ bnn); F(111, bnt ^ true); F(112, bnt ^ bt); F(113, bnt ^ bnt); T(114, bnt ^ false); T(115, bnt ^ bf); T(116, bnt ^ bnf); N(117, bnt ^ null); N(118, bnt ^ bnn); T(119, false ^ bnt); F(120, false ^ bnf); N(121, false ^ null); N(122, false ^ bnn); T(123, bf ^ bnt); F(124, bf ^ bnf); N(125, bf ^ null); N(126, bf ^ bnn); T(127, bnf ^ true); T(128, bnf ^ bt); T(129, bnf ^ bnt); F(130, bnf ^ false); F(131, bnf ^ bf); F(132, bnf ^ bnf); N(133, bnf ^ null); N(134, bnf ^ bnn); N(135, null ^ true); N(136, null ^ bt); N(137, null ^ bnt); N(138, null ^ false); N(139, null ^ bf); N(140, null ^ bnf); N(141, null ^ bnn); N(142, bnn ^ true); N(143, bnn ^ bt); N(144, bnn ^ bnt); N(145, bnn ^ false); N(146, bnn ^ bf); N(147, bnn ^ bnf); N(148, bnn ^ null); N(149, bnn ^ bnn); } }"; var verifier = CompileAndVerify(source: source, expectedOutput: ""); } [Fact] public void TestLiftedCompoundAssignment() { string source = @" using System; class C { static void Main() { int? n = 1; int a = 2; int? b = 3; short c = 4; short? d = 5; int? e = null; n += a; T(1, n == 3); n += b; T(2, n == 6); n += c; T(3, n == 10); n += d; T(4, n == 15); n += e; F(5, n.HasValue); n += a; F(6, n.HasValue); n += b; F(7, n.HasValue); n += c; F(8, n.HasValue); n += d; F(9, n.HasValue); Console.WriteLine(123); } static void T(int x, bool b) { if (!b) throw new Exception(x.ToString()); } static void F(int x, bool b) { if (b) throw new Exception(x.ToString()); } }"; var verifier = CompileAndVerify(source: source, expectedOutput: "123"); } #region "Regression" [Fact, WorkItem(543837, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543837")] public void Test11827() { string source2 = @" using System; class Program { static void Main() { Func<decimal?, decimal?> lambda = a => { return checked(a * a); }; Console.WriteLine(0); } }"; var verifier = CompileAndVerify(source: source2, expectedOutput: "0"); } [Fact, WorkItem(544001, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544001")] public void NullableUsedInUsingStatement() { string source = @" using System; struct S : IDisposable { public void Dispose() { Console.WriteLine(123); } static void Main() { using (S? r = new S()) { Console.Write(r); } } } "; CompileAndVerify(source: source, expectedOutput: @"S123"); } [Fact, WorkItem(544002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544002")] public void NullableUserDefinedUnary02() { string source = @" using System; struct S { public static int operator +(S s) { return 1; } public static int operator +(S? s) { return s.HasValue ? 10 : -10; } public static int operator -(S s) { return 2; } public static int operator -(S? s) { return s.HasValue ? 20 : -20; } public static int operator !(S s) { return 3; } public static int operator !(S? s) { return s.HasValue ? 30 : -30; } public static int operator ~(S s) { return 4; } public static int operator ~(S? s) { return s.HasValue ? 40 : -40; } public static void Main() { S? sq = new S(); Console.Write(+sq); Console.Write(-sq); Console.Write(!sq); Console.Write(~sq); sq = null; Console.Write(+sq); Console.Write(-sq); Console.Write(!sq); Console.Write(~sq); } } "; CompileAndVerify(source: source, expectedOutput: @"10203040-10-20-30-40"); } [Fact, WorkItem(544005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544005")] public void NoNullableValueFromOptionalParam() { string source = @" class Test { static void M( double? d0 = null, double? d1 = 1.11, double? d2 = 2, double? d3 = default(double?), double d4 = 4, double d5 = default(double), string s6 = ""6"", string s7 = null, string s8 = default(string)) { System.Console.WriteLine(""0:{0} 1:{1} 2:{2} 3:{3} 4:{4} 5:{5} 6:{6} 7:{7} 8:{8}"", d0, d1.Value.ToString(System.Globalization.CultureInfo.InvariantCulture), d2, d3, d4, d5, s6, s7, s8); } static void Main() { M(); } } "; string expected = @"0: 1:1.11 2:2 3: 4:4 5:0 6:6 7: 8:"; var verifier = CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(544006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544006")] public void ConflictImportedMethodWithNullableOptionalParam() { string source = @" public class Parent { public int Goo(int? d = 0) { return (int)d; } } "; string source2 = @" public class Parent { public int Goo(int? d = 0) { return (int)d; } } public class Test { public static void Main() { Parent p = new Parent(); System.Console.Write(p.Goo(0)); } } "; var complib = CreateCompilation( source, options: TestOptions.ReleaseDll, assemblyName: "TestDLL"); var comp = CreateCompilation( source2, references: new MetadataReference[] { complib.EmitToImageReference() }, options: TestOptions.ReleaseExe, assemblyName: "TestEXE"); comp.VerifyDiagnostics( // (11,9): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Parent p = new Parent(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent"), // (11,24): warning CS0436: The type 'Parent' in '' conflicts with the imported type 'Parent' in 'TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Parent p = new Parent(); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Parent").WithArguments("", "Parent", "TestDLL, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Parent") ); CompileAndVerify(comp, expectedOutput: @"0"); } [Fact, WorkItem(544258, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544258")] public void BindDelegateToObjectMethods() { string source = @" using System; public class Test { delegate int I(); static void Main() { int? x = 123; Func<string> d1 = x.ToString; I d2 = x.GetHashCode; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(544909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544909")] public void OperationOnEnumNullable() { string source = @" using System; public class NullableTest { public enum E : short { Zero = 0, One = 1, Max = System.Int16.MaxValue, Min = System.Int16.MinValue } static E? NULL = null; public static void Main() { E? nub = 0; Test(nub.HasValue); // t nub = NULL; Test(nub.HasValue); // f nub = ~nub; Test(nub.HasValue); // f nub = NULL++; Test(nub.HasValue); // f nub = 0; nub++; Test(nub.HasValue); // t Test(nub.GetValueOrDefault() == E.One); // t nub = E.Max; nub++; Test(nub.GetValueOrDefault() == E.Min); // t } static void Test(bool b) { Console.Write(b ? 't' : 'f'); } } "; CompileAndVerify(source, expectedOutput: "tfffttt"); } [Fact, WorkItem(544583, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544583")] public void ShortCircuitOperatorsOnNullable() { string source = @" class A { static void Main() { bool? b1 = true, b2 = false; var bb = b1 && b2; bb = b1 || b2; } } "; CreateCompilation(source).VerifyDiagnostics( // (7,18): error CS0019: Operator '&&' cannot be applied to operands of type 'bool?' and 'bool?' // var bb = b1 && b2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 && b2").WithArguments("&&", "bool?", "bool?"), // (8,14): error CS0019: Operator '||' cannot be applied to operands of type 'bool?' and 'bool?' // bb = b1 || b2; Diagnostic(ErrorCode.ERR_BadBinaryOps, "b1 || b2").WithArguments("||", "bool?", "bool?") ); } [Fact] public void ShortCircuitLiftedUserDefinedOperators() { // This test illustrates a bug in the native compiler which Roslyn fixes. // The native compiler disallows a *lifted* & operator from being used as an && // operator, but allows a *nullable* & operator to be used as an && operator. // There is no good reason for this discrepancy; either both should be legal // (because we can obviously generate good code that does what the user wants) // or we should disallow both. string source = @" using System; struct C { public bool b; public C(bool b) { this.b = b; } public static C operator &(C c1, C c2) { return new C(c1.b & c2.b); } public static C operator |(C c1, C c2) { return new C(c1.b | c2.b); } // null is false public static bool operator true(C? c) { return c == null ? false : c.Value.b; } public static bool operator false(C? c) { return c == null ? true : !c.Value.b; } public static C? True() { Console.Write('t'); return new C(true); } public static C? False() { Console.Write('f'); return new C(false); } public static C? Null() { Console.Write('n'); return new C?(); } } struct D { public bool b; public D(bool b) { this.b = b; } public static D? operator &(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b & d2.Value.b)) : (D?)null; } public static D? operator |(D? d1, D? d2) { return d1.HasValue && d2.HasValue ? new D?(new D(d1.Value.b | d2.Value.b)) : (D?)null; } // null is false public static bool operator true(D? d) { return d == null ? false : d.Value.b; } public static bool operator false(D? d) { return d == null ? true : !d.Value.b; } public static D? True() { Console.Write('t'); return new D(true); } public static D? False() { Console.Write('f'); return new D(false); } public static D? Null() { Console.Write('n'); return new D?(); } } class P { static void Main() { D?[] results1 = { D.True() && D.True(), // tt --> t D.True() && D.False(), // tf --> f D.True() && D.Null(), // tn --> n D.False() && D.True(), // f --> f D.False() && D.False(), // f --> f D.False() && D.Null(), // f --> f D.Null() && D.True(), // n --> n D.Null() && D.False(), // n --> n D.Null() && D.Null() // n --> n }; Console.WriteLine(); foreach(D? r in results1) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); Console.WriteLine(); C?[] results2 = { C.True() && C.True(), C.True() && C.False(), C.True() && C.Null(), C.False() && C.True(), C.False() && C.False(), C.False() && C.Null(), C.Null() && C.True(), C.Null() && C.False(), C.Null() && C.Null() }; Console.WriteLine(); foreach(C? r in results2) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); Console.WriteLine(); D?[] results3 = { D.True() || D.True(), // t --> t D.True() || D.False(), // t --> t D.True() || D.Null(), // t --> t D.False() || D.True(), // ft --> t D.False() || D.False(), // ff --> f D.False() || D.Null(), // fn --> n D.Null() || D.True(), // nt --> n D.Null() || D.False(), // nf --> n D.Null() || D.Null() // nn --> n }; Console.WriteLine(); foreach(D? r in results3) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); Console.WriteLine(); C?[] results4 = { C.True() || C.True(), C.True() || C.False(), C.True() || C.Null(), C.False() || C.True(), C.False() || C.False(), C.False() || C.Null(), C.Null() || C.True(), C.Null() || C.False(), C.Null() || C.Null() }; Console.WriteLine(); foreach(C? r in results4) Console.Write(r == null ? 'n' : r.Value.b ? 't' : 'f'); } } "; string expected = @"tttftnfffnnn tfnfffnnn tttftnfffnnn tfnfffnnn tttftfffnntnfnn ttttfnnnn tttftfffnntnfnn ttttfnnnn"; CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(529530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529530"), WorkItem(1036392, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036392")] public void NullableEnumMinusNull() { var source = @" using System; class Program { static void Main(string[] args) { Base64FormattingOptions? xn0 = Base64FormattingOptions.None; Console.WriteLine((xn0 - null).HasValue); } }"; CompileAndVerify(source, expectedOutput: "False").VerifyDiagnostics( // (9,28): warning CS0458: The result of the expression is always 'null' of type 'int?' // Console.WriteLine((xn0 - null).HasValue); Diagnostic(ErrorCode.WRN_AlwaysNull, "xn0 - null").WithArguments("int?").WithLocation(9, 28) ); } [Fact] public void NullableNullEquality() { var source = @" using System; public struct S { public static void Main() { S? s = new S(); Console.WriteLine(null == s); } }"; CompileAndVerify(source, expectedOutput: "False"); } [Fact, WorkItem(545166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545166")] public void Op_ExplicitImplicitOnNullable() { var source = @" using System; class Test { static void Main() { var x = (int?).op_Explicit(1); var y = (Nullable<int>).op_Implicit(2); } } "; // VB now allow these syntax, but C# does NOT (spec said) // Dev11 & Roslyn: (8,23): error CS1525: Invalid expression term '.' // --- // Dev11: error CS0118: 'int?' is a 'type' but is used like a 'variable' // Roslyn: (9,18): error CS0119: 'int?' is a type, which is not valid in the given context // Roslyn: (9,33): error CS0571: 'int?.implicit operator int?(int)': cannot explicitly call operator or accessor CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidExprTerm, ".").WithArguments("."), Diagnostic(ErrorCode.ERR_BadSKunknown, "Nullable<int>").WithArguments("int?", "type"), Diagnostic(ErrorCode.ERR_CantCallSpecialMethod, "op_Implicit").WithArguments("int?.implicit operator int?(int)") ); } #endregion } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { /// <summary> /// Diagnostic Analyzer Engine V2 /// /// This one follows pattern compiler has set for diagnostic analyzer. /// </summary> internal partial class DiagnosticIncrementalAnalyzer : IIncrementalAnalyzer2 { private readonly int _correlationId; private readonly DiagnosticAnalyzerTelemetry _telemetry; private readonly StateManager _stateManager; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; private readonly IDocumentTrackingService _documentTrackingService; private ConditionalWeakTable<Project, CompilationWithAnalyzers?> _projectCompilationsWithAnalyzers; internal DiagnosticAnalyzerService AnalyzerService { get; } internal Workspace Workspace { get; } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public DiagnosticIncrementalAnalyzer( DiagnosticAnalyzerService analyzerService, int correlationId, Workspace workspace, DiagnosticAnalyzerInfoCache analyzerInfoCache) { Contract.ThrowIfNull(analyzerService); AnalyzerService = analyzerService; Workspace = workspace; _documentTrackingService = workspace.Services.GetRequiredService<IDocumentTrackingService>(); _correlationId = correlationId; _stateManager = new StateManager(analyzerInfoCache); _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged; _telemetry = new DiagnosticAnalyzerTelemetry(); _diagnosticAnalyzerRunner = new InProcOrRemoteHostAnalyzerRunner(analyzerInfoCache, analyzerService.Listener); _projectCompilationsWithAnalyzers = new ConditionalWeakTable<Project, CompilationWithAnalyzers?>(); } internal DiagnosticAnalyzerInfoCache DiagnosticAnalyzerInfoCache => _diagnosticAnalyzerRunner.AnalyzerInfoCache; [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/54400", Constraint = "Avoid calling GetAllHostStateSets on this hot path.")] public bool ContainsDiagnostics(ProjectId projectId) { return _stateManager.HasAnyHostStateSet(static (stateSet, arg) => stateSet.ContainsAnyDocumentOrProjectDiagnostics(arg), projectId) || _stateManager.HasAnyProjectStateSet(projectId, static (stateSet, arg) => stateSet.ContainsAnyDocumentOrProjectDiagnostics(arg), projectId); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return e.Option.Feature == nameof(SimplificationOptions) || e.Option.Feature == nameof(CodeStyleOptions) || e.Option == SolutionCrawlerOptions.BackgroundAnalysisScopeOption || e.Option == SolutionCrawlerOptions.SolutionBackgroundAnalysisScopeOption || #pragma warning disable CS0618 // Type or member is obsolete - F# is still on the older ClosedFileDiagnostic option. e.Option == SolutionCrawlerOptions.ClosedFileDiagnostic; #pragma warning restore CS0618 // Type or member is obsolete } private void OnProjectAnalyzerReferenceChanged(object? sender, ProjectAnalyzerReferenceChangedEventArgs e) { if (e.Removed.Length == 0) { // nothing to refresh return; } // events will be automatically serialized. var project = e.Project; var stateSets = e.Removed; // make sure we drop cache related to the analyzers foreach (var stateSet in stateSets) { stateSet.OnRemoved(); } ClearAllDiagnostics(stateSets, project.Id); } public void Shutdown() { var stateSets = _stateManager.GetAllStateSets(); AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents => { var handleActiveFile = true; using var _ = PooledHashSet<DocumentId>.GetInstance(out var documentSet); foreach (var stateSet in stateSets) { var projectIds = stateSet.GetProjectsWithDiagnostics(); foreach (var projectId in projectIds) { stateSet.CollectDocumentsWithDiagnostics(projectId, documentSet); RaiseProjectDiagnosticsRemoved(stateSet, projectId, documentSet, handleActiveFile, raiseEvents); documentSet.Clear(); } } }); } private void ClearAllDiagnostics(ImmutableArray<StateSet> stateSets, ProjectId projectId) { AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents => { using var _ = PooledHashSet<DocumentId>.GetInstance(out var documentSet); foreach (var stateSet in stateSets) { Debug.Assert(documentSet.Count == 0); stateSet.CollectDocumentsWithDiagnostics(projectId, documentSet); // PERF: don't fire events for ones that we dont have any diagnostics on if (documentSet.Count > 0) { RaiseProjectDiagnosticsRemoved(stateSet, projectId, documentSet, handleActiveFile: true, raiseEvents); documentSet.Clear(); } } }); } private void RaiseDiagnosticsCreated( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> items, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(project.Solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateId(stateSet, project.Id, AnalysisKind.NonLocal), project.Solution.Workspace, project.Solution, project.Id, documentId: null, diagnostics: items)); } private void RaiseDiagnosticsRemoved( ProjectId projectId, Solution? solution, StateSet stateSet, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(solution == null || solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateId(stateSet, projectId, AnalysisKind.NonLocal), Workspace, solution, projectId, documentId: null)); } private void RaiseDiagnosticsCreated( TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray<DiagnosticData> items, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(document.Project.Solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateId(stateSet, document.Id, kind), document.Project.Solution.Workspace, document.Project.Solution, document.Project.Id, document.Id, items)); } private void RaiseDiagnosticsRemoved( DocumentId documentId, Solution? solution, StateSet stateSet, AnalysisKind kind, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(solution == null || solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateId(stateSet, documentId, kind), Workspace, solution, documentId.ProjectId, documentId)); } private static object CreateId(StateSet stateSet, DocumentId documentId, AnalysisKind kind) => new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, documentId, (int)kind, stateSet.ErrorSourceName); private static object CreateId(StateSet stateSet, ProjectId projectId, AnalysisKind kind) => new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, projectId, (int)kind, stateSet.ErrorSourceName); public static Task<VersionStamp> GetDiagnosticVersionAsync(Project project, CancellationToken cancellationToken) => project.GetDependentVersionAsync(cancellationToken); private static DiagnosticAnalysisResult GetResultOrEmpty(ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> map, DiagnosticAnalyzer analyzer, ProjectId projectId, VersionStamp version) { if (map.TryGetValue(analyzer, out var result)) { return result; } return DiagnosticAnalysisResult.CreateEmpty(projectId, version); } public void LogAnalyzerCountSummary() => _telemetry.ReportAndClear(_correlationId); internal IEnumerable<DiagnosticAnalyzer> GetAnalyzersTestOnly(Project project) => _stateManager.GetOrCreateStateSets(project).Select(s => s.Analyzer); private static string GetDocumentLogMessage(string title, TextDocument document, DiagnosticAnalyzer analyzer) => $"{title}: ({document.Id}, {document.Project.Id}), ({analyzer})"; private static string GetProjectLogMessage(Project project, IEnumerable<StateSet> stateSets) => $"project: ({project.Id}), ({string.Join(Environment.NewLine, stateSets.Select(s => s.Analyzer.ToString()))})"; private static string GetResetLogMessage(TextDocument document) => $"document close/reset: ({document.FilePath ?? document.Name})"; private static string GetOpenLogMessage(TextDocument document) => $"document open: ({document.FilePath ?? document.Name})"; private static string GetRemoveLogMessage(DocumentId id) => $"document remove: {id.ToString()}"; private static string GetRemoveLogMessage(ProjectId id) => $"project remove: {id.ToString()}"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Workspaces.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { /// <summary> /// Diagnostic Analyzer Engine V2 /// /// This one follows pattern compiler has set for diagnostic analyzer. /// </summary> internal partial class DiagnosticIncrementalAnalyzer : IIncrementalAnalyzer2 { private readonly int _correlationId; private readonly DiagnosticAnalyzerTelemetry _telemetry; private readonly StateManager _stateManager; private readonly InProcOrRemoteHostAnalyzerRunner _diagnosticAnalyzerRunner; private readonly IDocumentTrackingService _documentTrackingService; private ConditionalWeakTable<Project, CompilationWithAnalyzers?> _projectCompilationsWithAnalyzers; internal DiagnosticAnalyzerService AnalyzerService { get; } internal Workspace Workspace { get; } [Obsolete(MefConstruction.FactoryMethodMessage, error: true)] public DiagnosticIncrementalAnalyzer( DiagnosticAnalyzerService analyzerService, int correlationId, Workspace workspace, DiagnosticAnalyzerInfoCache analyzerInfoCache) { Contract.ThrowIfNull(analyzerService); AnalyzerService = analyzerService; Workspace = workspace; _documentTrackingService = workspace.Services.GetRequiredService<IDocumentTrackingService>(); _correlationId = correlationId; _stateManager = new StateManager(analyzerInfoCache); _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged; _telemetry = new DiagnosticAnalyzerTelemetry(); _diagnosticAnalyzerRunner = new InProcOrRemoteHostAnalyzerRunner(analyzerInfoCache, analyzerService.Listener); _projectCompilationsWithAnalyzers = new ConditionalWeakTable<Project, CompilationWithAnalyzers?>(); } internal DiagnosticAnalyzerInfoCache DiagnosticAnalyzerInfoCache => _diagnosticAnalyzerRunner.AnalyzerInfoCache; [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/54400", Constraint = "Avoid calling GetAllHostStateSets on this hot path.")] public bool ContainsDiagnostics(ProjectId projectId) { return _stateManager.HasAnyHostStateSet(static (stateSet, arg) => stateSet.ContainsAnyDocumentOrProjectDiagnostics(arg), projectId) || _stateManager.HasAnyProjectStateSet(projectId, static (stateSet, arg) => stateSet.ContainsAnyDocumentOrProjectDiagnostics(arg), projectId); } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return e.Option.Feature == nameof(SimplificationOptions) || e.Option.Feature == nameof(CodeStyleOptions) || e.Option == SolutionCrawlerOptions.BackgroundAnalysisScopeOption || e.Option == SolutionCrawlerOptions.SolutionBackgroundAnalysisScopeOption || #pragma warning disable CS0618 // Type or member is obsolete - F# is still on the older ClosedFileDiagnostic option. e.Option == SolutionCrawlerOptions.ClosedFileDiagnostic; #pragma warning restore CS0618 // Type or member is obsolete } private void OnProjectAnalyzerReferenceChanged(object? sender, ProjectAnalyzerReferenceChangedEventArgs e) { if (e.Removed.Length == 0) { // nothing to refresh return; } // events will be automatically serialized. var project = e.Project; var stateSets = e.Removed; // make sure we drop cache related to the analyzers foreach (var stateSet in stateSets) { stateSet.OnRemoved(); } ClearAllDiagnostics(stateSets, project.Id); } public void Shutdown() { var stateSets = _stateManager.GetAllStateSets(); AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents => { var handleActiveFile = true; using var _ = PooledHashSet<DocumentId>.GetInstance(out var documentSet); foreach (var stateSet in stateSets) { var projectIds = stateSet.GetProjectsWithDiagnostics(); foreach (var projectId in projectIds) { stateSet.CollectDocumentsWithDiagnostics(projectId, documentSet); RaiseProjectDiagnosticsRemoved(stateSet, projectId, documentSet, handleActiveFile, raiseEvents); documentSet.Clear(); } } }); } private void ClearAllDiagnostics(ImmutableArray<StateSet> stateSets, ProjectId projectId) { AnalyzerService.RaiseBulkDiagnosticsUpdated(raiseEvents => { using var _ = PooledHashSet<DocumentId>.GetInstance(out var documentSet); foreach (var stateSet in stateSets) { Debug.Assert(documentSet.Count == 0); stateSet.CollectDocumentsWithDiagnostics(projectId, documentSet); // PERF: don't fire events for ones that we dont have any diagnostics on if (documentSet.Count > 0) { RaiseProjectDiagnosticsRemoved(stateSet, projectId, documentSet, handleActiveFile: true, raiseEvents); documentSet.Clear(); } } }); } private void RaiseDiagnosticsCreated( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> items, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(project.Solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateId(stateSet, project.Id, AnalysisKind.NonLocal), project.Solution.Workspace, project.Solution, project.Id, documentId: null, diagnostics: items)); } private void RaiseDiagnosticsRemoved( ProjectId projectId, Solution? solution, StateSet stateSet, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(solution == null || solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateId(stateSet, projectId, AnalysisKind.NonLocal), Workspace, solution, projectId, documentId: null)); } private void RaiseDiagnosticsCreated( TextDocument document, StateSet stateSet, AnalysisKind kind, ImmutableArray<DiagnosticData> items, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(document.Project.Solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsCreated( CreateId(stateSet, document.Id, kind), document.Project.Solution.Workspace, document.Project.Solution, document.Project.Id, document.Id, items)); } private void RaiseDiagnosticsRemoved( DocumentId documentId, Solution? solution, StateSet stateSet, AnalysisKind kind, Action<DiagnosticsUpdatedArgs> raiseEvents) { Contract.ThrowIfFalse(solution == null || solution.Workspace == Workspace); raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsRemoved( CreateId(stateSet, documentId, kind), Workspace, solution, documentId.ProjectId, documentId)); } private static object CreateId(StateSet stateSet, DocumentId documentId, AnalysisKind kind) => new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, documentId, (int)kind, stateSet.ErrorSourceName); private static object CreateId(StateSet stateSet, ProjectId projectId, AnalysisKind kind) => new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, projectId, (int)kind, stateSet.ErrorSourceName); public static Task<VersionStamp> GetDiagnosticVersionAsync(Project project, CancellationToken cancellationToken) => project.GetDependentVersionAsync(cancellationToken); private static DiagnosticAnalysisResult GetResultOrEmpty(ImmutableDictionary<DiagnosticAnalyzer, DiagnosticAnalysisResult> map, DiagnosticAnalyzer analyzer, ProjectId projectId, VersionStamp version) { if (map.TryGetValue(analyzer, out var result)) { return result; } return DiagnosticAnalysisResult.CreateEmpty(projectId, version); } public void LogAnalyzerCountSummary() => _telemetry.ReportAndClear(_correlationId); internal IEnumerable<DiagnosticAnalyzer> GetAnalyzersTestOnly(Project project) => _stateManager.GetOrCreateStateSets(project).Select(s => s.Analyzer); private static string GetDocumentLogMessage(string title, TextDocument document, DiagnosticAnalyzer analyzer) => $"{title}: ({document.Id}, {document.Project.Id}), ({analyzer})"; private static string GetProjectLogMessage(Project project, IEnumerable<StateSet> stateSets) => $"project: ({project.Id}), ({string.Join(Environment.NewLine, stateSets.Select(s => s.Analyzer.ToString()))})"; private static string GetResetLogMessage(TextDocument document) => $"document close/reset: ({document.FilePath ?? document.Name})"; private static string GetOpenLogMessage(TextDocument document) => $"document open: ({document.FilePath ?? document.Name})"; private static string GetRemoveLogMessage(DocumentId id) => $"document remove: {id.ToString()}"; private static string GetRemoveLogMessage(ProjectId id) => $"project remove: {id.ToString()}"; } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IUnitTestingIncrementalAnalyzerProviderImplementation _incrementalAnalyzerProvider; private readonly Workspace _workspace; private IIncrementalAnalyzer? _lazyAnalyzer; internal UnitTestingIncrementalAnalyzerProvider(Workspace workspace, IUnitTestingIncrementalAnalyzerProviderImplementation incrementalAnalyzerProvider) { _workspace = workspace; _incrementalAnalyzerProvider = incrementalAnalyzerProvider; } // NOTE: We're currently expecting the analyzer to be singleton, so that // analyzers returned when calling this method twice would pass a reference equality check. // One instance should be created by SolutionCrawler, another one by us, when calling the // UnitTestingSolutionCrawlerServiceAccessor.Reanalyze method. IIncrementalAnalyzer IIncrementalAnalyzerProvider.CreateIncrementalAnalyzer(Workspace workspace) => _lazyAnalyzer ??= new UnitTestingIncrementalAnalyzer(_incrementalAnalyzerProvider.CreateIncrementalAnalyzer()); public void Reanalyze() { var solutionCrawlerService = _workspace.Services.GetService<ISolutionCrawlerService>(); if (solutionCrawlerService != null) { var analyzer = ((IIncrementalAnalyzerProvider)this).CreateIncrementalAnalyzer(_workspace)!; solutionCrawlerService.Reanalyze(_workspace, analyzer, projectIds: null, documentIds: null, highPriority: false); } } public static UnitTestingIncrementalAnalyzerProvider? TryRegister(Workspace workspace, string analyzerName, IUnitTestingIncrementalAnalyzerProviderImplementation provider) { var solutionCrawlerRegistrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); if (solutionCrawlerRegistrationService == null) { return null; } var analyzerProvider = new UnitTestingIncrementalAnalyzerProvider(workspace, provider); var metadata = new IncrementalAnalyzerProviderMetadata( analyzerName, highPriorityForActiveFile: false, new[] { workspace.Kind }); solutionCrawlerRegistrationService.AddAnalyzerProvider(analyzerProvider, metadata); return analyzerProvider; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IUnitTestingIncrementalAnalyzerProviderImplementation _incrementalAnalyzerProvider; private readonly Workspace _workspace; private IIncrementalAnalyzer? _lazyAnalyzer; internal UnitTestingIncrementalAnalyzerProvider(Workspace workspace, IUnitTestingIncrementalAnalyzerProviderImplementation incrementalAnalyzerProvider) { _workspace = workspace; _incrementalAnalyzerProvider = incrementalAnalyzerProvider; } // NOTE: We're currently expecting the analyzer to be singleton, so that // analyzers returned when calling this method twice would pass a reference equality check. // One instance should be created by SolutionCrawler, another one by us, when calling the // UnitTestingSolutionCrawlerServiceAccessor.Reanalyze method. IIncrementalAnalyzer IIncrementalAnalyzerProvider.CreateIncrementalAnalyzer(Workspace workspace) => _lazyAnalyzer ??= new UnitTestingIncrementalAnalyzer(_incrementalAnalyzerProvider.CreateIncrementalAnalyzer()); public void Reanalyze() { var solutionCrawlerService = _workspace.Services.GetService<ISolutionCrawlerService>(); if (solutionCrawlerService != null) { var analyzer = ((IIncrementalAnalyzerProvider)this).CreateIncrementalAnalyzer(_workspace)!; solutionCrawlerService.Reanalyze(_workspace, analyzer, projectIds: null, documentIds: null, highPriority: false); } } public static UnitTestingIncrementalAnalyzerProvider? TryRegister(Workspace workspace, string analyzerName, IUnitTestingIncrementalAnalyzerProviderImplementation provider) { var solutionCrawlerRegistrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); if (solutionCrawlerRegistrationService == null) { return null; } var analyzerProvider = new UnitTestingIncrementalAnalyzerProvider(workspace, provider); var metadata = new IncrementalAnalyzerProviderMetadata( analyzerName, highPriorityForActiveFile: false, new[] { workspace.Kind }); solutionCrawlerRegistrationService.AddAnalyzerProvider(analyzerProvider, metadata); return analyzerProvider; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/CoreTest/FindAllDeclarationsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public partial class FindAllDeclarationsTests : TestBase { #region FindDeclarationsAsync [Theory, InlineData("", true, SolutionKind.SingleClass, new string[0]), InlineData(" ", true, SolutionKind.SingleClass, new string[0]), InlineData("\u2619", true, SolutionKind.SingleClass, new string[0]), InlineData("testcase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.SingleClass, new string[0]), InlineData("testcases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.SingleClass, new string[0]), InlineData("TestCase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.SingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.SingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.SingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testcase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("testcases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("TestCase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("innertestcase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("innertestcase", false, SolutionKind.NestedClass, new string[0]), InlineData("InnerTestCase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("InnerTestCase", false, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("testcase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("testcase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]), InlineData("TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase1.TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]),] public async Task FindDeclarationsAsync_Test(string searchTerm, bool ignoreCase, SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindDeclarationsAsync(project, searchTerm, ignoreCase).ConfigureAwait(false); Verify(searchTerm, ignoreCase, workspaceKind, declarations, expectedResults); } [Fact] public async Task FindDeclarationsAsync_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindDeclarationsAsync(null, "Test", true); }); } [Fact] public async Task FindDeclarationsAsync_Test_NullString() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindDeclarationsAsync(project, null, true); }); } [Theory, CombinatorialData] public async Task FindDeclarationsAsync_Test_Cancellation(TestHost testHost) { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project, testHost); var declarations = await SymbolFinder.FindDeclarationsAsync(project, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); } [Theory, CombinatorialData] [WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public async Task FindDeclarationsAsync_Metadata(TestHost testHost) { using var workspace = CreateWorkspace(testHost); var solution = workspace.CurrentSolution; var csharpId = ProjectId.CreateNewId(); solution = solution .AddProject(csharpId, "CSharp", "CSharp", LanguageNames.CSharp) .AddMetadataReference(csharpId, MscorlibRef); var vbId = ProjectId.CreateNewId(); solution = solution .AddProject(vbId, "VB", "VB", LanguageNames.VisualBasic) .AddMetadataReference(vbId, MscorlibRef); var csharpResult = await SymbolFinder.FindDeclarationsAsync(solution.GetProject(csharpId), "Console", ignoreCase: false); Assert.True(csharpResult.Count() > 0); var vbResult = await SymbolFinder.FindDeclarationsAsync(solution.GetProject(vbId), "Console", ignoreCase: true); Assert.True(vbResult.Count() > 0); } [Theory, CombinatorialData] [WorkItem(6616, "https://github.com/dotnet/roslyn/issues/6616")] public async Task FindDeclarationsAsync_PreviousSubmission(TestHost testHost) { using var workspace = CreateWorkspace(testHost); var solution = workspace.CurrentSolution; var submission0Id = ProjectId.CreateNewId(); var submission0DocId = DocumentId.CreateNewId(submission0Id); const string submission0Name = "Submission#0"; solution = solution .AddProject(submission0Id, submission0Name, submission0Name, LanguageNames.CSharp) .AddMetadataReference(submission0Id, MscorlibRef) .AddDocument(submission0DocId, submission0Name, @" public class Outer { public class Inner { } } "); var submission1Id = ProjectId.CreateNewId(); var submission1DocId = DocumentId.CreateNewId(submission1Id); const string submission1Name = "Submission#1"; solution = solution .AddProject(submission1Id, submission1Name, submission1Name, LanguageNames.CSharp) .AddMetadataReference(submission1Id, MscorlibRef) .AddProjectReference(submission1Id, new ProjectReference(submission0Id)) .AddDocument(submission1DocId, submission1Name, @" Inner i; "); var actualSymbol = (await SymbolFinder.FindDeclarationsAsync(solution.GetProject(submission1Id), "Inner", ignoreCase: false)).SingleOrDefault(); var expectedSymbol = (await solution.GetProject(submission0Id).GetCompilationAsync()).GlobalNamespace.GetMembers("Outer").SingleOrDefault().GetMembers("Inner").SingleOrDefault(); Assert.Equal(expectedSymbol, actualSymbol); } #endregion #region FindSourceDeclarationsAsync_Project [Theory, InlineData("", true, SolutionKind.SingleClass, new string[0]), InlineData(" ", true, SolutionKind.SingleClass, new string[0]), InlineData("\u2619", true, SolutionKind.SingleClass, new string[0]), InlineData("testcase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.SingleClass, new string[0]), InlineData("testcases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.SingleClass, new string[0]), InlineData("TestCase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.SingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.SingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.SingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testcase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("testcases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("TestCase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("innertestcase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("innertestcase", false, SolutionKind.NestedClass, new string[0]), InlineData("InnerTestCase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("InnerTestCase", false, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("testcase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("testcase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]), InlineData("TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase1.TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]),] public async Task FindSourceDeclarationsAsync_Project_Test(string searchTerm, bool ignoreCase, SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, searchTerm, ignoreCase).ConfigureAwait(false); Verify(searchTerm, ignoreCase, workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Project)null, "Test", true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Test_NullString() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, null, true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsAsync_Solution [Theory, InlineData("", true, SolutionKind.SingleClass, new string[0]), InlineData(" ", true, SolutionKind.SingleClass, new string[0]), InlineData("\u2619", true, SolutionKind.SingleClass, new string[0]), InlineData("testcase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.SingleClass, new string[0]), InlineData("testcases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.SingleClass, new string[0]), InlineData("TestCase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.SingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.SingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.SingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testcase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase", "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("testcases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases" }), InlineData("testcases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("TestCase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase", "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase", "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases" }), InlineData("TestCases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases" }), InlineData("test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])", "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])", "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])", "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty", "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty", "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty", "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField", "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField", "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField", "TestCases.TestCase.TestField" }), InlineData("innertestcase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("innertestcase", false, SolutionKind.NestedClass, new string[0]), InlineData("InnerTestCase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("InnerTestCase", false, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("testcase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("testcase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]), InlineData("TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase1.TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]),] public async Task FindSourceDeclarationsAsync_Solution_Test(string searchTerm, bool ignoreCase, SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, searchTerm, ignoreCase).ConfigureAwait(false); Verify(searchTerm, ignoreCase, workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Solution)null, "Test", true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Test_NullString() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, null, true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsAsync_Project_Func [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsAsync_Project_Func_Test(SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => str.Contains("Test")).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_AlwaysTruePredicate() { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => true).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations, "TestCases", "TestCases.TestCase"); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_AlwaysFalsePredicate() { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => false).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Project)null, str => str.Contains("Test")); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_NullPredicate() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, null); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => str.Contains("Test"), SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsAsync_Solution_Func [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])", "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsAsync_Solution_Func_Test(SolutionKind workspaceKind, string[] expectedResult) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, str => str.Contains("Test")).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResult); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_AlwaysTruePredicate() { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, str => true).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations, "TestCases", "TestCases.TestCase"); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_AlwaysFalsePredicate() { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, str => false).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_NullSolution() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { await SymbolFinder.FindSourceDeclarationsAsync((Solution)null, str => str.Contains("Test")); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_NullPredicate() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsAsync(solution, null); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsAsync(solution, str => str.Contains("Test"), SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsWithPatternAsync_Project [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test(SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, "test").ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Theory, InlineData(SolutionKind.SingleClass, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleProperty, "tp", new[] { "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, "tf", new[] { "TestCases.TestCase.TestField" }),] public async Task FindSourceDeclarationsWithPatternAsync_CamelCase_Project_Test(SolutionKind workspaceKind, string pattern, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, pattern).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync((Project)null, "test"); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullPattern() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, null); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, "test", SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsWithPatternAsync_Solution [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])", "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test(SolutionKind workspaceKind, string[] expectedResult) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, "test").ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResult); } [Theory, InlineData(SolutionKind.SingleClass, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleProperty, "tp", new[] { "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, "tf", new[] { "TestCases.TestCase.TestField" }),] public async Task FindSourceDeclarationsWithPatternAsync_CamelCase_Solution_Test(SolutionKind workspaceKind, string pattern, string[] expectedResults) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, pattern).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullSolution() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { await SymbolFinder.FindSourceDeclarationsWithPatternAsync((Solution)null, "test"); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullPattern() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, null); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, "test", SymbolFilter.All, new CancellationToken(true)); }); } #endregion [Fact] public async Task TestSymbolTreeInfoSerialization() { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var project = solution.Projects.First(); // create symbol tree info from assembly var info = await SymbolTreeInfo.CreateSourceSymbolTreeInfoAsync( project, Checksum.Null, cancellationToken: CancellationToken.None); using var writerStream = new MemoryStream(); using (var writer = new ObjectWriter(writerStream, leaveOpen: true)) { info.WriteTo(writer); } using var readerStream = new MemoryStream(writerStream.ToArray()); using var reader = ObjectReader.TryGetReader(readerStream); var readInfo = SymbolTreeInfo.TestAccessor.ReadSymbolTreeInfo(reader, Checksum.Null); info.AssertEquivalentTo(readInfo); } [Fact, WorkItem(7941, "https://github.com/dotnet/roslyn/pull/7941")] public async Task FindDeclarationsInErrorSymbolsDoesntCrash() { var source = @" ' missing `Class` keyword Public Class1 Public Event MyEvent(ByVal a As String) End Class "; // create solution var pid = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pid, "VBProject", "VBProject", LanguageNames.VisualBasic) .AddMetadataReference(pid, MscorlibRef); var did = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did, "VBDocument.vb", SourceText.From(source)); var project = solution.Projects.Single(); // perform the search var foundDeclarations = await SymbolFinder.FindDeclarationsAsync(project, name: "MyEvent", ignoreCase: true); Assert.Equal(1, foundDeclarations.Count()); Assert.False(foundDeclarations.Any(decl => decl == null)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Remote.Testing; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] public partial class FindAllDeclarationsTests : TestBase { #region FindDeclarationsAsync [Theory, InlineData("", true, SolutionKind.SingleClass, new string[0]), InlineData(" ", true, SolutionKind.SingleClass, new string[0]), InlineData("\u2619", true, SolutionKind.SingleClass, new string[0]), InlineData("testcase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.SingleClass, new string[0]), InlineData("testcases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.SingleClass, new string[0]), InlineData("TestCase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.SingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.SingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.SingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testcase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("testcases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("TestCase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("innertestcase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("innertestcase", false, SolutionKind.NestedClass, new string[0]), InlineData("InnerTestCase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("InnerTestCase", false, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("testcase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("testcase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]), InlineData("TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase1.TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]),] public async Task FindDeclarationsAsync_Test(string searchTerm, bool ignoreCase, SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindDeclarationsAsync(project, searchTerm, ignoreCase).ConfigureAwait(false); Verify(searchTerm, ignoreCase, workspaceKind, declarations, expectedResults); } [Fact] public async Task FindDeclarationsAsync_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindDeclarationsAsync(null, "Test", true); }); } [Fact] public async Task FindDeclarationsAsync_Test_NullString() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindDeclarationsAsync(project, null, true); }); } [Theory, CombinatorialData] public async Task FindDeclarationsAsync_Test_Cancellation(TestHost testHost) { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project, testHost); var declarations = await SymbolFinder.FindDeclarationsAsync(project, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); } [Theory, CombinatorialData] [WorkItem(1094411, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1094411")] public async Task FindDeclarationsAsync_Metadata(TestHost testHost) { using var workspace = CreateWorkspace(testHost); var solution = workspace.CurrentSolution; var csharpId = ProjectId.CreateNewId(); solution = solution .AddProject(csharpId, "CSharp", "CSharp", LanguageNames.CSharp) .AddMetadataReference(csharpId, MscorlibRef); var vbId = ProjectId.CreateNewId(); solution = solution .AddProject(vbId, "VB", "VB", LanguageNames.VisualBasic) .AddMetadataReference(vbId, MscorlibRef); var csharpResult = await SymbolFinder.FindDeclarationsAsync(solution.GetProject(csharpId), "Console", ignoreCase: false); Assert.True(csharpResult.Count() > 0); var vbResult = await SymbolFinder.FindDeclarationsAsync(solution.GetProject(vbId), "Console", ignoreCase: true); Assert.True(vbResult.Count() > 0); } [Theory, CombinatorialData] [WorkItem(6616, "https://github.com/dotnet/roslyn/issues/6616")] public async Task FindDeclarationsAsync_PreviousSubmission(TestHost testHost) { using var workspace = CreateWorkspace(testHost); var solution = workspace.CurrentSolution; var submission0Id = ProjectId.CreateNewId(); var submission0DocId = DocumentId.CreateNewId(submission0Id); const string submission0Name = "Submission#0"; solution = solution .AddProject(submission0Id, submission0Name, submission0Name, LanguageNames.CSharp) .AddMetadataReference(submission0Id, MscorlibRef) .AddDocument(submission0DocId, submission0Name, @" public class Outer { public class Inner { } } "); var submission1Id = ProjectId.CreateNewId(); var submission1DocId = DocumentId.CreateNewId(submission1Id); const string submission1Name = "Submission#1"; solution = solution .AddProject(submission1Id, submission1Name, submission1Name, LanguageNames.CSharp) .AddMetadataReference(submission1Id, MscorlibRef) .AddProjectReference(submission1Id, new ProjectReference(submission0Id)) .AddDocument(submission1DocId, submission1Name, @" Inner i; "); var actualSymbol = (await SymbolFinder.FindDeclarationsAsync(solution.GetProject(submission1Id), "Inner", ignoreCase: false)).SingleOrDefault(); var expectedSymbol = (await solution.GetProject(submission0Id).GetCompilationAsync()).GlobalNamespace.GetMembers("Outer").SingleOrDefault().GetMembers("Inner").SingleOrDefault(); Assert.Equal(expectedSymbol, actualSymbol); } #endregion #region FindSourceDeclarationsAsync_Project [Theory, InlineData("", true, SolutionKind.SingleClass, new string[0]), InlineData(" ", true, SolutionKind.SingleClass, new string[0]), InlineData("\u2619", true, SolutionKind.SingleClass, new string[0]), InlineData("testcase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.SingleClass, new string[0]), InlineData("testcases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.SingleClass, new string[0]), InlineData("TestCase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.SingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.SingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.SingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testcase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("testcases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("TestCase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases" }), InlineData("test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("innertestcase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("innertestcase", false, SolutionKind.NestedClass, new string[0]), InlineData("InnerTestCase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("InnerTestCase", false, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("testcase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("testcase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]), InlineData("TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase1.TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]),] public async Task FindSourceDeclarationsAsync_Project_Test(string searchTerm, bool ignoreCase, SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, searchTerm, ignoreCase).ConfigureAwait(false); Verify(searchTerm, ignoreCase, workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Project)null, "Test", true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Test_NullString() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, null, true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsAsync_Solution [Theory, InlineData("", true, SolutionKind.SingleClass, new string[0]), InlineData(" ", true, SolutionKind.SingleClass, new string[0]), InlineData("\u2619", true, SolutionKind.SingleClass, new string[0]), InlineData("testcase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.SingleClass, new string[0]), InlineData("testcases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("testcases", false, SolutionKind.SingleClass, new string[0]), InlineData("TestCase", true, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.SingleClass, new[] { "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("TestCases", false, SolutionKind.SingleClass, new[] { "TestCases" }), InlineData("test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.SingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.SingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.SingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.SingleClassWithSingleField, new[] { "TestCases.TestCase.TestField" }), InlineData("testcase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase", "TestCases.TestCase" }), InlineData("testcase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("testcases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases" }), InlineData("testcases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("TestCase", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase", "TestCases.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase", "TestCases.TestCase" }), InlineData("TestCases", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases" }), InlineData("TestCases", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases" }), InlineData("test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])", "TestCases.TestCase.Test(string[])" }), InlineData("test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new string[0]), InlineData("Test", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])", "TestCases.TestCase.Test(string[])" }), InlineData("Test", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases.TestCase.Test(string[])", "TestCases.TestCase.Test(string[])" }), InlineData("testproperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty", "TestCases.TestCase.TestProperty" }), InlineData("testproperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new string[0]), InlineData("TestProperty", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty", "TestCases.TestCase.TestProperty" }), InlineData("TestProperty", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases.TestCase.TestProperty", "TestCases.TestCase.TestProperty" }), InlineData("testfield", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField", "TestCases.TestCase.TestField" }), InlineData("testfield", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new string[0]), InlineData("TestField", true, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField", "TestCases.TestCase.TestField" }), InlineData("TestField", false, SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases.TestCase.TestField", "TestCases.TestCase.TestField" }), InlineData("innertestcase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("innertestcase", false, SolutionKind.NestedClass, new string[0]), InlineData("InnerTestCase", true, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("InnerTestCase", false, SolutionKind.NestedClass, new[] { "TestCases.TestCase.InnerTestCase" }), InlineData("testcase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("testcase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]), InlineData("TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase", false, SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1.TestCase", "TestCase2.TestCase" }), InlineData("TestCase1.TestCase", true, SolutionKind.TwoNamespacesWithIdenticalClasses, new string[0]),] public async Task FindSourceDeclarationsAsync_Solution_Test(string searchTerm, bool ignoreCase, SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, searchTerm, ignoreCase).ConfigureAwait(false); Verify(searchTerm, ignoreCase, workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Solution)null, "Test", true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Test_NullString() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, null, true); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, "Test", true, SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsAsync_Project_Func [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsAsync_Project_Func_Test(SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => str.Contains("Test")).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_AlwaysTruePredicate() { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => true).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations, "TestCases", "TestCases.TestCase"); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_AlwaysFalsePredicate() { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => false).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsAsync((Project)null, str => str.Contains("Test")); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_NullPredicate() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, null); }); } [Fact] public async Task FindSourceDeclarationsAsync_Project_Func_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(project, str => str.Contains("Test"), SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsAsync_Solution_Func [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])", "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsAsync_Solution_Func_Test(SolutionKind workspaceKind, string[] expectedResult) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, str => str.Contains("Test")).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResult); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_AlwaysTruePredicate() { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, str => true).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations, "TestCases", "TestCases.TestCase"); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_AlwaysFalsePredicate() { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsAsync(solution, str => false).ConfigureAwait(false); Verify(SolutionKind.SingleClass, declarations); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_NullSolution() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { await SymbolFinder.FindSourceDeclarationsAsync((Solution)null, str => str.Contains("Test")); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_NullPredicate() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsAsync(solution, null); }); } [Fact] public async Task FindSourceDeclarationsAsync_Solution_Func_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsAsync(solution, str => str.Contains("Test"), SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsWithPatternAsync_Project [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test(SolutionKind workspaceKind, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, "test").ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Theory, InlineData(SolutionKind.SingleClass, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleProperty, "tp", new[] { "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, "tf", new[] { "TestCases.TestCase.TestField" }),] public async Task FindSourceDeclarationsWithPatternAsync_CamelCase_Project_Test(SolutionKind workspaceKind, string pattern, string[] expectedResults) { using var workspace = CreateWorkspaceWithProject(workspaceKind, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, pattern).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullProject() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync((Project)null, "test"); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_NullPattern() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, null); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Project_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithProject(SolutionKind.SingleClass, out var project); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(project, "test", SymbolFilter.All, new CancellationToken(true)); }); } #endregion #region FindSourceDeclarationsWithPatternAsync_Solution [Theory, InlineData(SolutionKind.SingleClass, new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.SingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleMethod, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])", "TestCases", "TestCases.TestCase", "TestCases.TestCase.Test(string[])" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleProperty, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.TwoProjectsEachWithASingleClassWithSingleField, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField", "TestCases", "TestCases.TestCase", "TestCases.TestCase.TestField" }), InlineData(SolutionKind.NestedClass, new[] { "TestCases", "TestCases.TestCase", "TestCases.TestCase.InnerTestCase" }), InlineData(SolutionKind.TwoNamespacesWithIdenticalClasses, new[] { "TestCase1", "TestCase1.TestCase", "TestCase2.TestCase", "TestCase2" }),] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test(SolutionKind workspaceKind, string[] expectedResult) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, "test").ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResult); } [Theory, InlineData(SolutionKind.SingleClass, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleMethod, "tc", new[] { "TestCases", "TestCases.TestCase" }), InlineData(SolutionKind.SingleClassWithSingleProperty, "tp", new[] { "TestCases.TestCase.TestProperty" }), InlineData(SolutionKind.SingleClassWithSingleField, "tf", new[] { "TestCases.TestCase.TestField" }),] public async Task FindSourceDeclarationsWithPatternAsync_CamelCase_Solution_Test(SolutionKind workspaceKind, string pattern, string[] expectedResults) { using var workspace = CreateWorkspaceWithSolution(workspaceKind, out var solution); var declarations = await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, pattern).ConfigureAwait(false); Verify(workspaceKind, declarations, expectedResults); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullSolution() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { await SymbolFinder.FindSourceDeclarationsWithPatternAsync((Solution)null, "test"); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_NullPattern() { await Assert.ThrowsAnyAsync<ArgumentNullException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, null); }); } [Fact] public async Task FindSourceDeclarationsWithPatternAsync_Solution_Test_Cancellation() { await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); await SymbolFinder.FindSourceDeclarationsWithPatternAsync(solution, "test", SymbolFilter.All, new CancellationToken(true)); }); } #endregion [Fact] public async Task TestSymbolTreeInfoSerialization() { using var workspace = CreateWorkspaceWithSolution(SolutionKind.SingleClass, out var solution); var project = solution.Projects.First(); // create symbol tree info from assembly var info = await SymbolTreeInfo.CreateSourceSymbolTreeInfoAsync( project, Checksum.Null, cancellationToken: CancellationToken.None); using var writerStream = new MemoryStream(); using (var writer = new ObjectWriter(writerStream, leaveOpen: true)) { info.WriteTo(writer); } using var readerStream = new MemoryStream(writerStream.ToArray()); using var reader = ObjectReader.TryGetReader(readerStream); var readInfo = SymbolTreeInfo.TestAccessor.ReadSymbolTreeInfo(reader, Checksum.Null); info.AssertEquivalentTo(readInfo); } [Fact, WorkItem(7941, "https://github.com/dotnet/roslyn/pull/7941")] public async Task FindDeclarationsInErrorSymbolsDoesntCrash() { var source = @" ' missing `Class` keyword Public Class1 Public Event MyEvent(ByVal a As String) End Class "; // create solution var pid = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pid, "VBProject", "VBProject", LanguageNames.VisualBasic) .AddMetadataReference(pid, MscorlibRef); var did = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did, "VBDocument.vb", SourceText.From(source)); var project = solution.Projects.Single(); // perform the search var foundDeclarations = await SymbolFinder.FindDeclarationsAsync(project, name: "MyEvent", ignoreCase: true); Assert.Equal(1, foundDeclarations.Count()); Assert.False(foundDeclarations.Any(decl => decl == null)); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/Core/Implementation/NavigationBar/NavigationBarModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { internal sealed class NavigationBarModel : IEquatable<NavigationBarModel> { public INavigationBarItemService ItemService { get; } public ImmutableArray<NavigationBarItem> Types { get; } public NavigationBarModel(INavigationBarItemService itemService, ImmutableArray<NavigationBarItem> types) { ItemService = itemService; Types = types; } public override bool Equals(object? obj) => Equals(obj as NavigationBarModel); public bool Equals(NavigationBarModel? other) => other != null && Types.SequenceEqual(other.Types); public override int GetHashCode() => throw new NotImplementedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar { internal sealed class NavigationBarModel : IEquatable<NavigationBarModel> { public INavigationBarItemService ItemService { get; } public ImmutableArray<NavigationBarItem> Types { get; } public NavigationBarModel(INavigationBarItemService itemService, ImmutableArray<NavigationBarItem> types) { ItemService = itemService; Types = types; } public override bool Equals(object? obj) => Equals(obj as NavigationBarModel); public bool Equals(NavigationBarModel? other) => other != null && Types.SequenceEqual(other.Types); public override int GetHashCode() => throw new NotImplementedException(); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/VisualBasic/Test/Semantic/Semantics/UnaryOperators.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class UnaryOperators Inherits BasicTestBase <Fact> <WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")> Public Sub Test1() Dim source = <compilation name="UnaryOperator1"> <file name="a.vb"> Option Strict Off Module Module1 Sub Main() Dim Bo As Boolean Dim SB As SByte Dim By As Byte Dim Sh As Short Dim US As UShort Dim [In] As Integer Dim UI As UInteger Dim Lo As Long Dim UL As ULong Dim De As Decimal Dim Si As Single Dim [Do] As Double Dim St As String Dim Ob As Object Dim Tc As System.TypeCode Bo = False SB = -1 By = 2 Sh = -3 US = 4 [In] = -5 UI = 6 Lo = -7 UL = 8 De = -9D Si = 10 [Do] = -11 St = "12" Ob = -13 System.Console.WriteLine("Unary Minus") PrintResult(-Nothing) PrintResult(-Bo) PrintResult(-SB) PrintResult(-By) PrintResult(-Sh) PrintResult(-US) PrintResult(-[In]) PrintResult(-UI) PrintResult(-Lo) PrintResult(-UL) PrintResult(-De) PrintResult(-Si) PrintResult(-[Do]) PrintResult(-St) PrintResult(-Ob) PrintResult(-Tc) PrintResult(-True) PrintResult(-False) PrintResult(-System.SByte.MaxValue) PrintResult(-System.Byte.MaxValue) PrintResult(-14S) PrintResult(-15US) PrintResult(-16I) PrintResult(-17UI) PrintResult(-19L) PrintResult(-20UL) PrintResult(-System.Single.MaxValue) PrintResult(-22.0) PrintResult(-23D) PrintResult(-"24") System.Console.WriteLine("") System.Console.WriteLine("Unary Plus") PrintResult(+Nothing) PrintResult(+Bo) PrintResult(+SB) PrintResult(+By) PrintResult(+Sh) PrintResult(+US) PrintResult(+[In]) PrintResult(+UI) PrintResult(+Lo) PrintResult(+UL) PrintResult(+De) PrintResult(+Si) PrintResult(+[Do]) PrintResult(+St) PrintResult(+Ob) PrintResult(+Tc) PrintResult(+True) PrintResult(+False) PrintResult(+System.SByte.MaxValue) PrintResult(+System.Byte.MaxValue) PrintResult(+14S) PrintResult(+15US) PrintResult(+16I) PrintResult(+17UI) PrintResult(+19L) PrintResult(+20UL) PrintResult(+System.Single.MaxValue) PrintResult(+22.0) PrintResult(+23D) PrintResult(+"24") System.Console.WriteLine("") System.Console.WriteLine("Logical Not") PrintResult(Not Nothing) PrintResult(Not Bo) PrintResult(Not SB) PrintResult(Not By) PrintResult(Not Sh) PrintResult(Not US) PrintResult(Not [In]) PrintResult(Not UI) PrintResult(Not Lo) PrintResult(Not UL) PrintResult(Not De) PrintResult(Not Si) PrintResult(Not [Do]) PrintResult(Not St) PrintResult(Not Ob) PrintResult(Not Tc) PrintResult(Not True) PrintResult(Not False) PrintResult(Not System.SByte.MaxValue) PrintResult(Not System.Byte.MaxValue) PrintResult(Not 14S) PrintResult(Not 15US) PrintResult(Not 16I) PrintResult(Not 17UI) PrintResult(Not 19L) PrintResult(Not 20UL) PrintResult(Not 21.0F) PrintResult(Not 22.0) PrintResult(Not 23D) PrintResult(Not "24") End Sub Sub PrintResult(val As Boolean) System.Console.WriteLine("Boolean: {0}", val) End Sub Sub PrintResult(val As SByte) System.Console.WriteLine("SByte: {0}", val) End Sub Sub PrintResult(val As Byte) System.Console.WriteLine("Byte: {0}", val) End Sub Sub PrintResult(val As Short) System.Console.WriteLine("Short: {0}", val) End Sub Sub PrintResult(val As UShort) System.Console.WriteLine("UShort: {0}", val) End Sub Sub PrintResult(val As Integer) System.Console.WriteLine("Integer: {0}", val) End Sub Sub PrintResult(val As UInteger) System.Console.WriteLine("UInteger: {0}", val) End Sub Sub PrintResult(val As Long) System.Console.WriteLine("Long: {0}", val) End Sub Sub PrintResult(val As ULong) System.Console.WriteLine("ULong: {0}", val) End Sub Sub PrintResult(val As Decimal) System.Console.WriteLine("Decimal: {0}", val) End Sub Sub PrintResult(val As Single) System.Console.WriteLine("Single: {0}", val.ToString("G7", System.Globalization.CultureInfo.InvariantCulture)) End Sub Sub PrintResult(val As Double) System.Console.WriteLine("Double: {0}", val) End Sub 'Sub PrintResult(val As Date) ' System.Console.WriteLine("Date: {0}", val) 'End Sub Sub PrintResult(val As Char) System.Console.WriteLine("Char: {0}", val) End Sub Sub PrintResult(val As String) System.Console.WriteLine("String: ") System.Console.WriteLine(val) End Sub Sub PrintResult(val As Object) System.Console.WriteLine("Object: {0}", val) End Sub Sub PrintResult(val As System.TypeCode) System.Console.WriteLine("TypeCode: {0}", val) End Sub End Module </file> </compilation> Dim expected = <![CDATA[ Unary Minus Integer: 0 Short: 0 SByte: 1 Short: -2 Short: 3 Integer: -4 Integer: 5 Long: -6 Long: 7 Decimal: -8 Decimal: 9 Single: -10 Double: 11 Double: -12 Object: 13 Integer: 0 Short: 1 Short: 0 SByte: -127 Short: -255 Short: -14 Integer: -15 Integer: -16 Long: -17 Long: -19 Decimal: -20 Single: -3.402823E+38 Double: -22 Decimal: -23 Double: -24 Unary Plus Integer: 0 Short: 0 SByte: -1 Byte: 2 Short: -3 UShort: 4 Integer: -5 UInteger: 6 Long: -7 ULong: 8 Decimal: -9 Single: 10 Double: -11 Double: 12 Object: -13 Integer: 0 Short: -1 Short: 0 SByte: 127 Byte: 255 Short: 14 UShort: 15 Integer: 16 UInteger: 17 Long: 19 ULong: 20 Single: 3.402823E+38 Double: 22 Decimal: 23 Double: 24 Logical Not Integer: -1 Boolean: True SByte: 0 Byte: 253 Short: 2 UShort: 65531 Integer: 4 UInteger: 4294967289 Long: 6 ULong: 18446744073709551607 Long: 8 Long: -11 Long: 10 Long: -13 Object: 12 TypeCode: -1 Boolean: False Boolean: True SByte: -128 Byte: 0 Short: -15 UShort: 65520 Integer: -17 UInteger: 4294967278 Long: -20 ULong: 18446744073709551595 Long: -22 Long: -23 Long: -24 Long: -25 ]]> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Assert.True(c1.Options.CheckOverflow) CompileAndVerify(c1, expected) c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(c1.Options.CheckOverflow) CompileAndVerify(c1, expected) End Sub <Fact> Public Sub Test2() Dim compilationDef = <compilation name="Test2"> <file name="a.vb"> Option Strict On Module Module1 Sub Main() Dim Da As Date Dim Ch As Char Dim Ob As Object Dim result As Object result = -Da result = -Ch result = -Ob result = +Da result = +Ch result = +Ob result = Not Da result = Not Ch result = Not Ob result = --Da End Sub End Module </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30487: Operator '-' is not defined for type 'Date'. result = -Da ~~~ BC30487: Operator '-' is not defined for type 'Char'. result = -Ch ~~~ BC30038: Option Strict On prohibits operands of type Object for operator '-'. result = -Ob ~~ BC42104: Variable 'Ob' is used before it has been assigned a value. A null reference exception could result at runtime. result = -Ob ~~ BC30487: Operator '+' is not defined for type 'Date'. result = +Da ~~~ BC30487: Operator '+' is not defined for type 'Char'. result = +Ch ~~~ BC30038: Option Strict On prohibits operands of type Object for operator '+'. result = +Ob ~~ BC30487: Operator 'Not' is not defined for type 'Date'. result = Not Da ~~~~~~ BC30487: Operator 'Not' is not defined for type 'Char'. result = Not Ch ~~~~~~ BC30038: Option Strict On prohibits operands of type Object for operator 'Not'. result = Not Ob ~~ BC30487: Operator '-' is not defined for type 'Date'. result = --Da ~~~ </expected>) End Sub <Fact> Public Sub Test3() Dim c1 = VisualBasicCompilation.Create("Test3", syntaxTrees:={VisualBasicSyntaxTree.ParseText( <text> Option Strict Off Module Module1 Interface I1 End Interface Function Main() As I1 Dim result As Object result = -Nothing End Function End Module</text>.Value )}, references:=Nothing, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC31091: Import of type 'Object' from assembly or module 'Test3.dll' failed. Module Module1 ~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Module1 ~~~~~~~ BC30002: Type 'System.Object' is not defined. Dim result As Object ~~~~~~ BC30002: Type 'System.Int32' is not defined. result = -Nothing ~~~~~~~ BC42105: Function 'Main' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Test4() Dim source = <compilation name="UnaryOperator4"> <file name="a.vb"> Option Strict Off Imports System Module Module1 Sub Main() Dim Ob As Object Ob = -System.Byte.MinValue Ob = -System.Byte.MaxValue Ob = -System.SByte.MinValue Ob = -System.SByte.MaxValue Ob = -Int16.MinValue Ob = -Int16.MaxValue Ob = -UInt16.MaxValue Ob = -UInt16.MinValue Ob = -Int32.MinValue Ob = -Int32.MaxValue Ob = -UInt32.MaxValue Ob = -UInt32.MinValue Ob = -Int64.MinValue Ob = -Int64.MaxValue Ob = -UInt64.MaxValue Ob = -UInt64.MinValue Ob = -System.Decimal.MaxValue Ob = -System.Decimal.MinValue Ob = -System.Single.MaxValue Ob = -System.Single.MinValue Ob = -System.Double.MaxValue Ob = -System.Double.MinValue End Sub End Module </file> </compilation> Dim expected = <expected> BC30439: Constant expression not representable in type 'SByte'. Ob = -System.SByte.MinValue ~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Short'. Ob = -Int16.MinValue ~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Integer'. Ob = -Int32.MinValue ~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. Ob = -Int64.MinValue ~~~~~~~~~~~~~~~ </expected> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Assert.True(c1.Options.CheckOverflow) CompilationUtils.AssertTheseDiagnostics(c1, expected) Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(c2.Options.CheckOverflow) CompilationUtils.AssertTheseDiagnostics(c2, expected) End Sub <Fact> Public Sub Test5() Dim compilationDef = <compilation name="UnaryOperator2"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim Ob As Object = Nothing Ob = -Ob Ob = +Ob Ob = Not Ob End Sub End Module </file> </compilation> Dim expected = <expected> BC42019: Operands of type Object used for operator '-'; runtime errors could occur. Ob = -Ob ~~ BC42019: Operands of type Object used for operator '+'; runtime errors could occur. Ob = +Ob ~~ BC42019: Operands of type Object used for operator 'Not'; runtime errors could occur. Ob = Not Ob ~~ </expected> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, expected) End Sub <WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")> <Fact()> Public Sub Bug13088() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Public Const Z1 As Integer = +2147483648 'BIND:"Public Const Z1 As Integer = +2147483648" Public Const Z2 As Integer = (-(-2147483648)) 'BIND1:"Public Const Z2 As Integer = (-(-2147483648))" Sub Main() End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "+2147483648").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "(-(-2147483648))").WithArguments("Integer")) Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z1").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z2").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) End Sub <Fact()> Public Sub IntrinsicSymbols() Dim operators() As UnaryOperatorKind = { UnaryOperatorKind.Plus, UnaryOperatorKind.Minus, UnaryOperatorKind.Not } Dim opTokens = (From op In operators Select SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(op))).ToArray() Dim typeNames() As String = { "System.Object", "System.String", "System.Double", "System.SByte", "System.Int16", "System.Int32", "System.Int64", "System.Decimal", "System.Single", "System.Byte", "System.UInt16", "System.UInt32", "System.UInt64", "System.Boolean", "System.Char", "System.DateTime", "System.TypeCode", "System.StringComparison", "System.Guid" } Dim builder As New System.Text.StringBuilder Dim n As Integer = 0 For Each arg1 In typeNames n += 1 builder.AppendFormat( "Sub Test{1}(x1 as {0}, x2 as {0}?)" & vbCrLf, arg1, n) Dim k As Integer = 0 For Each opToken In opTokens builder.AppendFormat( " Dim z{0}_1 = {1} x1" & vbCrLf & " Dim z{0}_2 = {1} x2" & vbCrLf & " If {1} x1" & vbCrLf & " End If" & vbCrLf & " If {1} x2" & vbCrLf & " End If" & vbCrLf, k, opToken) k += 1 Next builder.Append( "End Sub" & vbCrLf) Next Dim source = <compilation> <file name="a.vb"> Class Module1 <%= New System.Xml.Linq.XCData(builder.ToString()) %> End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(True)) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, UnaryExpressionSyntax) Where node IsNot Nothing).ToArray() n = 0 For Each name In typeNames Dim type = compilation.GetTypeByMetadataName(name) For Each op In operators TestIntrinsicSymbol( op, type, compilation, semanticModel, nodes(n), nodes(n + 1), nodes(n + 2), nodes(n + 3)) n += 4 Next Next Assert.Equal(n, nodes.Length) End Sub Private Sub TestIntrinsicSymbol( op As UnaryOperatorKind, type As TypeSymbol, compilation As VisualBasicCompilation, semanticModel As SemanticModel, node1 As UnaryExpressionSyntax, node2 As UnaryExpressionSyntax, node3 As UnaryExpressionSyntax, node4 As UnaryExpressionSyntax ) Dim info1 As SymbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal(CandidateReason.None, info1.CandidateReason) Assert.Equal(0, info1.CandidateSymbols.Length) Dim symbol1 = DirectCast(info1.Symbol, MethodSymbol) Dim symbol2 = semanticModel.GetSymbolInfo(node2).Symbol Dim symbol3 = DirectCast(semanticModel.GetSymbolInfo(node3).Symbol, MethodSymbol) Dim symbol4 = semanticModel.GetSymbolInfo(node4).Symbol Assert.Equal(symbol1, symbol3) If symbol1 IsNot Nothing Then Assert.NotSame(symbol1, symbol3) Assert.Equal(symbol1.GetHashCode(), symbol3.GetHashCode()) Assert.Equal(symbol1.Parameters(0), symbol3.Parameters(0)) Assert.Equal(symbol1.Parameters(0).GetHashCode(), symbol3.Parameters(0).GetHashCode()) End If Assert.Equal(symbol2, symbol4) Dim special As SpecialType = type.GetEnumUnderlyingTypeOrSelf().SpecialType Dim resultType As SpecialType = OverloadResolution.ResolveNotLiftedIntrinsicUnaryOperator(op, special) If resultType = SpecialType.None Then Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If Assert.NotNull(symbol1) Dim containerName As String = compilation.GetSpecialType(resultType).ToTestDisplayString() Dim returnName As String = containerName If op = UnaryOperatorKind.Not AndAlso type.IsEnumType() Then containerName = type.ToTestDisplayString() returnName = containerName End If Assert.Equal(String.Format("Function {0}.{1}(value As {0}) As {2}", containerName, OverloadResolution.TryGetOperatorName(op), returnName), symbol1.ToTestDisplayString()) Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind) Assert.True(symbol1.IsImplicitlyDeclared) Assert.Equal(op = UnaryOperatorKind.Minus AndAlso symbol1.ContainingType.IsIntegralType(), symbol1.IsCheckedBuiltin) Assert.False(symbol1.IsGenericMethod) Assert.False(symbol1.IsExtensionMethod) Assert.False(symbol1.IsExternalMethod) Assert.False(symbol1.CanBeReferencedByName) Assert.Null(symbol1.DeclaringCompilation) Assert.Equal(symbol1.Name, symbol1.MetadataName) Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters(0).Type) Assert.Equal(0, symbol1.Locations.Length) Assert.Null(symbol1.GetDocumentationCommentId) Assert.Equal("", symbol1.GetDocumentationCommentXml) Assert.True(symbol1.HasSpecialName) Assert.True(symbol1.IsShared) Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility) Assert.False(symbol1.IsOverloads) Assert.False(symbol1.IsOverrides) Assert.False(symbol1.IsOverridable) Assert.False(symbol1.IsMustOverride) Assert.False(symbol1.IsNotOverridable) Assert.Equal(1, symbol1.ParameterCount) Assert.Equal(0, symbol1.Parameters(0).Ordinal) Dim otherSymbol = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.Equal(symbol1, otherSymbol) If type.IsValueType Then Assert.Equal(symbol1, symbol2) Return End If Assert.Null(symbol2) End Sub <Fact()> Public Sub CheckedIntrinsicSymbols() Dim source = <compilation> <file name="a.vb"> Class Module1 Sub Test(x as Integer) Dim z1 = -x End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(False)) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, UnaryExpressionSyntax) Where node IsNot Nothing).Single() Dim symbol1 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.False(symbol1.IsCheckedBuiltin) compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(True)) semanticModel = compilation.GetSemanticModel(tree) Dim symbol2 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.True(symbol2.IsCheckedBuiltin) Assert.NotEqual(symbol1, symbol2) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.IO Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.OverloadResolution Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class UnaryOperators Inherits BasicTestBase <Fact> <WorkItem(33564, "https://github.com/dotnet/roslyn/issues/33564")> Public Sub Test1() Dim source = <compilation name="UnaryOperator1"> <file name="a.vb"> Option Strict Off Module Module1 Sub Main() Dim Bo As Boolean Dim SB As SByte Dim By As Byte Dim Sh As Short Dim US As UShort Dim [In] As Integer Dim UI As UInteger Dim Lo As Long Dim UL As ULong Dim De As Decimal Dim Si As Single Dim [Do] As Double Dim St As String Dim Ob As Object Dim Tc As System.TypeCode Bo = False SB = -1 By = 2 Sh = -3 US = 4 [In] = -5 UI = 6 Lo = -7 UL = 8 De = -9D Si = 10 [Do] = -11 St = "12" Ob = -13 System.Console.WriteLine("Unary Minus") PrintResult(-Nothing) PrintResult(-Bo) PrintResult(-SB) PrintResult(-By) PrintResult(-Sh) PrintResult(-US) PrintResult(-[In]) PrintResult(-UI) PrintResult(-Lo) PrintResult(-UL) PrintResult(-De) PrintResult(-Si) PrintResult(-[Do]) PrintResult(-St) PrintResult(-Ob) PrintResult(-Tc) PrintResult(-True) PrintResult(-False) PrintResult(-System.SByte.MaxValue) PrintResult(-System.Byte.MaxValue) PrintResult(-14S) PrintResult(-15US) PrintResult(-16I) PrintResult(-17UI) PrintResult(-19L) PrintResult(-20UL) PrintResult(-System.Single.MaxValue) PrintResult(-22.0) PrintResult(-23D) PrintResult(-"24") System.Console.WriteLine("") System.Console.WriteLine("Unary Plus") PrintResult(+Nothing) PrintResult(+Bo) PrintResult(+SB) PrintResult(+By) PrintResult(+Sh) PrintResult(+US) PrintResult(+[In]) PrintResult(+UI) PrintResult(+Lo) PrintResult(+UL) PrintResult(+De) PrintResult(+Si) PrintResult(+[Do]) PrintResult(+St) PrintResult(+Ob) PrintResult(+Tc) PrintResult(+True) PrintResult(+False) PrintResult(+System.SByte.MaxValue) PrintResult(+System.Byte.MaxValue) PrintResult(+14S) PrintResult(+15US) PrintResult(+16I) PrintResult(+17UI) PrintResult(+19L) PrintResult(+20UL) PrintResult(+System.Single.MaxValue) PrintResult(+22.0) PrintResult(+23D) PrintResult(+"24") System.Console.WriteLine("") System.Console.WriteLine("Logical Not") PrintResult(Not Nothing) PrintResult(Not Bo) PrintResult(Not SB) PrintResult(Not By) PrintResult(Not Sh) PrintResult(Not US) PrintResult(Not [In]) PrintResult(Not UI) PrintResult(Not Lo) PrintResult(Not UL) PrintResult(Not De) PrintResult(Not Si) PrintResult(Not [Do]) PrintResult(Not St) PrintResult(Not Ob) PrintResult(Not Tc) PrintResult(Not True) PrintResult(Not False) PrintResult(Not System.SByte.MaxValue) PrintResult(Not System.Byte.MaxValue) PrintResult(Not 14S) PrintResult(Not 15US) PrintResult(Not 16I) PrintResult(Not 17UI) PrintResult(Not 19L) PrintResult(Not 20UL) PrintResult(Not 21.0F) PrintResult(Not 22.0) PrintResult(Not 23D) PrintResult(Not "24") End Sub Sub PrintResult(val As Boolean) System.Console.WriteLine("Boolean: {0}", val) End Sub Sub PrintResult(val As SByte) System.Console.WriteLine("SByte: {0}", val) End Sub Sub PrintResult(val As Byte) System.Console.WriteLine("Byte: {0}", val) End Sub Sub PrintResult(val As Short) System.Console.WriteLine("Short: {0}", val) End Sub Sub PrintResult(val As UShort) System.Console.WriteLine("UShort: {0}", val) End Sub Sub PrintResult(val As Integer) System.Console.WriteLine("Integer: {0}", val) End Sub Sub PrintResult(val As UInteger) System.Console.WriteLine("UInteger: {0}", val) End Sub Sub PrintResult(val As Long) System.Console.WriteLine("Long: {0}", val) End Sub Sub PrintResult(val As ULong) System.Console.WriteLine("ULong: {0}", val) End Sub Sub PrintResult(val As Decimal) System.Console.WriteLine("Decimal: {0}", val) End Sub Sub PrintResult(val As Single) System.Console.WriteLine("Single: {0}", val.ToString("G7", System.Globalization.CultureInfo.InvariantCulture)) End Sub Sub PrintResult(val As Double) System.Console.WriteLine("Double: {0}", val) End Sub 'Sub PrintResult(val As Date) ' System.Console.WriteLine("Date: {0}", val) 'End Sub Sub PrintResult(val As Char) System.Console.WriteLine("Char: {0}", val) End Sub Sub PrintResult(val As String) System.Console.WriteLine("String: ") System.Console.WriteLine(val) End Sub Sub PrintResult(val As Object) System.Console.WriteLine("Object: {0}", val) End Sub Sub PrintResult(val As System.TypeCode) System.Console.WriteLine("TypeCode: {0}", val) End Sub End Module </file> </compilation> Dim expected = <![CDATA[ Unary Minus Integer: 0 Short: 0 SByte: 1 Short: -2 Short: 3 Integer: -4 Integer: 5 Long: -6 Long: 7 Decimal: -8 Decimal: 9 Single: -10 Double: 11 Double: -12 Object: 13 Integer: 0 Short: 1 Short: 0 SByte: -127 Short: -255 Short: -14 Integer: -15 Integer: -16 Long: -17 Long: -19 Decimal: -20 Single: -3.402823E+38 Double: -22 Decimal: -23 Double: -24 Unary Plus Integer: 0 Short: 0 SByte: -1 Byte: 2 Short: -3 UShort: 4 Integer: -5 UInteger: 6 Long: -7 ULong: 8 Decimal: -9 Single: 10 Double: -11 Double: 12 Object: -13 Integer: 0 Short: -1 Short: 0 SByte: 127 Byte: 255 Short: 14 UShort: 15 Integer: 16 UInteger: 17 Long: 19 ULong: 20 Single: 3.402823E+38 Double: 22 Decimal: 23 Double: 24 Logical Not Integer: -1 Boolean: True SByte: 0 Byte: 253 Short: 2 UShort: 65531 Integer: 4 UInteger: 4294967289 Long: 6 ULong: 18446744073709551607 Long: 8 Long: -11 Long: 10 Long: -13 Object: 12 TypeCode: -1 Boolean: False Boolean: True SByte: -128 Byte: 0 Short: -15 UShort: 65520 Integer: -17 UInteger: 4294967278 Long: -20 ULong: 18446744073709551595 Long: -22 Long: -23 Long: -24 Long: -25 ]]> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe) Assert.True(c1.Options.CheckOverflow) CompileAndVerify(c1, expected) c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(c1.Options.CheckOverflow) CompileAndVerify(c1, expected) End Sub <Fact> Public Sub Test2() Dim compilationDef = <compilation name="Test2"> <file name="a.vb"> Option Strict On Module Module1 Sub Main() Dim Da As Date Dim Ch As Char Dim Ob As Object Dim result As Object result = -Da result = -Ch result = -Ob result = +Da result = +Ch result = +Ob result = Not Da result = Not Ch result = Not Ob result = --Da End Sub End Module </file> </compilation> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC30487: Operator '-' is not defined for type 'Date'. result = -Da ~~~ BC30487: Operator '-' is not defined for type 'Char'. result = -Ch ~~~ BC30038: Option Strict On prohibits operands of type Object for operator '-'. result = -Ob ~~ BC42104: Variable 'Ob' is used before it has been assigned a value. A null reference exception could result at runtime. result = -Ob ~~ BC30487: Operator '+' is not defined for type 'Date'. result = +Da ~~~ BC30487: Operator '+' is not defined for type 'Char'. result = +Ch ~~~ BC30038: Option Strict On prohibits operands of type Object for operator '+'. result = +Ob ~~ BC30487: Operator 'Not' is not defined for type 'Date'. result = Not Da ~~~~~~ BC30487: Operator 'Not' is not defined for type 'Char'. result = Not Ch ~~~~~~ BC30038: Option Strict On prohibits operands of type Object for operator 'Not'. result = Not Ob ~~ BC30487: Operator '-' is not defined for type 'Date'. result = --Da ~~~ </expected>) End Sub <Fact> Public Sub Test3() Dim c1 = VisualBasicCompilation.Create("Test3", syntaxTrees:={VisualBasicSyntaxTree.ParseText( <text> Option Strict Off Module Module1 Interface I1 End Interface Function Main() As I1 Dim result As Object result = -Nothing End Function End Module</text>.Value )}, references:=Nothing, options:=TestOptions.ReleaseDll) CompilationUtils.AssertTheseDiagnostics(c1, <expected> BC31091: Import of type 'Object' from assembly or module 'Test3.dll' failed. Module Module1 ~~~~~~~ BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute..ctor' is not defined. Module Module1 ~~~~~~~ BC30002: Type 'System.Object' is not defined. Dim result As Object ~~~~~~ BC30002: Type 'System.Int32' is not defined. result = -Nothing ~~~~~~~ BC42105: Function 'Main' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Test4() Dim source = <compilation name="UnaryOperator4"> <file name="a.vb"> Option Strict Off Imports System Module Module1 Sub Main() Dim Ob As Object Ob = -System.Byte.MinValue Ob = -System.Byte.MaxValue Ob = -System.SByte.MinValue Ob = -System.SByte.MaxValue Ob = -Int16.MinValue Ob = -Int16.MaxValue Ob = -UInt16.MaxValue Ob = -UInt16.MinValue Ob = -Int32.MinValue Ob = -Int32.MaxValue Ob = -UInt32.MaxValue Ob = -UInt32.MinValue Ob = -Int64.MinValue Ob = -Int64.MaxValue Ob = -UInt64.MaxValue Ob = -UInt64.MinValue Ob = -System.Decimal.MaxValue Ob = -System.Decimal.MinValue Ob = -System.Single.MaxValue Ob = -System.Single.MinValue Ob = -System.Double.MaxValue Ob = -System.Double.MinValue End Sub End Module </file> </compilation> Dim expected = <expected> BC30439: Constant expression not representable in type 'SByte'. Ob = -System.SByte.MinValue ~~~~~~~~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Short'. Ob = -Int16.MinValue ~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Integer'. Ob = -Int32.MinValue ~~~~~~~~~~~~~~~ BC30439: Constant expression not representable in type 'Long'. Ob = -Int64.MinValue ~~~~~~~~~~~~~~~ </expected> Dim c1 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source) Assert.True(c1.Options.CheckOverflow) CompilationUtils.AssertTheseDiagnostics(c1, expected) Dim c2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe.WithOverflowChecks(False)) Assert.False(c2.Options.CheckOverflow) CompilationUtils.AssertTheseDiagnostics(c2, expected) End Sub <Fact> Public Sub Test5() Dim compilationDef = <compilation name="UnaryOperator2"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim Ob As Object = Nothing Ob = -Ob Ob = +Ob Ob = Not Ob End Sub End Module </file> </compilation> Dim expected = <expected> BC42019: Operands of type Object used for operator '-'; runtime errors could occur. Ob = -Ob ~~ BC42019: Operands of type Object used for operator '+'; runtime errors could occur. Ob = +Ob ~~ BC42019: Operands of type Object used for operator 'Not'; runtime errors could occur. Ob = Not Ob ~~ </expected> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, expected) End Sub <WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")> <Fact()> Public Sub Bug13088() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Public Const Z1 As Integer = +2147483648 'BIND:"Public Const Z1 As Integer = +2147483648" Public Const Z2 As Integer = (-(-2147483648)) 'BIND1:"Public Const Z2 As Integer = (-(-2147483648))" Sub Main() End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "+2147483648").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "(-(-2147483648))").WithArguments("Integer")) Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z1").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z2").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) End Sub <Fact()> Public Sub IntrinsicSymbols() Dim operators() As UnaryOperatorKind = { UnaryOperatorKind.Plus, UnaryOperatorKind.Minus, UnaryOperatorKind.Not } Dim opTokens = (From op In operators Select SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(op))).ToArray() Dim typeNames() As String = { "System.Object", "System.String", "System.Double", "System.SByte", "System.Int16", "System.Int32", "System.Int64", "System.Decimal", "System.Single", "System.Byte", "System.UInt16", "System.UInt32", "System.UInt64", "System.Boolean", "System.Char", "System.DateTime", "System.TypeCode", "System.StringComparison", "System.Guid" } Dim builder As New System.Text.StringBuilder Dim n As Integer = 0 For Each arg1 In typeNames n += 1 builder.AppendFormat( "Sub Test{1}(x1 as {0}, x2 as {0}?)" & vbCrLf, arg1, n) Dim k As Integer = 0 For Each opToken In opTokens builder.AppendFormat( " Dim z{0}_1 = {1} x1" & vbCrLf & " Dim z{0}_2 = {1} x2" & vbCrLf & " If {1} x1" & vbCrLf & " End If" & vbCrLf & " If {1} x2" & vbCrLf & " End If" & vbCrLf, k, opToken) k += 1 Next builder.Append( "End Sub" & vbCrLf) Next Dim source = <compilation> <file name="a.vb"> Class Module1 <%= New System.Xml.Linq.XCData(builder.ToString()) %> End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(True)) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim nodes = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, UnaryExpressionSyntax) Where node IsNot Nothing).ToArray() n = 0 For Each name In typeNames Dim type = compilation.GetTypeByMetadataName(name) For Each op In operators TestIntrinsicSymbol( op, type, compilation, semanticModel, nodes(n), nodes(n + 1), nodes(n + 2), nodes(n + 3)) n += 4 Next Next Assert.Equal(n, nodes.Length) End Sub Private Sub TestIntrinsicSymbol( op As UnaryOperatorKind, type As TypeSymbol, compilation As VisualBasicCompilation, semanticModel As SemanticModel, node1 As UnaryExpressionSyntax, node2 As UnaryExpressionSyntax, node3 As UnaryExpressionSyntax, node4 As UnaryExpressionSyntax ) Dim info1 As SymbolInfo = semanticModel.GetSymbolInfo(node1) Assert.Equal(CandidateReason.None, info1.CandidateReason) Assert.Equal(0, info1.CandidateSymbols.Length) Dim symbol1 = DirectCast(info1.Symbol, MethodSymbol) Dim symbol2 = semanticModel.GetSymbolInfo(node2).Symbol Dim symbol3 = DirectCast(semanticModel.GetSymbolInfo(node3).Symbol, MethodSymbol) Dim symbol4 = semanticModel.GetSymbolInfo(node4).Symbol Assert.Equal(symbol1, symbol3) If symbol1 IsNot Nothing Then Assert.NotSame(symbol1, symbol3) Assert.Equal(symbol1.GetHashCode(), symbol3.GetHashCode()) Assert.Equal(symbol1.Parameters(0), symbol3.Parameters(0)) Assert.Equal(symbol1.Parameters(0).GetHashCode(), symbol3.Parameters(0).GetHashCode()) End If Assert.Equal(symbol2, symbol4) Dim special As SpecialType = type.GetEnumUnderlyingTypeOrSelf().SpecialType Dim resultType As SpecialType = OverloadResolution.ResolveNotLiftedIntrinsicUnaryOperator(op, special) If resultType = SpecialType.None Then Assert.Null(symbol1) Assert.Null(symbol2) Assert.Null(symbol3) Assert.Null(symbol4) Return End If Assert.NotNull(symbol1) Dim containerName As String = compilation.GetSpecialType(resultType).ToTestDisplayString() Dim returnName As String = containerName If op = UnaryOperatorKind.Not AndAlso type.IsEnumType() Then containerName = type.ToTestDisplayString() returnName = containerName End If Assert.Equal(String.Format("Function {0}.{1}(value As {0}) As {2}", containerName, OverloadResolution.TryGetOperatorName(op), returnName), symbol1.ToTestDisplayString()) Assert.Equal(MethodKind.BuiltinOperator, symbol1.MethodKind) Assert.True(symbol1.IsImplicitlyDeclared) Assert.Equal(op = UnaryOperatorKind.Minus AndAlso symbol1.ContainingType.IsIntegralType(), symbol1.IsCheckedBuiltin) Assert.False(symbol1.IsGenericMethod) Assert.False(symbol1.IsExtensionMethod) Assert.False(symbol1.IsExternalMethod) Assert.False(symbol1.CanBeReferencedByName) Assert.Null(symbol1.DeclaringCompilation) Assert.Equal(symbol1.Name, symbol1.MetadataName) Assert.Same(symbol1.ContainingSymbol, symbol1.Parameters(0).Type) Assert.Equal(0, symbol1.Locations.Length) Assert.Null(symbol1.GetDocumentationCommentId) Assert.Equal("", symbol1.GetDocumentationCommentXml) Assert.True(symbol1.HasSpecialName) Assert.True(symbol1.IsShared) Assert.Equal(Accessibility.Public, symbol1.DeclaredAccessibility) Assert.False(symbol1.IsOverloads) Assert.False(symbol1.IsOverrides) Assert.False(symbol1.IsOverridable) Assert.False(symbol1.IsMustOverride) Assert.False(symbol1.IsNotOverridable) Assert.Equal(1, symbol1.ParameterCount) Assert.Equal(0, symbol1.Parameters(0).Ordinal) Dim otherSymbol = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.Equal(symbol1, otherSymbol) If type.IsValueType Then Assert.Equal(symbol1, symbol2) Return End If Assert.Null(symbol2) End Sub <Fact()> Public Sub CheckedIntrinsicSymbols() Dim source = <compilation> <file name="a.vb"> Class Module1 Sub Test(x as Integer) Dim z1 = -x End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll.WithOverflowChecks(False)) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) Dim node1 = (From node In tree.GetRoot().DescendantNodes() Select node = TryCast(node, UnaryExpressionSyntax) Where node IsNot Nothing).Single() Dim symbol1 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.False(symbol1.IsCheckedBuiltin) compilation = compilation.WithOptions(TestOptions.ReleaseDll.WithOverflowChecks(True)) semanticModel = compilation.GetSemanticModel(tree) Dim symbol2 = DirectCast(semanticModel.GetSymbolInfo(node1).Symbol, MethodSymbol) Assert.True(symbol2.IsCheckedBuiltin) Assert.NotEqual(symbol1, symbol2) End Sub End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_ISwitchExpression.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ISwitchExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NonExhaustive() { //null case is not handled -> not exhaustive string source = @" namespace Tests { public class Prog { static int EvalPoint((int, int)? point) => /*<bind>*/point switch { (0, int t) => t > 2 ? 3 : 4, var (_, _) => 2 }/*</bind>*/; static void Main() { EvalPoint(null); } } } "; string expectedOperationTree = @"ISwitchExpressionOperation (2 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'point switc ... }') Value: IParameterReferenceOperation: point (OperationKind.ParameterReference, Type: (System.Int32, System.Int32)?) (Syntax: 'point') Arms(2): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '(0, int t) ... > 2 ? 3 : 4') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(0, int t)') (InputType: (System.Int32, System.Int32)?, NarrowedType: (System.Int32, System.Int32), DeclaredSymbol: null, MatchedType: (System.Int32, System.Int32), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '0') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int t') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 t, MatchesNull: False) PropertySubpatterns (0) Value: IConditionalOperation (OperationKind.Conditional, Type: System.Int32) (Syntax: 't > 2 ? 3 : 4') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 't > 2') Left: ILocalReferenceOperation: t (OperationKind.LocalReference, Type: System.Int32) (Syntax: 't') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Locals: Local_1: System.Int32 t ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'var (_, _) => 2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(_, _)') (InputType: (System.Int32, System.Int32)?, NarrowedType: (System.Int32, System.Int32), DeclaredSymbol: null, MatchedType: (System.Int32, System.Int32), DeconstructSymbol: null) DeconstructionSubpatterns (2): IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) PropertySubpatterns (0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_Basic() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, 3 => 4, _ => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (3 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... 4, _ => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(3): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '3 => 4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '3') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NoArms() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (0 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Object) (Syntax: 'x switch { }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(0) "; var expectedDiagnostics = new[] { // file.cs(7,25): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // y = /*<bind>*/x switch { }/*</bind>*/; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(7, 25) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_MissingPattern() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '=> 5') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,34): error CS8504: Pattern missing // y = /*<bind>*/x switch { => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(7, 34) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadInput_01() { string source = @" using System; class X { void M(object y) { y = /*<bind>*/x switch { 1 => 2, 3 => 4, _ => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (3 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... 4, _ => 5 }') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x') Children(0) Arms(3): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: ?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '3 => 4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '3') (InputType: ?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: ?, NarrowedType: ?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,23): error CS0103: The name 'x' does not exist in the current context // y = /*<bind>*/x switch { 1 => 2, 3 => 4, _ => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(7, 23) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NoCommonType_01() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, _ => ""Z"" }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Object) (Syntax: 'x switch { ... _ => ""Z"" }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => ""Z""') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '""Z""') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Z"") (Syntax: '""Z""') "; var expectedDiagnostics = new DiagnosticDescription[] { }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NoCommonType_02() { string source = @" using System; class X { void M(int? x, object y) { var z = /*<bind>*/x switch { 1 => 2, _ => ""Z"" }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: 'x switch { ... _ => ""Z"" }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => ""Z""') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '""Z""') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Z"") (Syntax: '""Z""') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,29): error CS8506: No best type was found for the switch expression. // var z = /*<bind>*/x switch { 1 => 2, _ => "Z" }/*</bind>*/; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 29) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_MissingArrow() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ /*=>*/ 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { _ /*=>*/ 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ /*=>*/ 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,43): error CS1003: Syntax error, '=>' expected // y = /*<bind>*/x switch { _ /*=>*/ 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, "5").WithArguments("=>", "").WithLocation(7, 43) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_MissingExpression() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ => /*5*/ }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: 'x switch { _ => /*5*/ }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => /*5*/ ') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new[] { // file.cs(7,45): error CS1525: Invalid expression term '}' // y = /*<bind>*/x switch { _ => /*5*/ }/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(7, 45) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadPattern() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { NotFound => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... ound => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'NotFound => 5') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: 'NotFound') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'NotFound') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,34): error CS0103: The name 'NotFound' does not exist in the current context // y = /*<bind>*/x switch { NotFound => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 34) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadArmExpression() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ => NotFound }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: 'x switch { ... NotFound }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => NotFound') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) "; var expectedDiagnostics = new[] { // file.cs(7,39): error CS0103: The name 'NotFound' does not exist in the current context // y = /*<bind>*/x switch { _ => NotFound }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 39) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_SubsumedArm() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ => 5, 1 => 2 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... 5, 1 => 2 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new[] { // file.cs(7,42): error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. // y = /*<bind>*/x switch { _ => 5, 1 => 2 }/*</bind>*/; Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, "1").WithLocation(7, 42) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BasicGuard() { string source = @" using System; class X { void M(int? x, bool b, object y) { y = /*<bind>*/x switch { 1 when b => 2, _ => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... 2, _ => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 when b => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Guard: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_FalseGuard() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, _ when false => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... alse => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ when false => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Guard: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,25): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered. However, a pattern with a 'when' clause might successfully match this value. // y = /*<bind>*/x switch { 1 => 2, _ when false => 5 }/*</bind>*/; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("0").WithLocation(7, 25) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_TrueGuard() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, _ when true => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... true => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ when true => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Guard: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadGuard() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ when NotFound => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... ound => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ when NotFound => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Guard: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'NotFound') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,41): error CS0103: The name 'NotFound' does not exist in the current context // y = /*<bind>*/x switch { _ when NotFound => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 41) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_LocalsClash() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { int z when x is int z => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... nt z => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (2 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z when ... int z => 5') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int z') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Guard: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x is int z') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is int z') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Locals: Local_1: System.Int32 z Local_2: System.Int32 z "; var expectedDiagnostics = new[] { // file.cs(7,54): error CS0128: A local variable or function named 'z' is already defined in this scope // y = /*<bind>*/x switch { int z when x is int z => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(7, 54) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void TargetTypedSwitchExpression_ImplicitCast() { var source = @" using System; bool b = true; /*<bind>*/Action<string> a = b switch { true => arg => {}, false => arg => {} };/*</bind>*/"; var expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action<stri ... rg => {} };') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action<stri ... arg => {} }') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.String> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = b switc ... arg => {} }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= b switch ... arg => {} }') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.String>, IsImplicit) (Syntax: 'b switch { ... arg => {} }') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Action<System.String>) (Syntax: 'b switch { ... arg => {} }') Value: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'true => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'true') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'false => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'false') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void TargetTypedSwitchExpression_ExplicitCast() { var source = @" using System; bool b = true; /*<bind>*/var a = (Action<string>)(b switch { true => arg => {}, false => arg => {} });/*</bind>*/"; var expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var a = (Ac ... g => {} });') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = (Ac ... rg => {} })') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.String> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = (Action ... rg => {} })') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (Action<s ... rg => {} })') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.String>) (Syntax: '(Action<str ... rg => {} })') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Action<System.String>) (Syntax: 'b switch { ... arg => {} }') Value: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'true => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'true') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'false => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'false') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchExpression_BasicFlow() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ result = input switch { 1 => false, _ => true }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '_ => true') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Leaving: {R2} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R2} } Block[B6] - Block Predecessors: [B4] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B7] - Block Predecessors: [B3] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundGuard() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, int input, bool a, bool b) /*<bind>*/{ result = input switch { 1 when a && b => false }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 when a && b => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Leaving: {R2} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} } Block[B6] - Block Predecessors: [B2] [B3] [B4] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B7] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundInput() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, bool a, int input1, int input2) /*<bind>*/{ result = (a ? input1 : input2) switch { 1 => false }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? input1 : input2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B8] Leaving: {R2} } Block[B7] - Block Predecessors: [B5] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: '(a ? input1 ... }') Arguments(0) Initializer: null Block[B8] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (a ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = (a ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '(a ? input1 ... }') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_BadInput_02() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result) /*<bind>*/{ result = NotFound switch { 1 => false }; }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(7,18): error CS0103: The name 'NotFound' does not exist in the current context // result = NotFound switch Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'NotFound') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'NotFound') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: ?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: 'NotFound sw ... }') Arguments(0) Initializer: null Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = No ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = No ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'NotFound sw ... }') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundConsequence() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, bool a, int input, bool input1, bool input2) /*<bind>*/{ result = input switch { 1 => (a ? input1 : input2) }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => (a ? i ... 1 : input2)') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B7] Leaving: {R2} Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B7] Leaving: {R2} } Block[B6] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B7] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundPattern() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, bool a, int input, int input1, int input2) /*<bind>*/{ result = input switch { (a ? input1 : input2) => true }; }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(9,18): error CS0150: A constant value is expected // (a ? input1 : input2) => true Diagnostic(ErrorCode.ERR_ConstantExpected, "a ? input1 : input2").WithLocation(9, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B3] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input1') Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input2') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Jump if False (Regular) to Block[B8] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: '(a ? input1 ... t2) => true') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '(a ? input1 : input2)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? input1 : input2') Leaving: {R3} {R2} Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B9] Leaving: {R2} } Block[B8] - Block Predecessors: [B6] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B9] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B10] Leaving: {R1} } Block[B10] - Exit Predecessors: [B9] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchExpression_Combinators() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { bool M(char input) /*<bind>*/{ return input switch { >= 'A' and <= 'Z' or >= 'a' and <= 'z' => true, '_' => false, not (>= '0' and <= '9') => true, _ => false, }; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [0] .locals {R2} { CaptureIds: [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '>= 'A' and ... 'z' => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and ... and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R2} Block[B3] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: ''_' => false') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: ''_'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: _) (Syntax: ''_'') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B10] Leaving: {R2} Block[B5] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'not (>= '0' ... 9') => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: INegatedPatternOperation (OperationKind.NegatedPattern, Type: null) (Syntax: 'not (>= '0' and <= '9')') (InputType: System.Char, NarrowedType: System.Char) Pattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= '0' and <= '9'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= '0'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: 0) (Syntax: ''0'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= '9'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: 9) (Syntax: ''9'') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R2} Block[B7] - Block Predecessors: [B5] Statements (0) Jump if False (Regular) to Block[B9] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '_ => false') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Char, NarrowedType: System.Char) Leaving: {R2} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B10] Leaving: {R2} } Block[B9] - Block Predecessors: [B7] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B10] - Block Predecessors: [B2] [B4] [B6] [B8] Statements (0) Next (Return) Block[B11] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Leaving: {R1} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class IOperationTests_ISwitchExpression : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NonExhaustive() { //null case is not handled -> not exhaustive string source = @" namespace Tests { public class Prog { static int EvalPoint((int, int)? point) => /*<bind>*/point switch { (0, int t) => t > 2 ? 3 : 4, var (_, _) => 2 }/*</bind>*/; static void Main() { EvalPoint(null); } } } "; string expectedOperationTree = @"ISwitchExpressionOperation (2 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'point switc ... }') Value: IParameterReferenceOperation: point (OperationKind.ParameterReference, Type: (System.Int32, System.Int32)?) (Syntax: 'point') Arms(2): ISwitchExpressionArmOperation (1 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '(0, int t) ... > 2 ? 3 : 4') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(0, int t)') (InputType: (System.Int32, System.Int32)?, NarrowedType: (System.Int32, System.Int32), DeclaredSymbol: null, MatchedType: (System.Int32, System.Int32), DeconstructSymbol: null) DeconstructionSubpatterns (2): IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '0') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int t') (InputType: System.Int32, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 t, MatchesNull: False) PropertySubpatterns (0) Value: IConditionalOperation (OperationKind.Conditional, Type: System.Int32) (Syntax: 't > 2 ? 3 : 4') Condition: IBinaryOperation (BinaryOperatorKind.GreaterThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 't > 2') Left: ILocalReferenceOperation: t (OperationKind.LocalReference, Type: System.Int32) (Syntax: 't') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') WhenTrue: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') WhenFalse: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') Locals: Local_1: System.Int32 t ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'var (_, _) => 2') Pattern: IRecursivePatternOperation (OperationKind.RecursivePattern, Type: null) (Syntax: '(_, _)') (InputType: (System.Int32, System.Int32)?, NarrowedType: (System.Int32, System.Int32), DeclaredSymbol: null, MatchedType: (System.Int32, System.Int32), DeconstructSymbol: null) DeconstructionSubpatterns (2): IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) PropertySubpatterns (0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_Basic() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, 3 => 4, _ => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (3 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... 4, _ => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(3): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '3 => 4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '3') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NoArms() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (0 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Object) (Syntax: 'x switch { }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(0) "; var expectedDiagnostics = new[] { // file.cs(7,25): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered. // y = /*<bind>*/x switch { }/*</bind>*/; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(7, 25) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_MissingPattern() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '=> 5') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,34): error CS8504: Pattern missing // y = /*<bind>*/x switch { => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_MissingPattern, "=>").WithLocation(7, 34) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadInput_01() { string source = @" using System; class X { void M(object y) { y = /*<bind>*/x switch { 1 => 2, 3 => 4, _ => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (3 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... 4, _ => 5 }') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x') Children(0) Arms(3): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: ?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '3 => 4') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '3') (InputType: ?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: ?, NarrowedType: ?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,23): error CS0103: The name 'x' does not exist in the current context // y = /*<bind>*/x switch { 1 => 2, 3 => 4, _ => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(7, 23) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NoCommonType_01() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, _ => ""Z"" }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Object) (Syntax: 'x switch { ... _ => ""Z"" }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => ""Z""') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: '""Z""') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Z"") (Syntax: '""Z""') "; var expectedDiagnostics = new DiagnosticDescription[] { }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_NoCommonType_02() { string source = @" using System; class X { void M(int? x, object y) { var z = /*<bind>*/x switch { 1 => 2, _ => ""Z"" }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: 'x switch { ... _ => ""Z"" }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '2') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => ""Z""') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ?, IsImplicit) (Syntax: '""Z""') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Z"") (Syntax: '""Z""') "; var expectedDiagnostics = new DiagnosticDescription[] { // file.cs(7,29): error CS8506: No best type was found for the switch expression. // var z = /*<bind>*/x switch { 1 => 2, _ => "Z" }/*</bind>*/; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 29) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_MissingArrow() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ /*=>*/ 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { _ /*=>*/ 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ /*=>*/ 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,43): error CS1003: Syntax error, '=>' expected // y = /*<bind>*/x switch { _ /*=>*/ 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_SyntaxError, "5").WithArguments("=>", "").WithLocation(7, 43) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_MissingExpression() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ => /*5*/ }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: 'x switch { _ => /*5*/ }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => /*5*/ ') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '') Children(0) "; var expectedDiagnostics = new[] { // file.cs(7,45): error CS1525: Invalid expression term '}' // y = /*<bind>*/x switch { _ => /*5*/ }/*</bind>*/; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(7, 45) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadPattern() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { NotFound => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... ound => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'NotFound => 5') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: 'NotFound') (InputType: System.Int32?, NarrowedType: System.Int32) Value: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'NotFound') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,34): error CS0103: The name 'NotFound' does not exist in the current context // y = /*<bind>*/x switch { NotFound => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 34) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadArmExpression() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ => NotFound }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: ?, IsInvalid) (Syntax: 'x switch { ... NotFound }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ => NotFound') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) "; var expectedDiagnostics = new[] { // file.cs(7,39): error CS0103: The name 'NotFound' does not exist in the current context // y = /*<bind>*/x switch { _ => NotFound }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 39) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_SubsumedArm() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ => 5, 1 => 2 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... 5, 1 => 2 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') "; var expectedDiagnostics = new[] { // file.cs(7,42): error CS8510: The pattern is unreachable. It has already been handled by a previous arm of the switch expression or it is impossible to match. // y = /*<bind>*/x switch { _ => 5, 1 => 2 }/*</bind>*/; Diagnostic(ErrorCode.ERR_SwitchArmSubsumed, "1").WithLocation(7, 42) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BasicGuard() { string source = @" using System; class X { void M(int? x, bool b, object y) { y = /*<bind>*/x switch { 1 when b => 2, _ => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... 2, _ => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 when b => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Guard: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_FalseGuard() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, _ when false => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... alse => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ when false => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Guard: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,25): warning CS8846: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '0' is not covered. However, a pattern with a 'when' clause might successfully match this value. // y = /*<bind>*/x switch { 1 => 2, _ when false => 5 }/*</bind>*/; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveWithWhen, "switch").WithArguments("0").WithLocation(7, 25) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_TrueGuard() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { 1 => 2, _ when true => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Int32) (Syntax: 'x switch { ... true => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '1 => 2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: '_ when true => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Guard: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_BadGuard() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { _ when NotFound => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... ound => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: '_ when NotFound => 5') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32?, NarrowedType: System.Int32?) Guard: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'NotFound') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') "; var expectedDiagnostics = new[] { // file.cs(7,41): error CS0103: The name 'NotFound' does not exist in the current context // y = /*<bind>*/x switch { _ when NotFound => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 41) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Patterns)] [Fact] public void SwitchExpression_LocalsClash() { string source = @" using System; class X { void M(int? x, object y) { y = /*<bind>*/x switch { int z when x is int z => 5 }/*</bind>*/; } } "; string expectedOperationTree = @" ISwitchExpressionOperation (1 arms, IsExhaustive: False) (OperationKind.SwitchExpression, Type: System.Int32, IsInvalid) (Syntax: 'x switch { ... nt z => 5 }') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Arms(1): ISwitchExpressionArmOperation (2 locals) (OperationKind.SwitchExpressionArm, Type: null, IsInvalid) (Syntax: 'int z when ... int z => 5') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null) (Syntax: 'int z') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Guard: IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'x is int z') Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: 'x is int z') Value: IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'x') Pattern: IDeclarationPatternOperation (OperationKind.DeclarationPattern, Type: null, IsInvalid) (Syntax: 'int z') (InputType: System.Int32?, NarrowedType: System.Int32, DeclaredSymbol: System.Int32 z, MatchesNull: False) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') Locals: Local_1: System.Int32 z Local_2: System.Int32 z "; var expectedDiagnostics = new[] { // file.cs(7,54): error CS0128: A local variable or function named 'z' is already defined in this scope // y = /*<bind>*/x switch { int z when x is int z => 5 }/*</bind>*/; Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(7, 54) }; VerifyOperationTreeAndDiagnosticsForTest<SwitchExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void TargetTypedSwitchExpression_ImplicitCast() { var source = @" using System; bool b = true; /*<bind>*/Action<string> a = b switch { true => arg => {}, false => arg => {} };/*</bind>*/"; var expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'Action<stri ... rg => {} };') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'Action<stri ... arg => {} }') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.String> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = b switc ... arg => {} }') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= b switch ... arg => {} }') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.String>, IsImplicit) (Syntax: 'b switch { ... arg => {} }') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Action<System.String>) (Syntax: 'b switch { ... arg => {} }') Value: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'true => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'true') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'false => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'false') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [Fact] public void TargetTypedSwitchExpression_ExplicitCast() { var source = @" using System; bool b = true; /*<bind>*/var a = (Action<string>)(b switch { true => arg => {}, false => arg => {} });/*</bind>*/"; var expectedOperationTree = @" IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'var a = (Ac ... g => {} });') IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'var a = (Ac ... rg => {} })') Declarators: IVariableDeclaratorOperation (Symbol: System.Action<System.String> a) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'a = (Action ... rg => {} })') Initializer: IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (Action<s ... rg => {} })') IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Action<System.String>) (Syntax: '(Action<str ... rg => {} })') Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Operand: ISwitchExpressionOperation (2 arms, IsExhaustive: True) (OperationKind.SwitchExpression, Type: System.Action<System.String>) (Syntax: 'b switch { ... arg => {} }') Value: ILocalReferenceOperation: b (OperationKind.LocalReference, Type: System.Boolean) (Syntax: 'b') Arms(2): ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'true => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'true') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null ISwitchExpressionArmOperation (0 locals) (OperationKind.SwitchExpressionArm, Type: null) (Syntax: 'false => arg => {}') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: 'false') (InputType: System.Boolean, NarrowedType: System.Boolean) Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Value: IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Action<System.String>, IsImplicit) (Syntax: 'arg => {}') Target: IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'arg => {}') IBlockOperation (1 statements) (OperationKind.Block, Type: null) (Syntax: '{}') IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '{}') ReturnedValue: null Initializer: null "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchExpression_BasicFlow() { string source = @" public sealed class MyClass { void M(bool result, int input) /*<bind>*/{ result = input switch { 1 => false, _ => true }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} Block[B4] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '_ => true') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Int32, NarrowedType: System.Int32) Leaving: {R2} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B7] Leaving: {R2} } Block[B6] - Block Predecessors: [B4] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B7] - Block Predecessors: [B3] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundGuard() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, int input, bool a, bool b) /*<bind>*/{ result = input switch { 1 when a && b => false }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 when a && b => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Leaving: {R2} Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B6] IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Leaving: {R2} Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B4] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B7] Leaving: {R2} } Block[B6] - Block Predecessors: [B2] [B3] [B4] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B7] - Block Predecessors: [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundInput() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, bool a, int input1, int input2) /*<bind>*/{ result = (a ? input1 : input2) switch { 1 => false }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B4] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input1') Next (Regular) Block[B5] Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? input1 : input2') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B8] Leaving: {R2} } Block[B7] - Block Predecessors: [B5] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: '(a ? input1 ... }') Arguments(0) Initializer: null Block[B8] - Block Predecessors: [B6] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = (a ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = (a ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: '(a ? input1 ... }') Next (Regular) Block[B9] Leaving: {R1} } Block[B9] - Exit Predecessors: [B8] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_BadInput_02() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result) /*<bind>*/{ result = NotFound switch { 1 => false }; }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(7,18): error CS0103: The name 'NotFound' does not exist in the current context // result = NotFound switch Diagnostic(ErrorCode.ERR_NameNotInContext, "NotFound").WithArguments("NotFound").WithLocation(7, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'NotFound') Value: IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'NotFound') Children(0) Jump if False (Regular) to Block[B4] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => false') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'NotFound') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: ?, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: 'NotFound sw ... }') Arguments(0) Initializer: null Block[B5] - Block Predecessors: [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = No ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = No ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'NotFound sw ... }') Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundConsequence() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, bool a, int input, bool input1, bool input2) /*<bind>*/{ result = input switch { 1 => (a ? input1 : input2) }; }/*</bind>*/ } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Jump if False (Regular) to Block[B6] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '1 => (a ? i ... 1 : input2)') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: '1') (InputType: System.Int32, NarrowedType: System.Int32) Value: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input1') Next (Regular) Block[B7] Leaving: {R2} Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'input2') Next (Regular) Block[B7] Leaving: {R2} } Block[B6] - Block Predecessors: [B2] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B7] - Block Predecessors: [B4] [B5] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B8] Leaving: {R1} } Block[B8] - Exit Predecessors: [B7] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact, WorkItem(32216, "https://github.com/dotnet/roslyn/issues/32216")] public void SwitchExpression_CompoundPattern() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { void M(bool result, bool a, int input, int input1, int input2) /*<bind>*/{ result = input switch { (a ? input1 : input2) => true }; }/*</bind>*/ } "; var expectedDiagnostics = new[] { // file.cs(9,18): error CS0150: A constant value is expected // (a ? input1 : input2) => true Diagnostic(ErrorCode.ERR_ConstantExpected, "a ? input1 : input2").WithLocation(9, 18) }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'result') Value: IParameterReferenceOperation: result (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'result') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'input') Next (Regular) Block[B3] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B3] - Block Predecessors: [B2] Statements (0) Jump if False (Regular) to Block[B5] IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input1') Value: IParameterReferenceOperation: input1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input1') Next (Regular) Block[B6] Block[B5] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'input2') Value: IParameterReferenceOperation: input2 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'input2') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B4] [B5] Statements (0) Jump if False (Regular) to Block[B8] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean, IsInvalid) (Syntax: '(a ? input1 ... t2) => true') Value: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null, IsInvalid) (Syntax: '(a ? input1 : input2)') (InputType: System.Int32, NarrowedType: System.Int32) Value: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? input1 : input2') Leaving: {R3} {R2} Next (Regular) Block[B7] Leaving: {R3} } Block[B7] - Block Predecessors: [B6] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B9] Leaving: {R2} } Block[B8] - Block Predecessors: [B6] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsInvalid, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B9] - Block Predecessors: [B7] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'result = in ... };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean, IsInvalid) (Syntax: 'result = in ... }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'result') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'input switc ... }') Next (Regular) Block[B10] Leaving: {R1} } Block[B10] - Exit Predecessors: [B9] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void SwitchExpression_Combinators() { string source = @" #pragma warning disable CS8509 public sealed class MyClass { bool M(char input) /*<bind>*/{ return input switch { >= 'A' and <= 'Z' or >= 'a' and <= 'z' => true, '_' => false, not (>= '0' and <= '9') => true, _ => false, }; }/*</bind>*/ } "; var expectedDiagnostics = new DiagnosticDescription[] { }; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} {R2} .locals {R1} { CaptureIds: [0] .locals {R2} { CaptureIds: [1] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'input') Value: IParameterReferenceOperation: input (OperationKind.ParameterReference, Type: System.Char) (Syntax: 'input') Jump if False (Regular) to Block[B3] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '>= 'A' and ... 'z' => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IBinaryPatternOperation (BinaryOperatorKind.Or) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and ... and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'A' and <= 'Z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'A'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: A) (Syntax: ''A'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'Z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: Z) (Syntax: ''Z'') RightPattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= 'a' and <= 'z'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= 'a'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: a) (Syntax: ''a'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= 'z'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: z) (Syntax: ''z'') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R2} Block[B3] - Block Predecessors: [B1] Statements (0) Jump if False (Regular) to Block[B5] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: ''_' => false') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IConstantPatternOperation (OperationKind.ConstantPattern, Type: null) (Syntax: ''_'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: _) (Syntax: ''_'') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B3] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B10] Leaving: {R2} Block[B5] - Block Predecessors: [B3] Statements (0) Jump if False (Regular) to Block[B7] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: 'not (>= '0' ... 9') => true') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: INegatedPatternOperation (OperationKind.NegatedPattern, Type: null) (Syntax: 'not (>= '0' and <= '9')') (InputType: System.Char, NarrowedType: System.Char) Pattern: IBinaryPatternOperation (BinaryOperatorKind.And) (OperationKind.BinaryPattern, Type: null) (Syntax: '>= '0' and <= '9'') (InputType: System.Char, NarrowedType: System.Char) LeftPattern: IRelationalPatternOperation (BinaryOperatorKind.GreaterThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '>= '0'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: 0) (Syntax: ''0'') RightPattern: IRelationalPatternOperation (BinaryOperatorKind.LessThanOrEqual) (OperationKind.RelationalPattern, Type: null) (Syntax: '<= '9'') (InputType: System.Char, NarrowedType: System.Char) Value: ILiteralOperation (OperationKind.Literal, Type: System.Char, Constant: 9) (Syntax: ''9'') Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'true') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true') Next (Regular) Block[B10] Leaving: {R2} Block[B7] - Block Predecessors: [B5] Statements (0) Jump if False (Regular) to Block[B9] IIsPatternOperation (OperationKind.IsPattern, Type: System.Boolean) (Syntax: '_ => false') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Char, IsImplicit) (Syntax: 'input') Pattern: IDiscardPatternOperation (OperationKind.DiscardPattern, Type: null) (Syntax: '_') (InputType: System.Char, NarrowedType: System.Char) Leaving: {R2} Next (Regular) Block[B8] Block[B8] - Block Predecessors: [B7] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'false') Value: ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: False) (Syntax: 'false') Next (Regular) Block[B10] Leaving: {R2} } Block[B9] - Block Predecessors: [B7] Statements (0) Next (Throw) Block[null] IObjectCreationOperation (Constructor: System.InvalidOperationException..ctor()) (OperationKind.ObjectCreation, Type: System.InvalidOperationException, IsImplicit) (Syntax: 'input switc ... }') Arguments(0) Initializer: null Block[B10] - Block Predecessors: [B2] [B4] [B6] [B8] Statements (0) Next (Return) Block[B11] IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'input switc ... }') Leaving: {R1} } Block[B11] - Exit Predecessors: [B10] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularWithPatternCombinators); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/CSharp/Portable/Symbols/Synthesized/RefKindVector.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal struct RefKindVector : IEquatable<RefKindVector> { private BitVector _bits; internal static RefKindVector Create(int capacity) { return new RefKindVector(capacity); } private RefKindVector(int capacity) { _bits = BitVector.Create(capacity * 2); } private RefKindVector(BitVector bits) { _bits = bits; } internal bool IsNull => _bits.IsNull; internal int Capacity => _bits.Capacity / 2; internal IEnumerable<ulong> Words() => _bits.Words(); internal RefKind this[int index] { get { index *= 2; return (_bits[index + 1], _bits[index]) switch { (false, false) => RefKind.None, (false, true) => RefKind.Ref, (true, false) => RefKind.Out, (true, true) => RefKind.RefReadOnly, }; } set { index *= 2; (_bits[index + 1], _bits[index]) = value switch { RefKind.None => (false, false), RefKind.Ref => (false, true), RefKind.Out => (true, false), RefKind.RefReadOnly => (true, true), _ => throw ExceptionUtilities.UnexpectedValue(value) }; } } public bool Equals(RefKindVector other) { return _bits.Equals(other._bits); } public override bool Equals(object? obj) { return obj is RefKindVector other && this.Equals(other); } public override int GetHashCode() { return _bits.GetHashCode(); } public string ToRefKindString() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append("{"); int i = 0; foreach (var word in this.Words()) { if (i > 0) { builder.Append(","); } builder.AppendFormat("{0:x8}", word); i++; } builder.Append("}"); Debug.Assert(i > 0); return pooledBuilder.ToStringAndFree(); } public static bool TryParse(string refKindString, int capacity, out RefKindVector result) { ulong? firstWord = null; ArrayBuilder<ulong>? otherWords = null; foreach (var word in refKindString.Split(',')) { ulong value; try { value = Convert.ToUInt64(word, 16); } catch (Exception) { result = default; return false; } if (firstWord is null) { firstWord = value; } else { otherWords ??= ArrayBuilder<ulong>.GetInstance(); otherWords.Add(value); } } Debug.Assert(firstWord is not null); var bitVector = BitVector.FromWords(firstWord.Value, otherWords?.ToArrayAndFree() ?? Array.Empty<ulong>(), capacity * 2); result = new RefKindVector(bitVector); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal struct RefKindVector : IEquatable<RefKindVector> { private BitVector _bits; internal static RefKindVector Create(int capacity) { return new RefKindVector(capacity); } private RefKindVector(int capacity) { _bits = BitVector.Create(capacity * 2); } private RefKindVector(BitVector bits) { _bits = bits; } internal bool IsNull => _bits.IsNull; internal int Capacity => _bits.Capacity / 2; internal IEnumerable<ulong> Words() => _bits.Words(); internal RefKind this[int index] { get { index *= 2; return (_bits[index + 1], _bits[index]) switch { (false, false) => RefKind.None, (false, true) => RefKind.Ref, (true, false) => RefKind.Out, (true, true) => RefKind.RefReadOnly, }; } set { index *= 2; (_bits[index + 1], _bits[index]) = value switch { RefKind.None => (false, false), RefKind.Ref => (false, true), RefKind.Out => (true, false), RefKind.RefReadOnly => (true, true), _ => throw ExceptionUtilities.UnexpectedValue(value) }; } } public bool Equals(RefKindVector other) { return _bits.Equals(other._bits); } public override bool Equals(object? obj) { return obj is RefKindVector other && this.Equals(other); } public override int GetHashCode() { return _bits.GetHashCode(); } public string ToRefKindString() { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; builder.Append("{"); int i = 0; foreach (var word in this.Words()) { if (i > 0) { builder.Append(","); } builder.AppendFormat("{0:x8}", word); i++; } builder.Append("}"); Debug.Assert(i > 0); return pooledBuilder.ToStringAndFree(); } public static bool TryParse(string refKindString, int capacity, out RefKindVector result) { ulong? firstWord = null; ArrayBuilder<ulong>? otherWords = null; foreach (var word in refKindString.Split(',')) { ulong value; try { value = Convert.ToUInt64(word, 16); } catch (Exception) { result = default; return false; } if (firstWord is null) { firstWord = value; } else { otherWords ??= ArrayBuilder<ulong>.GetInstance(); otherWords.Add(value); } } Debug.Assert(firstWord is not null); var bitVector = BitVector.FromWords(firstWord.Value, otherWords?.ToArrayAndFree() ?? Array.Empty<ulong>(), capacity * 2); result = new RefKindVector(bitVector); return true; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/CSharp/Test/Emit/PDB/PDBDynamicLocalsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBDynamicLocalsTests : CSharpTestBase { [Fact] public void EmitPDBDynamicObjectVariable1() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { dynamic d1 = new Helper(); dynamic d2 = new Point(); D d4 = new D(d1.goo); Helper d5 = new Helper(d1); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { CSharpRef }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> <bucket flags=""1"" slotId=""1"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""67"" /> <slot kind=""0"" offset=""98"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""28"" document=""1"" /> <entry offset=""0x17"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""24"" document=""1"" /> <entry offset=""0xb1"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""30"" document=""1"" /> <entry offset=""0x10f"" startLine=""24"" startColumn=""3"" endLine=""24"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x110""> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d2"" il_index=""1"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d4"" il_index=""2"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d5"" il_index=""3"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocals1() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic[] arrDynamic = new dynamic[] {""1""}; foreach (dynamic d in arrDynamic) { //do nothing } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""1"" slotId=""3"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""6"" offset=""58"" /> <slot kind=""8"" offset=""58"" /> <slot kind=""0"" offset=""58"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""46"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x11"" startLine=""8"" startColumn=""31"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""28"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <local name=""arrDynamic"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <local name=""d"" il_index=""3"" il_start=""0x17"" il_end=""0x1d"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicConstVariable() { string source = @" class Test { public static void Main(string[] args) { { const dynamic d = null; const string c = null; } { const dynamic c = null; const dynamic d = null; } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""c"" /> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""d"" value=""null"" type=""Object"" /> <constant name=""c"" value=""null"" type=""String"" /> </scope> <scope startOffset=""0x3"" endOffset=""0x5""> <constant name=""c"" value=""null"" type=""Object"" /> <constant name=""d"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicDuplicateName() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { { dynamic a = null; object b = null; } { dynamic[] a = null; dynamic b = null; } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""a"" /> <bucket flags=""01"" slotId=""2"" localName=""a"" /> <bucket flags=""1"" slotId=""3"" localName=""b"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""64"" /> <slot kind=""0"" offset=""119"" /> <slot kind=""0"" offset=""150"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""30"" document=""1"" /> <entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0x6"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0xd"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <scope startOffset=""0x1"" endOffset=""0x7""> <local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> </scope> <scope startOffset=""0x7"" endOffset=""0xd""> <local name=""a"" il_index=""2"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> <local name=""b"" il_index=""3"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicVariableNameTooLong() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d12345678901234567890123456789012345678901234567890123456789012"" /> <bucket flags=""1"" slotId=""0"" localName=""b12345678901234567890123456789012345678901234567890123456789012"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""234"" /> <slot kind=""0"" offset=""336"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""89"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""88"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <local name=""c123456789012345678901234567890123456789012345678901234567890123"" il_index=""0"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <local name=""d12345678901234567890123456789012345678901234567890123456789012"" il_index=""1"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <constant name=""a123456789012345678901234567890123456789012345678901234567890123"" value=""null"" type=""Object"" /> <constant name=""b12345678901234567890123456789012345678901234567890123456789012"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicArrayVariable() { string source = WithWindowsLineBreaks(@" class ArrayTest { int x; } class Test { public static void Main(string[] args) { dynamic[] arr = new dynamic[10]; dynamic[,] arrdim = new string[2,3]; dynamic[] arrobj = new ArrayTest[2]; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arr"" /> <bucket flags=""01"" slotId=""1"" localName=""arrdim"" /> <bucket flags=""01"" slotId=""2"" localName=""arrobj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""91"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x1e"" startLine=""13"" startColumn=""3"" endLine=""13"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1f""> <local name=""arr"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrdim"" il_index=""1"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrobj"" il_index=""2"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicCollectionVariable() { string source = WithWindowsLineBreaks(@" using System.Collections.Generic; class Test { public static void Main(string[] args) { dynamic l1 = new List<int>(); List<dynamic> l2 = new List<dynamic>(); dynamic l3 = new List<dynamic>(); Dictionary<dynamic,dynamic> d1 = new Dictionary<dynamic,dynamic>(); dynamic d2 = new Dictionary<int,int>(); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""l1"" /> <bucket flags=""01"" slotId=""1"" localName=""l2"" /> <bucket flags=""1"" slotId=""2"" localName=""l3"" /> <bucket flags=""011"" slotId=""3"" localName=""d1"" /> <bucket flags=""1"" slotId=""4"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""146"" /> <slot kind=""0"" offset=""197"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""3"" endLine=""6"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""32"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0xd"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""70"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""42"" document=""1"" /> <entry offset=""0x20"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <namespace name=""System.Collections.Generic"" /> <local name=""l1"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l2"" il_index=""1"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l3"" il_index=""2"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d1"" il_index=""3"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d2"" il_index=""4"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBDynamicObjectVariable2() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { Helper staticObj = new Helper(); dynamic d1 = new Helper(); dynamic d3 = new D(staticObj.goo); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d1"" /> <bucket flags=""1"" slotId=""2"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""12"" /> <slot kind=""0"" offset=""49"" /> <slot kind=""0"" offset=""79"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""35"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""29"" document=""1"" /> <entry offset=""0xd"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""37"" document=""1"" /> <entry offset=""0x1a"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <local name=""staticObj"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d1"" il_index=""1"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d3"" il_index=""2"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassConstructorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { public Test() { dynamic d; } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""2"" endLine=""4"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <scope startOffset=""0x7"" endOffset=""0x9""> <local name=""d"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassPropertyDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { string field; public dynamic Field { get { dynamic d = field + field; return d; } set { dynamic d = null; //field = d; Not yet implemented in Roslyn } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Field""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Field"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""1"" /> <entry offset=""0x3"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassOverloadedOperatorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Complex { int real; int imaginary; public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static dynamic operator +(Complex c1, Complex c2) { dynamic d = new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); return d; } } class Test { public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Complex"" name="".ctor"" parameterNames=""real, imaginary""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""44"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""Complex"" name=""op_Addition"" parameterNames=""c1, c2""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""81"" document=""1"" /> <entry offset=""0x21"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0x25"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassIndexerDynamicLocal() { string source = WithWindowsLineBreaks(@" class Test { dynamic[] arr; public dynamic this[int i] { get { dynamic d = arr[i]; return d; } set { dynamic d = (dynamic) value; arr[i] = d; } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Item"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0xe"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x10"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Item"" parameterNames=""i, value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""41"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0xc"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassEventHandlerDynamicLocal() { string source = WithWindowsLineBreaks(@" using System; class Sample { public static void Main() { ConsoleKeyInfo cki; Console.Clear(); Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler); } protected static void myHandler(object sender, ConsoleCancelEventArgs args) { dynamic d; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Sample"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""26"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""76"" document=""1"" /> <entry offset=""0x19"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <namespace name=""System"" /> <local name=""cki"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> <method containingType=""Sample"" name=""myHandler"" parameterNames=""sender, args""> <customDebugInfo> <forward declaringType=""Sample"" methodName=""Main"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBStructDynamicLocals() { string source = WithWindowsLineBreaks(@" using System; struct Test { int d; public Test(int d) { dynamic d1; this.d = d; } public int D { get { dynamic d2; return d; } set { dynamic d3; d = value; } } public static Test operator +(Test t1, Test t2) { dynamic d4; return new Test(t1.d + t2.d); } public static void Main() { dynamic d5; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor"" parameterNames=""d""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""get_D""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc""> <local name=""d2"" il_index=""0"" il_start=""0x0"" il_end=""0xc"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_D"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <local name=""d3"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""op_Addition"" parameterNames=""t1, t2""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d4"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""38"" document=""1"" /> <entry offset=""0x16"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x18""> <local name=""d4"" il_index=""0"" il_start=""0x0"" il_end=""0x18"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBAnonymousFunctionLocals() { string source = WithWindowsLineBreaks(@" using System; class Test { public delegate dynamic D1(dynamic d1); public delegate void D2(dynamic d2); public static void Main(string[] args) { D1 obj1 = d3 => d3; D2 obj2 = new D2(d4 => { dynamic d5; d5 = d4; }); D1 obj3 = (dynamic d6) => { return d6; }; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""14"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""102"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <lambda offset=""27"" /> <lambda offset=""63"" /> <lambda offset=""125"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""50"" document=""1"" /> <entry offset=""0x61"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x62""> <namespace name=""System"" /> <local name=""obj1"" il_index=""0"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj2"" il_index=""1"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj3"" il_index=""2"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_0"" parameterNames=""d3""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""27"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_1"" parameterNames=""d4""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""73"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""32"" endLine=""10"" endColumn=""33"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""46"" endLine=""10"" endColumn=""54"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""55"" endLine=""10"" endColumn=""56"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_2"" parameterNames=""d6""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""21"" offset=""125"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""35"" endLine=""11"" endColumn=""36"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""37"" endLine=""11"" endColumn=""47"" document=""1"" /> <entry offset=""0x5"" startLine=""11"" startColumn=""48"" endLine=""11"" endColumn=""49"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalVariables() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; dynamic[] scores = new dynamic[] { ""97"", ""92"", ""81"", ""60"" }; dynamic[] arrDynamic = new dynamic[] { ""1"", ""2"", ""3"" }; while (d1 < 1) { dynamic dInWhile; d1++; } do { dynamic dInDoWhile; d1++; } while (d1 < 1); foreach (int d in arrInt) { dynamic dInForEach; } for (int i = 0; i < 1; i++) { dynamic dInFor; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { dynamic dInIf; } else { dynamic dInElse; } try { dynamic dInTry; throw new Exception(); } catch { dynamic dInCatch; } finally { dynamic dInFinally; } IEnumerable<dynamic> scoreQuery1 = from score in scores select score; dynamic scoreQuery2 = from score in scores select score; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""2"" localName=""scores"" /> <bucket flags=""01"" slotId=""3"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""4"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""5"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""6"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""8"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""13"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""15"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""17"" localName=""d"" /> <bucket flags=""1"" slotId=""20"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""21"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""22"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""23"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""24"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""159"" /> <slot kind=""0"" offset=""1077"" /> <slot kind=""0"" offset=""1169"" /> <slot kind=""0"" offset=""261"" /> <slot kind=""1"" offset=""214"" /> <slot kind=""0"" offset=""345"" /> <slot kind=""1"" offset=""310"" /> <slot kind=""6"" offset=""412"" /> <slot kind=""8"" offset=""412"" /> <slot kind=""0"" offset=""412"" /> <slot kind=""0"" offset=""470"" /> <slot kind=""0"" offset=""511"" /> <slot kind=""0"" offset=""562"" /> <slot kind=""1"" offset=""502"" /> <slot kind=""0"" offset=""603"" /> <slot kind=""1"" offset=""590"" /> <slot kind=""1"" offset=""678"" /> <slot kind=""0"" offset=""723"" /> <slot kind=""0"" offset=""787"" /> <slot kind=""0"" offset=""852"" /> <slot kind=""0"" offset=""954"" /> <slot kind=""0"" offset=""1024"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""1145"" /> <lambda offset=""1237"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""69"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""64"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x5d"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x5e"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x63"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x6e"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x72"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x73"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x79"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x7e"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x84"" hidden=""true"" document=""1"" /> <entry offset=""0x86"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x8d"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x8e"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x95"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x9d"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0xa0"" hidden=""true"" document=""1"" /> <entry offset=""0xa2"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0xa3"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0xa4"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0xaa"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0xb1"" hidden=""true"" document=""1"" /> <entry offset=""0xb5"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0xbc"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0xbf"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0xc0"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0xd0"" hidden=""true"" document=""1"" /> <entry offset=""0xd4"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0xd5"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0xd6"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0xd9"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0xda"" hidden=""true"" document=""1"" /> <entry offset=""0xdb"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0xdc"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0xe2"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0xe3"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0xe4"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0xe7"" hidden=""true"" document=""1"" /> <entry offset=""0xe9"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xea"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xec"" startLine=""56"" startColumn=""9"" endLine=""58"" endColumn=""26"" document=""1"" /> <entry offset=""0x113"" startLine=""59"" startColumn=""9"" endLine=""61"" endColumn=""26"" document=""1"" /> <entry offset=""0x13a"" startLine=""62"" startColumn=""5"" endLine=""62"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13b""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scores"" il_index=""2"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrDynamic"" il_index=""3"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery1"" il_index=""4"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery2"" il_index=""5"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <scope startOffset=""0x5d"" endOffset=""0x63""> <local name=""dInWhile"" il_index=""6"" il_start=""0x5d"" il_end=""0x63"" attributes=""0"" /> </scope> <scope startOffset=""0x6d"" endOffset=""0x73""> <local name=""dInDoWhile"" il_index=""8"" il_start=""0x6d"" il_end=""0x73"" attributes=""0"" /> </scope> <scope startOffset=""0x86"" endOffset=""0x8f""> <local name=""d"" il_index=""12"" il_start=""0x86"" il_end=""0x8f"" attributes=""0"" /> <scope startOffset=""0x8d"" endOffset=""0x8f""> <local name=""dInForEach"" il_index=""13"" il_start=""0x8d"" il_end=""0x8f"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0x9d"" endOffset=""0xb5""> <local name=""i"" il_index=""14"" il_start=""0x9d"" il_end=""0xb5"" attributes=""0"" /> <scope startOffset=""0xa2"" endOffset=""0xa4""> <local name=""dInFor"" il_index=""15"" il_start=""0xa2"" il_end=""0xa4"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0xb5"" endOffset=""0xca""> <local name=""d"" il_index=""17"" il_start=""0xb5"" il_end=""0xca"" attributes=""0"" /> </scope> <scope startOffset=""0xd4"" endOffset=""0xd6""> <local name=""dInIf"" il_index=""20"" il_start=""0xd4"" il_end=""0xd6"" attributes=""0"" /> </scope> <scope startOffset=""0xd8"" endOffset=""0xda""> <local name=""dInElse"" il_index=""21"" il_start=""0xd8"" il_end=""0xda"" attributes=""0"" /> </scope> <scope startOffset=""0xdb"" endOffset=""0xe2""> <local name=""dInTry"" il_index=""22"" il_start=""0xdb"" il_end=""0xe2"" attributes=""0"" /> </scope> <scope startOffset=""0xe3"" endOffset=""0xe5""> <local name=""dInCatch"" il_index=""23"" il_start=""0xe3"" il_end=""0xe5"" attributes=""0"" /> </scope> <scope startOffset=""0xe9"" endOffset=""0xeb""> <local name=""dInFinally"" il_index=""24"" il_start=""0xe9"" il_end=""0xeb"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_0"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""58"" startColumn=""20"" endLine=""58"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_1"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""61"" startColumn=""20"" endLine=""61"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalConstants() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; const dynamic scores = null; const dynamic arrDynamic = null; while (d1 < 1) { const dynamic dInWhile = null; d1++; } do { const dynamic dInDoWhile = null; d1++; } while (d1 < 1); foreach (int d in arrInt) { const dynamic dInForEach = null; } for (int i = 0; i < 1; i++) { const dynamic dInFor = null; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { const dynamic dInIf = null; } else { const dynamic dInElse = null; } try { const dynamic dInTry = null; throw new Exception(); } catch { const dynamic dInCatch = null; } finally { const dynamic dInFinally = null; } const IEnumerable<dynamic> scoreQuery1 = null; const dynamic scoreQuery2 = null; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""scores"" /> <bucket flags=""1"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""0"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""0"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""0"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""9"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""0"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""0"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""0"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""1"" offset=""159"" /> <slot kind=""1"" offset=""268"" /> <slot kind=""6"" offset=""383"" /> <slot kind=""8"" offset=""383"" /> <slot kind=""0"" offset=""383"" /> <slot kind=""0"" offset=""495"" /> <slot kind=""1"" offset=""486"" /> <slot kind=""0"" offset=""600"" /> <slot kind=""1"" offset=""587"" /> <slot kind=""1"" offset=""675"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x18"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x2a"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x34"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x43"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x44"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x4b"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x53"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0x59"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0x5a"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0x60"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x74"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0x75"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0x76"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0x7c"" hidden=""true"" document=""1"" /> <entry offset=""0x80"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0x86"" hidden=""true"" document=""1"" /> <entry offset=""0x8a"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0x8b"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0x8c"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0x90"" hidden=""true"" document=""1"" /> <entry offset=""0x91"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0x92"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0x98"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0x99"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0x9a"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0x9d"" hidden=""true"" document=""1"" /> <entry offset=""0x9f"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xa0"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xa2"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa3""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <constant name=""scores"" value=""null"" type=""Object"" /> <constant name=""arrDynamic"" value=""null"" type=""Object"" /> <constant name=""scoreQuery1"" value=""null"" signature=""System.Collections.Generic.IEnumerable`1{Object}"" /> <constant name=""scoreQuery2"" value=""null"" type=""Object"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <constant name=""dInWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x25"" endOffset=""0x2b""> <constant name=""dInDoWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x3c"" endOffset=""0x45""> <local name=""d"" il_index=""6"" il_start=""0x3c"" il_end=""0x45"" attributes=""0"" /> <scope startOffset=""0x43"" endOffset=""0x45""> <constant name=""dInForEach"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x53"" endOffset=""0x6b""> <local name=""i"" il_index=""7"" il_start=""0x53"" il_end=""0x6b"" attributes=""0"" /> <scope startOffset=""0x58"" endOffset=""0x5a""> <constant name=""dInFor"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x6b"" endOffset=""0x80""> <local name=""d"" il_index=""9"" il_start=""0x6b"" il_end=""0x80"" attributes=""0"" /> </scope> <scope startOffset=""0x8a"" endOffset=""0x8c""> <constant name=""dInIf"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x8e"" endOffset=""0x90""> <constant name=""dInElse"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x91"" endOffset=""0x98""> <constant name=""dInTry"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x99"" endOffset=""0x9b""> <constant name=""dInCatch"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x9f"" endOffset=""0xa1""> <constant name=""dInFinally"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(17947, "https://github.com/dotnet/roslyn/issues/17947")] [Fact] public void VariablesAndConstantsInUnreachableCode() { string source = WithWindowsLineBreaks(@" class C { void F() { dynamic v1 = 1; const dynamic c1 = null; throw null; dynamic v2 = 1; const dynamic c2 = null; { dynamic v3 = 1; const dynamic c3 = null; } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 10 (0xa) .maxstack 1 .locals init (object V_0, //v1 object V_1, //v2 object V_2) //v3 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldnull IL_0009: throw }"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""v1"" /> <bucket flags=""1"" slotId=""1"" localName=""v2"" /> <bucket flags=""1"" slotId=""0"" localName=""c1"" /> <bucket flags=""1"" slotId=""0"" localName=""c2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""103"" /> <slot kind=""0"" offset=""181"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""v1"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v2"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <constant name=""c1"" value=""null"" type=""Object"" /> <constant name=""c2"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBVarVariableLocal() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic d = ""1""; var v = d; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""1"" localName=""v"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""29"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""13"" document=""1"" /> <entry offset=""0x9"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <namespace name=""System"" /> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBGenericDynamicNonLocal() { string source = WithWindowsLineBreaks(@" using System; class dynamic<T> { public T field; } class Test { public static void Main(string[] args) { dynamic<dynamic> obj = new dynamic<dynamic>(); obj.field = ""1""; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""obj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""22"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""49"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""2"" endLine=""13"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13""> <namespace name=""System"" /> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x13"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_1() //With 2 normal dynamic locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; dynamic zzz; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""1"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""41"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_2() //With 1 normal dynamic local and 1 containing dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic> zzz; } } class Goo<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""46"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_3() //With 1 normal dynamic local and 1 containing(more than one) dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""68"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_4() //With 1 normal dynamic local, 1 containing dynamic local with a normal local variable { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; int dummy = 0; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""2"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""0"" offset=""92"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""dummy"" il_index=""1"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""zzz"" il_index=""2"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_5_Just_Long() //Dynamic local with dynamic attribute of length 63 above which the flag is emitted empty { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""010101010101010101010101010101010101010101010101010101010101011"" slotId=""0"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""361"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_6_Too_Long() //The limitation of the previous testcase with dynamic attribute length 64 and not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_7() //Corner case dynamic locals with normal locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z1; int dummy1 = 0; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z2; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; int dummy2 = 0; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""389"" /> <slot kind=""0"" offset=""771"" /> <slot kind=""0"" offset=""1145"" /> <slot kind=""0"" offset=""1162"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x6"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z1"" il_index=""0"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy1"" il_index=""1"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z2"" il_index=""2"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z3"" il_index=""3"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy2"" il_index=""4"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_8_Mixed_Corner_Cases() //Mixed case with one more limitation. If identifier length is greater than 63 then the info is not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; dynamic www; dynamic length63length63length63length63length63length63length63length6; dynamic length64length64length64length64length64length64length64length64; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""www"" /> <bucket flags=""1"" slotId=""2"" localName=""length63length63length63length63length63length63length63length6"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""393"" /> <slot kind=""0"" offset=""415"" /> <slot kind=""0"" offset=""497"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z3"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length63length63length63length63length63length63length63length6"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length64length64length64length64length64length64length64length64"" il_index=""3"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_9() //Check corner case with only corner cases { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> yes; F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> no; dynamic www; } } class F<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""0000000000000000000000000000000000000000000000000000000000000001"" slotId=""0"" localName=""yes"" /> <bucket flags=""1"" slotId=""2"" localName=""www"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""208"" /> <slot kind=""0"" offset=""422"" /> <slot kind=""0"" offset=""443"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yes"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""no"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_TwoScope() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic simple; for(int x =0 ; x < 10 ; ++x) { dynamic inner; } } static void nothing(dynamic localArg) { dynamic localInner; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""simple"" /> <bucket flags=""1"" slotId=""2"" localName=""inner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""44"" /> <slot kind=""0"" offset=""84"" /> <slot kind=""1"" offset=""36"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""24"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x15""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""simple"" il_index=""0"" il_start=""0x0"" il_end=""0x15"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x14""> <local name=""x"" il_index=""1"" il_start=""0x1"" il_end=""0x14"" attributes=""0"" /> <scope startOffset=""0x5"" endOffset=""0x7""> <local name=""inner"" il_index=""2"" il_start=""0x5"" il_end=""0x7"" attributes=""0"" /> </scope> </scope> </scope> </method> <method containingType=""Program"" name=""nothing"" parameterNames=""localArg""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""localInner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""localInner"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(637465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637465")] [Fact] public void DynamicLocalOptimizedAway() { string source = WithWindowsLineBreaks(@" class C { public static void Main() { dynamic d = GetDynamic(); } static dynamic GetDynamic() { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""34"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""GetDynamic""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB { public class PDBDynamicLocalsTests : CSharpTestBase { [Fact] public void EmitPDBDynamicObjectVariable1() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { dynamic d1 = new Helper(); dynamic d2 = new Point(); D d4 = new D(d1.goo); Helper d5 = new Helper(d1); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, references: new[] { CSharpRef }, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> <bucket flags=""1"" slotId=""1"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""67"" /> <slot kind=""0"" offset=""98"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""29"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""28"" document=""1"" /> <entry offset=""0x17"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""24"" document=""1"" /> <entry offset=""0xb1"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""30"" document=""1"" /> <entry offset=""0x10f"" startLine=""24"" startColumn=""3"" endLine=""24"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x110""> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d2"" il_index=""1"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d4"" il_index=""2"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> <local name=""d5"" il_index=""3"" il_start=""0x0"" il_end=""0x110"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocals1() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic[] arrDynamic = new dynamic[] {""1""}; foreach (dynamic d in arrDynamic) { //do nothing } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""1"" slotId=""3"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""6"" offset=""58"" /> <slot kind=""8"" offset=""58"" /> <slot kind=""0"" offset=""58"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""46"" document=""1"" /> <entry offset=""0x10"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""16"" document=""1"" /> <entry offset=""0x11"" startLine=""8"" startColumn=""31"" endLine=""8"" endColumn=""41"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""8"" startColumn=""18"" endLine=""8"" endColumn=""27"" document=""1"" /> <entry offset=""0x1b"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x1c"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" hidden=""true"" document=""1"" /> <entry offset=""0x21"" startLine=""8"" startColumn=""28"" endLine=""8"" endColumn=""30"" document=""1"" /> <entry offset=""0x27"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x28""> <namespace name=""System"" /> <local name=""arrDynamic"" il_index=""0"" il_start=""0x0"" il_end=""0x28"" attributes=""0"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <local name=""d"" il_index=""3"" il_start=""0x17"" il_end=""0x1d"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicConstVariable() { string source = @" class Test { public static void Main(string[] args) { { const dynamic d = null; const string c = null; } { const dynamic c = null; const dynamic d = null; } } }"; var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""c"" /> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x4"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x5"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <scope startOffset=""0x1"" endOffset=""0x3""> <constant name=""d"" value=""null"" type=""Object"" /> <constant name=""c"" value=""null"" type=""String"" /> </scope> <scope startOffset=""0x3"" endOffset=""0x5""> <constant name=""c"" value=""null"" type=""Object"" /> <constant name=""d"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicDuplicateName() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { { dynamic a = null; object b = null; } { dynamic[] a = null; dynamic b = null; } } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""a"" /> <bucket flags=""01"" slotId=""2"" localName=""a"" /> <bucket flags=""1"" slotId=""3"" localName=""b"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""34"" /> <slot kind=""0"" offset=""64"" /> <slot kind=""0"" offset=""119"" /> <slot kind=""0"" offset=""150"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""10"" document=""1"" /> <entry offset=""0x2"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""30"" document=""1"" /> <entry offset=""0x4"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""29"" document=""1"" /> <entry offset=""0x6"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" document=""1"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x8"" startLine=""11"" startColumn=""13"" endLine=""11"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""30"" document=""1"" /> <entry offset=""0xc"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0xd"" startLine=""14"" startColumn=""2"" endLine=""14"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <scope startOffset=""0x1"" endOffset=""0x7""> <local name=""a"" il_index=""0"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> <local name=""b"" il_index=""1"" il_start=""0x1"" il_end=""0x7"" attributes=""0"" /> </scope> <scope startOffset=""0x7"" endOffset=""0xd""> <local name=""a"" il_index=""2"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> <local name=""b"" il_index=""3"" il_start=""0x7"" il_end=""0xd"" attributes=""0"" /> </scope> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicVariableNameTooLong() { string source = WithWindowsLineBreaks(@" class Test { public static void Main(string[] args) { const dynamic a123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars const dynamic b12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars dynamic c123456789012345678901234567890123456789012345678901234567890123 = null; // 64 chars dynamic d12345678901234567890123456789012345678901234567890123456789012 = null; // 63 chars } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb( @"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d12345678901234567890123456789012345678901234567890123456789012"" /> <bucket flags=""1"" slotId=""0"" localName=""b12345678901234567890123456789012345678901234567890123456789012"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""234"" /> <slot kind=""0"" offset=""336"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""89"" document=""1"" /> <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""88"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x6""> <local name=""c123456789012345678901234567890123456789012345678901234567890123"" il_index=""0"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <local name=""d12345678901234567890123456789012345678901234567890123456789012"" il_index=""1"" il_start=""0x0"" il_end=""0x6"" attributes=""0"" /> <constant name=""a123456789012345678901234567890123456789012345678901234567890123"" value=""null"" type=""Object"" /> <constant name=""b12345678901234567890123456789012345678901234567890123456789012"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicArrayVariable() { string source = WithWindowsLineBreaks(@" class ArrayTest { int x; } class Test { public static void Main(string[] args) { dynamic[] arr = new dynamic[10]; dynamic[,] arrdim = new string[2,3]; dynamic[] arrobj = new ArrayTest[2]; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""arr"" /> <bucket flags=""01"" slotId=""1"" localName=""arrdim"" /> <bucket flags=""01"" slotId=""2"" localName=""arrobj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""91"" /> <slot kind=""temp"" /> <slot kind=""temp"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""35"" document=""1"" /> <entry offset=""0x9"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""39"" document=""1"" /> <entry offset=""0x1e"" startLine=""13"" startColumn=""3"" endLine=""13"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1f""> <local name=""arr"" il_index=""0"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrdim"" il_index=""1"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> <local name=""arrobj"" il_index=""2"" il_start=""0x0"" il_end=""0x1f"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBDynamicCollectionVariable() { string source = WithWindowsLineBreaks(@" using System.Collections.Generic; class Test { public static void Main(string[] args) { dynamic l1 = new List<int>(); List<dynamic> l2 = new List<dynamic>(); dynamic l3 = new List<dynamic>(); Dictionary<dynamic,dynamic> d1 = new Dictionary<dynamic,dynamic>(); dynamic d2 = new Dictionary<int,int>(); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""l1"" /> <bucket flags=""01"" slotId=""1"" localName=""l2"" /> <bucket flags=""1"" slotId=""2"" localName=""l3"" /> <bucket flags=""011"" slotId=""3"" localName=""d1"" /> <bucket flags=""1"" slotId=""4"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""52"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""146"" /> <slot kind=""0"" offset=""197"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""3"" endLine=""6"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""32"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""42"" document=""1"" /> <entry offset=""0xd"" startLine=""9"" startColumn=""3"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""3"" endLine=""10"" endColumn=""70"" document=""1"" /> <entry offset=""0x19"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""42"" document=""1"" /> <entry offset=""0x20"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x21""> <namespace name=""System.Collections.Generic"" /> <local name=""l1"" il_index=""0"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l2"" il_index=""1"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""l3"" il_index=""2"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d1"" il_index=""3"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> <local name=""d2"" il_index=""4"" il_start=""0x0"" il_end=""0x21"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBDynamicObjectVariable2() { string source = WithWindowsLineBreaks(@" class Helper { int x; public void goo(int y){} public Helper(){} public Helper(int x){} } struct Point { int x; int y; } class Test { delegate void D(int y); public static void Main(string[] args) { Helper staticObj = new Helper(); dynamic d1 = new Helper(); dynamic d3 = new D(staticObj.goo); } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Helper"" name=""goo"" parameterNames=""y""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""24"" endLine=""5"" endColumn=""25"" document=""1"" /> <entry offset=""0x1"" startLine=""5"" startColumn=""25"" endLine=""5"" endColumn=""26"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""17"" document=""1"" /> <entry offset=""0x7"" startLine=""6"" startColumn=""17"" endLine=""6"" endColumn=""18"" document=""1"" /> <entry offset=""0x8"" startLine=""6"" startColumn=""18"" endLine=""6"" endColumn=""19"" document=""1"" /> </sequencePoints> </method> <method containingType=""Helper"" name="".ctor"" parameterNames=""x""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""22"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""22"" endLine=""7"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""23"" endLine=""7"" endColumn=""24"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Helper"" methodName=""goo"" parameterNames=""y"" /> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""d1"" /> <bucket flags=""1"" slotId=""2"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""12"" /> <slot kind=""0"" offset=""49"" /> <slot kind=""0"" offset=""79"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""3"" endLine=""18"" endColumn=""4"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""3"" endLine=""19"" endColumn=""35"" document=""1"" /> <entry offset=""0x7"" startLine=""20"" startColumn=""3"" endLine=""20"" endColumn=""29"" document=""1"" /> <entry offset=""0xd"" startLine=""21"" startColumn=""3"" endLine=""21"" endColumn=""37"" document=""1"" /> <entry offset=""0x1a"" startLine=""22"" startColumn=""3"" endLine=""22"" endColumn=""4"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1b""> <local name=""staticObj"" il_index=""0"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d1"" il_index=""1"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> <local name=""d3"" il_index=""2"" il_start=""0x0"" il_end=""0x1b"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassConstructorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { public Test() { dynamic d; } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""4"" startColumn=""2"" endLine=""4"" endColumn=""15"" document=""1"" /> <entry offset=""0x7"" startLine=""5"" startColumn=""2"" endLine=""5"" endColumn=""3"" document=""1"" /> <entry offset=""0x8"" startLine=""7"" startColumn=""2"" endLine=""7"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <scope startOffset=""0x7"" endOffset=""0x9""> <local name=""d"" il_index=""0"" il_start=""0x7"" il_end=""0x9"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassPropertyDynamicLocals() { string source = WithWindowsLineBreaks(@" class Test { string field; public dynamic Field { get { dynamic d = field + field; return d; } set { dynamic d = null; //field = d; Not yet implemented in Roslyn } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Field""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""39"" document=""1"" /> <entry offset=""0x13"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x19""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x19"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Field"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""30"" document=""1"" /> <entry offset=""0x3"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Field"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassOverloadedOperatorDynamicLocals() { string source = WithWindowsLineBreaks(@" class Complex { int real; int imaginary; public Complex(int real, int imaginary) { this.real = real; this.imaginary = imaginary; } public static dynamic operator +(Complex c1, Complex c2) { dynamic d = new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); return d; } } class Test { public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Complex"" name="".ctor"" parameterNames=""real, imaginary""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""44"" document=""1"" /> <entry offset=""0x7"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x8"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""26"" document=""1"" /> <entry offset=""0xf"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0x16"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""Complex"" name=""op_Addition"" parameterNames=""c1, c2""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""81"" document=""1"" /> <entry offset=""0x21"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""18"" document=""1"" /> <entry offset=""0x25"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x27""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x27"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Complex"" methodName="".ctor"" parameterNames=""real, imaginary"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""22"" startColumn=""5"" endLine=""22"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassIndexerDynamicLocal() { string source = WithWindowsLineBreaks(@" class Test { dynamic[] arr; public dynamic this[int i] { get { dynamic d = arr[i]; return d; } set { dynamic d = (dynamic) value; arr[i] = d; } } public static void Main(string[] args) { } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""get_Item"" parameterNames=""i""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""32"" document=""1"" /> <entry offset=""0xa"" startLine=""10"" startColumn=""13"" endLine=""10"" endColumn=""22"" document=""1"" /> <entry offset=""0xe"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x10""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x10"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_Item"" parameterNames=""i, value""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""41"" document=""1"" /> <entry offset=""0x3"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""1"" /> <entry offset=""0xc"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xd""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xd"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <forward declaringType=""Test"" methodName=""get_Item"" parameterNames=""i"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBClassEventHandlerDynamicLocal() { string source = WithWindowsLineBreaks(@" using System; class Sample { public static void Main() { ConsoleKeyInfo cki; Console.Clear(); Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler); } protected static void myHandler(object sender, ConsoleCancelEventArgs args) { dynamic d; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Sample"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""26"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""25"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""76"" document=""1"" /> <entry offset=""0x19"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x1a""> <namespace name=""System"" /> <local name=""cki"" il_index=""0"" il_start=""0x0"" il_end=""0x1a"" attributes=""0"" /> </scope> </method> <method containingType=""Sample"" name=""myHandler"" parameterNames=""sender, args""> <customDebugInfo> <forward declaringType=""Sample"" methodName=""Main"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBStructDynamicLocals() { string source = WithWindowsLineBreaks(@" using System; struct Test { int d; public Test(int d) { dynamic d1; this.d = d; } public int D { get { dynamic d2; return d; } set { dynamic d3; d = value; } } public static Test operator +(Test t1, Test t2) { dynamic d4; return new Test(t1.d + t2.d); } public static void Main() { dynamic d5; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name="".ctor"" parameterNames=""d""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d1"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x8"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <namespace name=""System"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""get_D""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""22"" document=""1"" /> <entry offset=""0xa"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xc""> <local name=""d2"" il_index=""0"" il_start=""0x0"" il_end=""0xc"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""set_D"" parameterNames=""value""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d3"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""23"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""23"" document=""1"" /> <entry offset=""0x8"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x9""> <local name=""d3"" il_index=""0"" il_start=""0x0"" il_end=""0x9"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""op_Addition"" parameterNames=""t1, t2""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d4"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""21"" offset=""0"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""38"" document=""1"" /> <entry offset=""0x16"" startLine=""29"" startColumn=""5"" endLine=""29"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x18""> <local name=""d4"" il_index=""0"" il_start=""0x0"" il_end=""0x18"" attributes=""0"" /> </scope> </method> <method containingType=""Test"" name=""Main""> <customDebugInfo> <forward declaringType=""Test"" methodName="".ctor"" parameterNames=""d"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""31"" startColumn=""5"" endLine=""31"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""33"" startColumn=""5"" endLine=""33"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBAnonymousFunctionLocals() { string source = WithWindowsLineBreaks(@" using System; class Test { public delegate dynamic D1(dynamic d1); public delegate void D2(dynamic d2); public static void Main(string[] args) { D1 obj1 = d3 => d3; D2 obj2 = new D2(d4 => { dynamic d5; d5 = d4; }); D1 obj3 = (dynamic d6) => { return d6; }; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""14"" /> <slot kind=""0"" offset=""43"" /> <slot kind=""0"" offset=""102"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>2</methodOrdinal> <lambda offset=""27"" /> <lambda offset=""63"" /> <lambda offset=""125"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""28"" document=""1"" /> <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""50"" document=""1"" /> <entry offset=""0x61"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x62""> <namespace name=""System"" /> <local name=""obj1"" il_index=""0"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj2"" il_index=""1"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> <local name=""obj3"" il_index=""2"" il_start=""0x0"" il_end=""0x62"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_0"" parameterNames=""d3""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""25"" endLine=""9"" endColumn=""27"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_1"" parameterNames=""d4""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d5"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""73"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""32"" endLine=""10"" endColumn=""33"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""46"" endLine=""10"" endColumn=""54"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""55"" endLine=""10"" endColumn=""56"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <local name=""d5"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__2_2"" parameterNames=""d6""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> <encLocalSlotMap> <slot kind=""21"" offset=""125"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""35"" endLine=""11"" endColumn=""36"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""37"" endLine=""11"" endColumn=""47"" document=""1"" /> <entry offset=""0x5"" startLine=""11"" startColumn=""48"" endLine=""11"" endColumn=""49"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalVariables() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; dynamic[] scores = new dynamic[] { ""97"", ""92"", ""81"", ""60"" }; dynamic[] arrDynamic = new dynamic[] { ""1"", ""2"", ""3"" }; while (d1 < 1) { dynamic dInWhile; d1++; } do { dynamic dInDoWhile; d1++; } while (d1 < 1); foreach (int d in arrInt) { dynamic dInForEach; } for (int i = 0; i < 1; i++) { dynamic dInFor; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { dynamic dInIf; } else { dynamic dInElse; } try { dynamic dInTry; throw new Exception(); } catch { dynamic dInCatch; } finally { dynamic dInFinally; } IEnumerable<dynamic> scoreQuery1 = from score in scores select score; dynamic scoreQuery2 = from score in scores select score; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""2"" localName=""scores"" /> <bucket flags=""01"" slotId=""3"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""4"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""5"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""6"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""8"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""13"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""15"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""17"" localName=""d"" /> <bucket flags=""1"" slotId=""20"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""21"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""22"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""23"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""24"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""0"" offset=""89"" /> <slot kind=""0"" offset=""159"" /> <slot kind=""0"" offset=""1077"" /> <slot kind=""0"" offset=""1169"" /> <slot kind=""0"" offset=""261"" /> <slot kind=""1"" offset=""214"" /> <slot kind=""0"" offset=""345"" /> <slot kind=""1"" offset=""310"" /> <slot kind=""6"" offset=""412"" /> <slot kind=""8"" offset=""412"" /> <slot kind=""0"" offset=""412"" /> <slot kind=""0"" offset=""470"" /> <slot kind=""0"" offset=""511"" /> <slot kind=""0"" offset=""562"" /> <slot kind=""1"" offset=""502"" /> <slot kind=""0"" offset=""603"" /> <slot kind=""1"" offset=""590"" /> <slot kind=""1"" offset=""678"" /> <slot kind=""0"" offset=""723"" /> <slot kind=""0"" offset=""787"" /> <slot kind=""0"" offset=""852"" /> <slot kind=""0"" offset=""954"" /> <slot kind=""0"" offset=""1024"" /> </encLocalSlotMap> <encLambdaMap> <methodOrdinal>0</methodOrdinal> <lambda offset=""1145"" /> <lambda offset=""1237"" /> </encLambdaMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""69"" document=""1"" /> <entry offset=""0x3c"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""64"" document=""1"" /> <entry offset=""0x5b"" hidden=""true"" document=""1"" /> <entry offset=""0x5d"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x5e"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x62"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x63"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x69"" hidden=""true"" document=""1"" /> <entry offset=""0x6d"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x6e"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x72"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x73"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x79"" hidden=""true"" document=""1"" /> <entry offset=""0x7d"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x7e"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x84"" hidden=""true"" document=""1"" /> <entry offset=""0x86"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x8d"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x8e"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" hidden=""true"" document=""1"" /> <entry offset=""0x95"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x9d"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0xa0"" hidden=""true"" document=""1"" /> <entry offset=""0xa2"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0xa3"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0xa4"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0xaa"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0xb1"" hidden=""true"" document=""1"" /> <entry offset=""0xb5"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0xbc"" hidden=""true"" document=""1"" /> <entry offset=""0xbe"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0xbf"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0xc0"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0xc6"" hidden=""true"" document=""1"" /> <entry offset=""0xca"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0xd0"" hidden=""true"" document=""1"" /> <entry offset=""0xd4"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0xd5"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0xd6"" hidden=""true"" document=""1"" /> <entry offset=""0xd8"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0xd9"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0xda"" hidden=""true"" document=""1"" /> <entry offset=""0xdb"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0xdc"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0xe2"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0xe3"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0xe4"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0xe7"" hidden=""true"" document=""1"" /> <entry offset=""0xe9"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xea"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xec"" startLine=""56"" startColumn=""9"" endLine=""58"" endColumn=""26"" document=""1"" /> <entry offset=""0x113"" startLine=""59"" startColumn=""9"" endLine=""61"" endColumn=""26"" document=""1"" /> <entry offset=""0x13a"" startLine=""62"" startColumn=""5"" endLine=""62"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13b""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scores"" il_index=""2"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""arrDynamic"" il_index=""3"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery1"" il_index=""4"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <local name=""scoreQuery2"" il_index=""5"" il_start=""0x0"" il_end=""0x13b"" attributes=""0"" /> <scope startOffset=""0x5d"" endOffset=""0x63""> <local name=""dInWhile"" il_index=""6"" il_start=""0x5d"" il_end=""0x63"" attributes=""0"" /> </scope> <scope startOffset=""0x6d"" endOffset=""0x73""> <local name=""dInDoWhile"" il_index=""8"" il_start=""0x6d"" il_end=""0x73"" attributes=""0"" /> </scope> <scope startOffset=""0x86"" endOffset=""0x8f""> <local name=""d"" il_index=""12"" il_start=""0x86"" il_end=""0x8f"" attributes=""0"" /> <scope startOffset=""0x8d"" endOffset=""0x8f""> <local name=""dInForEach"" il_index=""13"" il_start=""0x8d"" il_end=""0x8f"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0x9d"" endOffset=""0xb5""> <local name=""i"" il_index=""14"" il_start=""0x9d"" il_end=""0xb5"" attributes=""0"" /> <scope startOffset=""0xa2"" endOffset=""0xa4""> <local name=""dInFor"" il_index=""15"" il_start=""0xa2"" il_end=""0xa4"" attributes=""0"" /> </scope> </scope> <scope startOffset=""0xb5"" endOffset=""0xca""> <local name=""d"" il_index=""17"" il_start=""0xb5"" il_end=""0xca"" attributes=""0"" /> </scope> <scope startOffset=""0xd4"" endOffset=""0xd6""> <local name=""dInIf"" il_index=""20"" il_start=""0xd4"" il_end=""0xd6"" attributes=""0"" /> </scope> <scope startOffset=""0xd8"" endOffset=""0xda""> <local name=""dInElse"" il_index=""21"" il_start=""0xd8"" il_end=""0xda"" attributes=""0"" /> </scope> <scope startOffset=""0xdb"" endOffset=""0xe2""> <local name=""dInTry"" il_index=""22"" il_start=""0xdb"" il_end=""0xe2"" attributes=""0"" /> </scope> <scope startOffset=""0xe3"" endOffset=""0xe5""> <local name=""dInCatch"" il_index=""23"" il_start=""0xe3"" il_end=""0xe5"" attributes=""0"" /> </scope> <scope startOffset=""0xe9"" endOffset=""0xeb""> <local name=""dInFinally"" il_index=""24"" il_start=""0xe9"" il_end=""0xeb"" attributes=""0"" /> </scope> </scope> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_0"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""58"" startColumn=""20"" endLine=""58"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> <method containingType=""Test+&lt;&gt;c"" name=""&lt;Main&gt;b__0_1"" parameterNames=""score""> <customDebugInfo> <forward declaringType=""Test"" methodName=""Main"" parameterNames=""args"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""61"" startColumn=""20"" endLine=""61"" endColumn=""25"" document=""1"" /> </sequencePoints> </method> </methods> </symbols>"); } [Fact] public void EmitPDBLangConstructsLocalConstants() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; using System.Linq; class Test { public static void Main(string[] args) { int d1 = 0; int[] arrInt = new int[] { 1, 2, 3 }; const dynamic scores = null; const dynamic arrDynamic = null; while (d1 < 1) { const dynamic dInWhile = null; d1++; } do { const dynamic dInDoWhile = null; d1++; } while (d1 < 1); foreach (int d in arrInt) { const dynamic dInForEach = null; } for (int i = 0; i < 1; i++) { const dynamic dInFor = null; } for (dynamic d = ""1""; d1 < 0;) { //do nothing } if (d1 == 0) { const dynamic dInIf = null; } else { const dynamic dInElse = null; } try { const dynamic dInTry = null; throw new Exception(); } catch { const dynamic dInCatch = null; } finally { const dynamic dInFinally = null; } const IEnumerable<dynamic> scoreQuery1 = null; const dynamic scoreQuery2 = null; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""3"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""scores"" /> <bucket flags=""1"" slotId=""0"" localName=""arrDynamic"" /> <bucket flags=""01"" slotId=""0"" localName=""scoreQuery1"" /> <bucket flags=""1"" slotId=""0"" localName=""scoreQuery2"" /> <bucket flags=""1"" slotId=""0"" localName=""dInWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInDoWhile"" /> <bucket flags=""1"" slotId=""0"" localName=""dInForEach"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFor"" /> <bucket flags=""1"" slotId=""9"" localName=""d"" /> <bucket flags=""1"" slotId=""0"" localName=""dInIf"" /> <bucket flags=""1"" slotId=""0"" localName=""dInElse"" /> <bucket flags=""1"" slotId=""0"" localName=""dInTry"" /> <bucket flags=""1"" slotId=""0"" localName=""dInCatch"" /> <bucket flags=""1"" slotId=""0"" localName=""dInFinally"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""15"" /> <slot kind=""0"" offset=""38"" /> <slot kind=""1"" offset=""159"" /> <slot kind=""1"" offset=""268"" /> <slot kind=""6"" offset=""383"" /> <slot kind=""8"" offset=""383"" /> <slot kind=""0"" offset=""383"" /> <slot kind=""0"" offset=""495"" /> <slot kind=""1"" offset=""486"" /> <slot kind=""0"" offset=""600"" /> <slot kind=""1"" offset=""587"" /> <slot kind=""1"" offset=""675"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> <entry offset=""0x3"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""46"" document=""1"" /> <entry offset=""0x15"" hidden=""true"" document=""1"" /> <entry offset=""0x17"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""1"" /> <entry offset=""0x18"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""18"" document=""1"" /> <entry offset=""0x1c"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""1"" /> <entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""23"" document=""1"" /> <entry offset=""0x22"" hidden=""true"" document=""1"" /> <entry offset=""0x25"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""1"" /> <entry offset=""0x26"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""18"" document=""1"" /> <entry offset=""0x2a"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x2b"" startLine=""22"" startColumn=""11"" endLine=""22"" endColumn=""26"" document=""1"" /> <entry offset=""0x30"" hidden=""true"" document=""1"" /> <entry offset=""0x33"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""16"" document=""1"" /> <entry offset=""0x34"" startLine=""23"" startColumn=""27"" endLine=""23"" endColumn=""33"" document=""1"" /> <entry offset=""0x3a"" hidden=""true"" document=""1"" /> <entry offset=""0x3c"" startLine=""23"" startColumn=""18"" endLine=""23"" endColumn=""23"" document=""1"" /> <entry offset=""0x43"" startLine=""24"" startColumn=""9"" endLine=""24"" endColumn=""10"" document=""1"" /> <entry offset=""0x44"" startLine=""26"" startColumn=""9"" endLine=""26"" endColumn=""10"" document=""1"" /> <entry offset=""0x45"" hidden=""true"" document=""1"" /> <entry offset=""0x4b"" startLine=""23"" startColumn=""24"" endLine=""23"" endColumn=""26"" document=""1"" /> <entry offset=""0x53"" startLine=""27"" startColumn=""14"" endLine=""27"" endColumn=""23"" document=""1"" /> <entry offset=""0x56"" hidden=""true"" document=""1"" /> <entry offset=""0x58"" startLine=""28"" startColumn=""9"" endLine=""28"" endColumn=""10"" document=""1"" /> <entry offset=""0x59"" startLine=""30"" startColumn=""9"" endLine=""30"" endColumn=""10"" document=""1"" /> <entry offset=""0x5a"" startLine=""27"" startColumn=""32"" endLine=""27"" endColumn=""35"" document=""1"" /> <entry offset=""0x60"" startLine=""27"" startColumn=""25"" endLine=""27"" endColumn=""30"" document=""1"" /> <entry offset=""0x67"" hidden=""true"" document=""1"" /> <entry offset=""0x6b"" startLine=""31"" startColumn=""14"" endLine=""31"" endColumn=""29"" document=""1"" /> <entry offset=""0x72"" hidden=""true"" document=""1"" /> <entry offset=""0x74"" startLine=""32"" startColumn=""9"" endLine=""32"" endColumn=""10"" document=""1"" /> <entry offset=""0x75"" startLine=""34"" startColumn=""9"" endLine=""34"" endColumn=""10"" document=""1"" /> <entry offset=""0x76"" startLine=""31"" startColumn=""31"" endLine=""31"" endColumn=""37"" document=""1"" /> <entry offset=""0x7c"" hidden=""true"" document=""1"" /> <entry offset=""0x80"" startLine=""35"" startColumn=""9"" endLine=""35"" endColumn=""21"" document=""1"" /> <entry offset=""0x86"" hidden=""true"" document=""1"" /> <entry offset=""0x8a"" startLine=""36"" startColumn=""9"" endLine=""36"" endColumn=""10"" document=""1"" /> <entry offset=""0x8b"" startLine=""38"" startColumn=""9"" endLine=""38"" endColumn=""10"" document=""1"" /> <entry offset=""0x8c"" hidden=""true"" document=""1"" /> <entry offset=""0x8e"" startLine=""40"" startColumn=""9"" endLine=""40"" endColumn=""10"" document=""1"" /> <entry offset=""0x8f"" startLine=""42"" startColumn=""9"" endLine=""42"" endColumn=""10"" document=""1"" /> <entry offset=""0x90"" hidden=""true"" document=""1"" /> <entry offset=""0x91"" startLine=""44"" startColumn=""9"" endLine=""44"" endColumn=""10"" document=""1"" /> <entry offset=""0x92"" startLine=""46"" startColumn=""13"" endLine=""46"" endColumn=""35"" document=""1"" /> <entry offset=""0x98"" startLine=""48"" startColumn=""9"" endLine=""48"" endColumn=""14"" document=""1"" /> <entry offset=""0x99"" startLine=""49"" startColumn=""9"" endLine=""49"" endColumn=""10"" document=""1"" /> <entry offset=""0x9a"" startLine=""51"" startColumn=""9"" endLine=""51"" endColumn=""10"" document=""1"" /> <entry offset=""0x9d"" hidden=""true"" document=""1"" /> <entry offset=""0x9f"" startLine=""53"" startColumn=""9"" endLine=""53"" endColumn=""10"" document=""1"" /> <entry offset=""0xa0"" startLine=""55"" startColumn=""9"" endLine=""55"" endColumn=""10"" document=""1"" /> <entry offset=""0xa2"" startLine=""58"" startColumn=""5"" endLine=""58"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa3""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <namespace name=""System.Linq"" /> <local name=""d1"" il_index=""0"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <local name=""arrInt"" il_index=""1"" il_start=""0x0"" il_end=""0xa3"" attributes=""0"" /> <constant name=""scores"" value=""null"" type=""Object"" /> <constant name=""arrDynamic"" value=""null"" type=""Object"" /> <constant name=""scoreQuery1"" value=""null"" signature=""System.Collections.Generic.IEnumerable`1{Object}"" /> <constant name=""scoreQuery2"" value=""null"" type=""Object"" /> <scope startOffset=""0x17"" endOffset=""0x1d""> <constant name=""dInWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x25"" endOffset=""0x2b""> <constant name=""dInDoWhile"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x3c"" endOffset=""0x45""> <local name=""d"" il_index=""6"" il_start=""0x3c"" il_end=""0x45"" attributes=""0"" /> <scope startOffset=""0x43"" endOffset=""0x45""> <constant name=""dInForEach"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x53"" endOffset=""0x6b""> <local name=""i"" il_index=""7"" il_start=""0x53"" il_end=""0x6b"" attributes=""0"" /> <scope startOffset=""0x58"" endOffset=""0x5a""> <constant name=""dInFor"" value=""null"" type=""Object"" /> </scope> </scope> <scope startOffset=""0x6b"" endOffset=""0x80""> <local name=""d"" il_index=""9"" il_start=""0x6b"" il_end=""0x80"" attributes=""0"" /> </scope> <scope startOffset=""0x8a"" endOffset=""0x8c""> <constant name=""dInIf"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x8e"" endOffset=""0x90""> <constant name=""dInElse"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x91"" endOffset=""0x98""> <constant name=""dInTry"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x99"" endOffset=""0x9b""> <constant name=""dInCatch"" value=""null"" type=""Object"" /> </scope> <scope startOffset=""0x9f"" endOffset=""0xa1""> <constant name=""dInFinally"" value=""null"" type=""Object"" /> </scope> </scope> </method> </methods> </symbols>"); } [WorkItem(17947, "https://github.com/dotnet/roslyn/issues/17947")] [Fact] public void VariablesAndConstantsInUnreachableCode() { string source = WithWindowsLineBreaks(@" class C { void F() { dynamic v1 = 1; const dynamic c1 = null; throw null; dynamic v2 = 1; const dynamic c2 = null; { dynamic v3 = 1; const dynamic c3 = null; } } } "); var c = CreateCompilation(source, options: TestOptions.DebugDll); var v = CompileAndVerify(c); v.VerifyIL("C.F", @" { // Code size 10 (0xa) .maxstack 1 .locals init (object V_0, //v1 object V_1, //v2 object V_2) //v3 IL_0000: nop IL_0001: ldc.i4.1 IL_0002: box ""int"" IL_0007: stloc.0 IL_0008: ldnull IL_0009: throw }"); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""F""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""v1"" /> <bucket flags=""1"" slotId=""1"" localName=""v2"" /> <bucket flags=""1"" slotId=""0"" localName=""c1"" /> <bucket flags=""1"" slotId=""0"" localName=""c2"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""103"" /> <slot kind=""0"" offset=""181"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""24"" document=""1"" /> <entry offset=""0x8"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <local name=""v1"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v2"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <constant name=""c1"" value=""null"" type=""Object"" /> <constant name=""c2"" value=""null"" type=""Object"" /> </scope> </method> </methods> </symbols> "); } [Fact] public void EmitPDBVarVariableLocal() { string source = WithWindowsLineBreaks(@" using System; class Test { public static void Main(string[] args) { dynamic d = ""1""; var v = d; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""d"" /> <bucket flags=""1"" slotId=""1"" localName=""v"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""13"" /> <slot kind=""0"" offset=""29"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""2"" endLine=""6"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""7"" startColumn=""3"" endLine=""7"" endColumn=""19"" document=""1"" /> <entry offset=""0x7"" startLine=""8"" startColumn=""3"" endLine=""8"" endColumn=""13"" document=""1"" /> <entry offset=""0x9"" startLine=""9"" startColumn=""2"" endLine=""9"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xa""> <namespace name=""System"" /> <local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> <local name=""v"" il_index=""1"" il_start=""0x0"" il_end=""0xa"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [Fact] public void EmitPDBGenericDynamicNonLocal() { string source = WithWindowsLineBreaks(@" using System; class dynamic<T> { public T field; } class Test { public static void Main(string[] args) { dynamic<dynamic> obj = new dynamic<dynamic>(); obj.field = ""1""; } }"); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Test"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> <dynamicLocals> <bucket flags=""01"" slotId=""0"" localName=""obj"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""22"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""10"" startColumn=""2"" endLine=""10"" endColumn=""3"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""3"" endLine=""11"" endColumn=""49"" document=""1"" /> <entry offset=""0x7"" startLine=""12"" startColumn=""3"" endLine=""12"" endColumn=""19"" document=""1"" /> <entry offset=""0x12"" startLine=""13"" startColumn=""2"" endLine=""13"" endColumn=""3"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x13""> <namespace name=""System"" /> <local name=""obj"" il_index=""0"" il_start=""0x0"" il_end=""0x13"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_1() //With 2 normal dynamic locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; dynamic zzz; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""1"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""41"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_2() //With 1 normal dynamic local and 1 containing dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic> zzz; } } class Goo<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""46"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_3() //With 1 normal dynamic local and 1 containing(more than one) dynamic local { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""1"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""68"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""zzz"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_4() //With 1 normal dynamic local, 1 containing dynamic local with a normal local variable { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic yyy; int dummy = 0; Goo<dynamic, Goo<dynamic,dynamic>> zzz; } } class Goo<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""yyy"" /> <bucket flags=""01011"" slotId=""2"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""37"" /> <slot kind=""0"" offset=""92"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""23"" document=""1"" /> <entry offset=""0x3"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x4""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yyy"" il_index=""0"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""dummy"" il_index=""1"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> <local name=""zzz"" il_index=""2"" il_start=""0x0"" il_end=""0x4"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_5_Just_Long() //Dynamic local with dynamic attribute of length 63 above which the flag is emitted empty { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""010101010101010101010101010101010101010101010101010101010101011"" slotId=""0"" localName=""zzz"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""361"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_6_Too_Long() //The limitation of the previous testcase with dynamic attribute length 64 and not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zzz; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""zzz"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_7() //Corner case dynamic locals with normal locals { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z1; int dummy1 = 0; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z2; F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; int dummy2 = 0; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""389"" /> <slot kind=""0"" offset=""771"" /> <slot kind=""0"" offset=""1145"" /> <slot kind=""0"" offset=""1162"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""24"" document=""1"" /> <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""24"" document=""1"" /> <entry offset=""0x6"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x7""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z1"" il_index=""0"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy1"" il_index=""1"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z2"" il_index=""2"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""z3"" il_index=""3"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> <local name=""dummy2"" il_index=""4"" il_start=""0x0"" il_end=""0x7"" attributes=""0"" /> </scope> </method> </methods> </symbols> "); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_8_Mixed_Corner_Cases() //Mixed case with one more limitation. If identifier length is greater than 63 then the info is not emitted { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<dynamic, F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,F<dynamic,dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> z3; dynamic www; dynamic length63length63length63length63length63length63length63length6; dynamic length64length64length64length64length64length64length64length64; } } class F<T,V> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""1"" localName=""www"" /> <bucket flags=""1"" slotId=""2"" localName=""length63length63length63length63length63length63length63length6"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""372"" /> <slot kind=""0"" offset=""393"" /> <slot kind=""0"" offset=""415"" /> <slot kind=""0"" offset=""497"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""z3"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length63length63length63length63length63length63length63length6"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""length64length64length64length64length64length64length64length64"" il_index=""3"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_9() //Check corner case with only corner cases { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> yes; F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<F<dynamic>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> no; dynamic www; } } class F<T> { } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""0000000000000000000000000000000000000000000000000000000000000001"" slotId=""0"" localName=""yes"" /> <bucket flags=""1"" slotId=""2"" localName=""www"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""208"" /> <slot kind=""0"" offset=""422"" /> <slot kind=""0"" offset=""443"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""yes"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""no"" il_index=""1"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> <local name=""www"" il_index=""2"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(17390, "DevDiv_Projects/Roslyn")] [Fact] public void EmitPDBForDynamicLocals_TwoScope() { string source = WithWindowsLineBreaks(@" using System; using System.Collections.Generic; class Program { static void Main(string[] args) { dynamic simple; for(int x =0 ; x < 10 ; ++x) { dynamic inner; } } static void nothing(dynamic localArg) { dynamic localInner; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll); c.VerifyPdb(@"<symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""Program"" name=""Main"" parameterNames=""args""> <customDebugInfo> <using> <namespace usingCount=""2"" /> </using> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""simple"" /> <bucket flags=""1"" slotId=""2"" localName=""inner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> <slot kind=""0"" offset=""44"" /> <slot kind=""0"" offset=""84"" /> <slot kind=""1"" offset=""36"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""9"" startColumn=""13"" endLine=""9"" endColumn=""21"" document=""1"" /> <entry offset=""0x3"" hidden=""true"" document=""1"" /> <entry offset=""0x5"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" document=""1"" /> <entry offset=""0x6"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""27"" document=""1"" /> <entry offset=""0x7"" startLine=""9"" startColumn=""33"" endLine=""9"" endColumn=""36"" document=""1"" /> <entry offset=""0xb"" startLine=""9"" startColumn=""24"" endLine=""9"" endColumn=""30"" document=""1"" /> <entry offset=""0x11"" hidden=""true"" document=""1"" /> <entry offset=""0x14"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x15""> <namespace name=""System"" /> <namespace name=""System.Collections.Generic"" /> <local name=""simple"" il_index=""0"" il_start=""0x0"" il_end=""0x15"" attributes=""0"" /> <scope startOffset=""0x1"" endOffset=""0x14""> <local name=""x"" il_index=""1"" il_start=""0x1"" il_end=""0x14"" attributes=""0"" /> <scope startOffset=""0x5"" endOffset=""0x7""> <local name=""inner"" il_index=""2"" il_start=""0x5"" il_end=""0x7"" attributes=""0"" /> </scope> </scope> </scope> </method> <method containingType=""Program"" name=""nothing"" parameterNames=""localArg""> <customDebugInfo> <forward declaringType=""Program"" methodName=""Main"" parameterNames=""args"" /> <dynamicLocals> <bucket flags=""1"" slotId=""0"" localName=""localInner"" /> </dynamicLocals> <encLocalSlotMap> <slot kind=""0"" offset=""19"" /> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""16"" startColumn=""5"" endLine=""16"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <local name=""localInner"" il_index=""0"" il_start=""0x0"" il_end=""0x2"" attributes=""0"" /> </scope> </method> </methods> </symbols>"); } [WorkItem(637465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/637465")] [Fact] public void DynamicLocalOptimizedAway() { string source = WithWindowsLineBreaks(@" class C { public static void Main() { dynamic d = GetDynamic(); } static dynamic GetDynamic() { throw null; } } "); var c = CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.ReleaseDll); c.VerifyPdb(@" <symbols> <files> <file id=""1"" name="""" language=""C#"" /> </files> <methods> <method containingType=""C"" name=""Main""> <customDebugInfo> <using> <namespace usingCount=""0"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""34"" document=""1"" /> <entry offset=""0x6"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method containingType=""C"" name=""GetDynamic""> <customDebugInfo> <forward declaringType=""C"" methodName=""Main"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""20"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/VisualStudio/VisualBasic/Impl/CodeModel/Extenders/ExtenderNames.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Friend Module ExtenderNames Public Const ExternalLocation As String = "ExternalLocation" Public Const VBAutoPropertyExtender As String = "VBAutoPropertyExtender" Public Const VBGenericExtender As String = "VBGenericExtender" Public Const VBPartialMethodExtender As String = "VBPartialMethodExtender" End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Friend Module ExtenderNames Public Const ExternalLocation As String = "ExternalLocation" Public Const VBAutoPropertyExtender As String = "VBAutoPropertyExtender" Public Const VBGenericExtender As String = "VBGenericExtender" Public Const VBPartialMethodExtender As String = "VBPartialMethodExtender" End Module End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/VisualBasic/Portable/EmbeddedLanguages/VisualBasicEmbeddedLanguageFeaturesProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices Imports Microsoft.CodeAnalysis.Features.EmbeddedLanguages Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.Features.EmbeddedLanguages <ExportLanguageService(GetType(IEmbeddedLanguagesProvider), LanguageNames.VisualBasic, ServiceLayer.Desktop), [Shared]> Friend Class VisualBasicEmbeddedLanguageFeaturesProvider Inherits AbstractEmbeddedLanguageFeaturesProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(VisualBasicEmbeddedLanguagesProvider.Info) End Sub Friend Overrides Function EscapeText(text As String, token As SyntaxToken) As String Return EmbeddedLanguageUtilities.EscapeText(text) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices Imports Microsoft.CodeAnalysis.Features.EmbeddedLanguages Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.VisualBasic.EmbeddedLanguages.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.Features.EmbeddedLanguages <ExportLanguageService(GetType(IEmbeddedLanguagesProvider), LanguageNames.VisualBasic, ServiceLayer.Desktop), [Shared]> Friend Class VisualBasicEmbeddedLanguageFeaturesProvider Inherits AbstractEmbeddedLanguageFeaturesProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(VisualBasicEmbeddedLanguagesProvider.Info) End Sub Friend Overrides Function EscapeText(text As String, token As SyntaxToken) As String Return EmbeddedLanguageUtilities.EscapeText(text) End Function End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/IfKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public IfKeywordRecommender() : base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsPreProcessorKeywordContext || context.IsStatementContext || context.IsGlobalStatementContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class IfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public IfKeywordRecommender() : base(SyntaxKind.IfKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsPreProcessorKeywordContext || context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal static class ActiveStatementTestHelpers { public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp( string[] markedSources, string[]? filePaths = null, int[]? methodRowIds = null, Guid[]? modules = null, int[]? methodVersions = null, int[]? ilOffsets = null, ActiveStatementFlags[]? flags = null) { return ActiveStatementsDescription.GetActiveStatementDebugInfos( (source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path), markedSources, filePaths, extension: ".cs", methodRowIds, modules, methodVersions, ilOffsets, flags); } public static string Delete(string src, string marker) { while (true) { var startStr = "/*delete" + marker; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length; src = src.Substring(0, start) + src.Substring(end); } } /// <summary> /// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/. /// </summary> public static string InsertNewLines(string src, string marker) { while (true) { var startStr = "/*insert" + marker + "["; var endStr = "*/"; var start = src.IndexOf(startStr); if (start == -1) { return src; } var startOfLineCount = start + startStr.Length; var endOfLineCount = src.IndexOf(']', startOfLineCount); var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount)); var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length; src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end); } } public static string Update(string src, string marker) => InsertNewLines(Delete(src, marker), marker); public static string InspectActiveStatement(ActiveStatement statement) => $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]"; public static string InspectActiveStatementAndInstruction(ActiveStatement statement) => InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay(); public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text) => InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'"; public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update) => $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}"; public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions) => regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}"); public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r) => $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}"; public static string GetFirstLineText(LinePositionSpan span, SourceText text) => text.Lines[span.Start.Line].ToString().Trim(); public static string InspectSequencePointUpdates(SequencePointUpdates updates) => $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]"; public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates) => updates.Select(InspectSequencePointUpdates); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.LazySyntaxTree.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree Private NotInheritable Class LazySyntaxTree Inherits VisualBasicSyntaxTree Private ReadOnly _text As SourceText Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _path As String Private ReadOnly _diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Private _lazyRoot As VisualBasicSyntaxNode ''' <summary> ''' Used to create new tree incrementally. ''' </summary> Friend Sub New(text As SourceText, options As VisualBasicParseOptions, path As String, diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic)) Debug.Assert(options IsNot Nothing) _text = text _options = options _path = If(path, String.Empty) _diagnosticOptions = If(diagnosticOptions, EmptyDiagnosticOptions) End Sub Public Overrides ReadOnly Property FilePath As String Get Return _path End Get End Property Friend Overrides ReadOnly Property IsMyTemplate As Boolean Get Return False End Get End Property Public Overrides Function GetText(Optional cancellationToken As CancellationToken = Nothing) As SourceText Return _text End Function Public Overrides Function TryGetText(ByRef text As SourceText) As Boolean text = _text Return True End Function Public Overrides ReadOnly Property Encoding As Encoding Get Return _text.Encoding End Get End Property Public Overrides ReadOnly Property Length As Integer Get Return _text.Length End Get End Property Public Overrides Function GetRoot(Optional cancellationToken As CancellationToken = Nothing) As VisualBasicSyntaxNode If _lazyRoot Is Nothing Then ' Parse the syntax tree Dim tree = SyntaxFactory.ParseSyntaxTree(_text, _options, _path, cancellationToken) Dim root = CloneNodeAsRoot(CType(tree.GetRoot(cancellationToken), VisualBasicSyntaxNode)) Interlocked.CompareExchange(_lazyRoot, root, Nothing) End If Return _lazyRoot End Function Public Overrides Function TryGetRoot(ByRef root As VisualBasicSyntaxNode) As Boolean root = _lazyRoot Return root IsNot Nothing End Function Public Overrides ReadOnly Property HasCompilationUnitRoot As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Public Overrides ReadOnly Property DiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Get Return _diagnosticOptions End Get End Property ''' <summary> ''' Get a reference to the given node. ''' </summary> Public Overrides Function GetReference(node As SyntaxNode) As SyntaxReference Return New SimpleSyntaxReference(Me, node) End Function Public Overrides Function WithRootAndOptions(root As SyntaxNode, options As ParseOptions) As SyntaxTree If _lazyRoot Is root AndAlso _options Is options Then Return Me End If Return New ParsedSyntaxTree( Nothing, _text.Encoding, _text.ChecksumAlgorithm, _path, DirectCast(options, VisualBasicParseOptions), DirectCast(root, VisualBasicSyntaxNode), isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithFilePath(path As String) As SyntaxTree If String.Equals(Me._path, path) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, path, _options, root, isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, path, _diagnosticOptions) End If End Function Public Overrides Function WithDiagnosticOptions(options As ImmutableDictionary(Of String, ReportDiagnostic)) As SyntaxTree If options Is Nothing Then options = EmptyDiagnosticOptions End If If ReferenceEquals(_diagnosticOptions, options) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, _path, _options, root, isMyTemplate:=False, options, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, _path, options) End If End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree Private NotInheritable Class LazySyntaxTree Inherits VisualBasicSyntaxTree Private ReadOnly _text As SourceText Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _path As String Private ReadOnly _diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Private _lazyRoot As VisualBasicSyntaxNode ''' <summary> ''' Used to create new tree incrementally. ''' </summary> Friend Sub New(text As SourceText, options As VisualBasicParseOptions, path As String, diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic)) Debug.Assert(options IsNot Nothing) _text = text _options = options _path = If(path, String.Empty) _diagnosticOptions = If(diagnosticOptions, EmptyDiagnosticOptions) End Sub Public Overrides ReadOnly Property FilePath As String Get Return _path End Get End Property Friend Overrides ReadOnly Property IsMyTemplate As Boolean Get Return False End Get End Property Public Overrides Function GetText(Optional cancellationToken As CancellationToken = Nothing) As SourceText Return _text End Function Public Overrides Function TryGetText(ByRef text As SourceText) As Boolean text = _text Return True End Function Public Overrides ReadOnly Property Encoding As Encoding Get Return _text.Encoding End Get End Property Public Overrides ReadOnly Property Length As Integer Get Return _text.Length End Get End Property Public Overrides Function GetRoot(Optional cancellationToken As CancellationToken = Nothing) As VisualBasicSyntaxNode If _lazyRoot Is Nothing Then ' Parse the syntax tree Dim tree = SyntaxFactory.ParseSyntaxTree(_text, _options, _path, cancellationToken) Dim root = CloneNodeAsRoot(CType(tree.GetRoot(cancellationToken), VisualBasicSyntaxNode)) Interlocked.CompareExchange(_lazyRoot, root, Nothing) End If Return _lazyRoot End Function Public Overrides Function TryGetRoot(ByRef root As VisualBasicSyntaxNode) As Boolean root = _lazyRoot Return root IsNot Nothing End Function Public Overrides ReadOnly Property HasCompilationUnitRoot As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Public Overrides ReadOnly Property DiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Get Return _diagnosticOptions End Get End Property ''' <summary> ''' Get a reference to the given node. ''' </summary> Public Overrides Function GetReference(node As SyntaxNode) As SyntaxReference Return New SimpleSyntaxReference(Me, node) End Function Public Overrides Function WithRootAndOptions(root As SyntaxNode, options As ParseOptions) As SyntaxTree If _lazyRoot Is root AndAlso _options Is options Then Return Me End If Return New ParsedSyntaxTree( Nothing, _text.Encoding, _text.ChecksumAlgorithm, _path, DirectCast(options, VisualBasicParseOptions), DirectCast(root, VisualBasicSyntaxNode), isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithFilePath(path As String) As SyntaxTree If String.Equals(Me._path, path) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, path, _options, root, isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, path, _diagnosticOptions) End If End Function Public Overrides Function WithDiagnosticOptions(options As ImmutableDictionary(Of String, ReportDiagnostic)) As SyntaxTree If options Is Nothing Then options = EmptyDiagnosticOptions End If If ReferenceEquals(_diagnosticOptions, options) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, _path, _options, root, isMyTemplate:=False, options, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, _path, options) End If End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ModifierKeywordRecommenderTests.InsideModuleDeclaration.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideModuleDeclaration Inherits RecommenderTests <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DefaultNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Default") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Narrowing") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overloads") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overrides") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shadows") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shared") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Widening") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Partial") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterPrivateTest() VerifyRecommendationsContain(<ModuleDeclaration>Private |</ModuleDeclaration>, "Partial") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideModuleDeclaration Inherits RecommenderTests <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DefaultNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Default") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Narrowing") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overloads") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overrides") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shadows") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shared") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Widening") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Partial") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterPrivateTest() VerifyRecommendationsContain(<ModuleDeclaration>Private |</ModuleDeclaration>, "Partial") End Sub End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationConstructorInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationConstructorInfo { private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationConstructorInfo> s_constructorToInfoMap = new(); private readonly bool _isPrimaryConstructor; private readonly bool _isUnsafe; private readonly string _typeName; private readonly ImmutableArray<SyntaxNode> _baseConstructorArguments; private readonly ImmutableArray<SyntaxNode> _thisConstructorArguments; private readonly ImmutableArray<SyntaxNode> _statements; private CodeGenerationConstructorInfo( bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { _isPrimaryConstructor = isPrimaryConstructor; _isUnsafe = isUnsafe; _typeName = typeName; _statements = statements; _baseConstructorArguments = baseConstructorArguments; _thisConstructorArguments = thisConstructorArguments; } public static void Attach( IMethodSymbol constructor, bool isPrimaryConstructor, bool isUnsafe, string typeName, ImmutableArray<SyntaxNode> statements, ImmutableArray<SyntaxNode> baseConstructorArguments, ImmutableArray<SyntaxNode> thisConstructorArguments) { var info = new CodeGenerationConstructorInfo(isPrimaryConstructor, isUnsafe, typeName, statements, baseConstructorArguments, thisConstructorArguments); s_constructorToInfoMap.Add(constructor, info); } private static CodeGenerationConstructorInfo? GetInfo(IMethodSymbol method) { s_constructorToInfoMap.TryGetValue(method, out var info); return info; } public static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(IMethodSymbol constructor) => GetThisConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(IMethodSymbol constructor) => GetBaseConstructorArgumentsOpt(GetInfo(constructor)); public static ImmutableArray<SyntaxNode> GetStatements(IMethodSymbol constructor) => GetStatements(GetInfo(constructor)); public static string GetTypeName(IMethodSymbol constructor) => GetTypeName(GetInfo(constructor), constructor); public static bool GetIsUnsafe(IMethodSymbol constructor) => GetIsUnsafe(GetInfo(constructor)); public static bool GetIsPrimaryConstructor(IMethodSymbol constructor) => GetIsPrimaryConstructor(GetInfo(constructor)); private static ImmutableArray<SyntaxNode> GetThisConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._thisConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetBaseConstructorArgumentsOpt(CodeGenerationConstructorInfo? info) => info?._baseConstructorArguments ?? default; private static ImmutableArray<SyntaxNode> GetStatements(CodeGenerationConstructorInfo? info) => info?._statements ?? default; private static string GetTypeName(CodeGenerationConstructorInfo? info, IMethodSymbol constructor) => info == null ? constructor.ContainingType.Name : info._typeName; private static bool GetIsUnsafe(CodeGenerationConstructorInfo? info) => info?._isUnsafe ?? false; private static bool GetIsPrimaryConstructor(CodeGenerationConstructorInfo? info) => info?._isPrimaryConstructor ?? false; } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/VisualBasicTest/Recommendations/RecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations ''' <summary> ''' Base class for all recommender tests. ''' </summary> <UseExportProvider> Public MustInherit Class RecommenderTests End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations ''' <summary> ''' Base class for all recommender tests. ''' </summary> <UseExportProvider> Public MustInherit Class RecommenderTests End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/Core/Portable/ExtractInterface/TypeDiscoveryRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.ExtractInterface { internal enum TypeDiscoveryRule { TypeDeclaration, TypeNameOnly } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.ExtractInterface { internal enum TypeDiscoveryRule { TypeDeclaration, TypeNameOnly } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/LanguageServer/ProtocolUnitTests/Definitions/GoToTypeDefinitionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToTypeDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoTypeDefinitionAsync() { var markup = @"class {|definition:A|} { } class B { {|caret:|}A classA; }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class {|definition:A|} { } }", @"namespace One { class B { {|caret:|}A classA; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_InvalidLocation() { var markup = @"class {|definition:A|} { } class B { A classA; {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoTypeDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentTypeDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToTypeDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoTypeDefinitionAsync() { var markup = @"class {|definition:A|} { } class B { {|caret:|}A classA; }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class {|definition:A|} { } }", @"namespace One { class B { {|caret:|}A classA; } }" }; using var testLspServer = CreateTestLspServer(markups, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoTypeDefinitionAsync_InvalidLocation() { var markup = @"class {|definition:A|} { } class B { A classA; {|caret:|} }"; using var testLspServer = CreateTestLspServer(markup, out var locations); var results = await RunGotoTypeDefinitionAsync(testLspServer, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoTypeDefinitionAsync(TestLspServer testLspServer, LSP.Location caret) { return await testLspServer.ExecuteRequestAsync<LSP.TextDocumentPositionParams, LSP.Location[]>(LSP.Methods.TextDocumentTypeDefinitionName, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), null, CancellationToken.None); } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Features/CSharp/Portable/xlf/CSharpFeaturesResources.pl.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">Dodaj operator „await”</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">Dodaj elementy „await” i „ConfigureAwait(false)”</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">Dodaj brakujące instrukcje using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">Dodaj/usuń nawiasy klamrowe w przypadku jednowierszowych instrukcji sterowania</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">Zezwalaj na niebezpieczny kod w tym projekcie</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">Zastosuj preferencje treści wyrażenia/bloku</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">Zastosuj preferencje niejawnego/jawnego typu</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">Zastosuj preferencje wstawionych zmiennych „out”</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">Zastosuj preferencje typu języka/platformy</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">Zastosuj preferencje kwalifikacji „this.”</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">Zastosuj preferowane preferencje umieszczania elementu „using”</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">Przypisz parametry „out”</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">Przypisz parametry „out” (na początku)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">Przypisz do „{0}”</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">Automatyczne wybieranie zostało wyłączone z powodu możliwej deklaracji zmiennej wzorca.</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">Zmień na wyrażenie „as”</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">Zmień na rzutowanie</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">Porównaj z „{0}”</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">Konwertuj na metodę</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">Konwertuj na zwykły ciąg</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">Konwertuj na wyrażenie „switch”</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">Konwertuj na instrukcję „switch”</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">Konwertuj na ciąg dosłowny</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Zadeklaruj jako dopuszczający wartość null</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">Napraw zwracany typ</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">Wstawiona zmienna tymczasowa</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">Wykryto konflikty.</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">Ustawiaj pola prywatne jako tylko do odczytu, gdy to możliwe</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">Ustaw jako „ref struct”</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">Usuń słowo kluczowe „in”</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">Usuń modyfikator „new”</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">Odwróć instrukcję „for”</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">Uprość wyrażenie lambda</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">Uprość wszystkie wystąpienia</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Sortuj modyfikatory dostępności</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Odpieczętuj klasę „{0}”</target> <note /> </trans-unit> <trans-unit id="Use_recursive_patterns"> <source>Use recursive patterns</source> <target state="translated">Używanie wzorców rekursywnych</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">Ostrzeżenie: tymczasowe wbudowywanie do wywołania metody warunkowej.</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">Ostrzeżenie: śródwierszowe użycie zmiennej tymczasowej może zmienić znaczenie kodu.</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">asynchroniczna instrukcja foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">asynchroniczna deklaracja using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">alias zewnętrzny</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;wyrażenie lambda&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu możliwej deklaracji lambda.</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">deklaracja zmiennej lokalnej</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;nazwa składowej&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu możliwego utworzenia jawnie nazwanej anonimowej składowej typu.</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;nazwa elementu&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">Funkcja automatycznego wyboru została wyłączona ze względu na prawdopodobne utworzenie elementu typu krotki.</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;zmienna wzorca&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;zmienna zakresu&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu możliwej deklaracji zmiennej zakresu.</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">Uprość nazwę „{0}”</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">Uprość dostęp do składowej „{0}”</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">Usuń kwalifikację „this”</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">Nazwę można uprościć</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">Nie można określić prawidłowego zakresu instrukcji do wyodrębnienia</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">Nie wszystkie ścieżki w kodzie zwracają wartość</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">Zaznaczenie nie zawiera prawidłowego węzła</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">Nieprawidłowe zaznaczenie.</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">Zawiera nieprawidłowe zaznaczenie.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">Zaznaczenie zawiera błędy składni</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">Zaznaczenie nie może zawierać dyrektyw preprocesora.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">Zaznaczenie nie może zawierać instrukcji yield.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">Zaznaczenie nie może zawierać instrukcji throw.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">Zaznaczenie nie może być częścią wyrażenia inicjatora stałej.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">Wybór nie może zawierać wyrażenia wzorca.</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">Zaznaczony kod znajduje się w niebezpiecznym kontekście.</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">Brak prawidłowego zakresu instrukcji do wyodrębnienia</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">przestarzałe</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">rozszerzenie</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">oczekujący</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">oczekujący, rozszerzenie</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">Organizuj użycia</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">Wstaw element „await”.</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">Ustaw element {0}, aby zwracał zadanie zamiast elementu void.</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">Zmień zwracany typ z {0} na {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">Zamień instrukcję return na instrukcję yield return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">Generuj operator jawnej konwersji w elemencie „{0}”</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">Generuj operator niejawnej konwersji w elemencie „{0}”</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">rekord</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="translated">struktura rekordów</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">instrukcja switch</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">klauzula case instrukcji switch</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">blok try</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">klauzula catch</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">klauzula filter</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">klauzula finally</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">instrukcja fixed</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">deklaracja using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">instrukcja using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">instrukcja lock</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">instrukcja foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">instrukcja checked</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">instrukcja unchecked</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">wyrażenie await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">metoda anonimowa</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">klauzula from</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">klauzula join</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">klauzula let</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">klauzula where</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">klauzula orderby</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">klauzula select</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">klauzula groupby</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">treść zapytania</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">klauzula into</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">wzorzec is</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">dekonstrukcja</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">krotka</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">funkcja lokalna</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">zmienna „out”</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">ref — lokalna zmienna lub wyrażenie</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">instrukcja global</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">dyrektywa using</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">pole event</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">operator konwersji</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">destruktor</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">indeksator</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">metoda pobierająca właściwości</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">metoda pobierająca indeksatora</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">metoda ustawiająca właściwości</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">metoda ustawiająca indeksatora</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">cel atrybutu</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">'Element „{0}” nie zawiera konstruktora, który przyjmuje wiele argumentów.</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">Nazwa „{0}” nie istnieje w bieżącym kontekście.</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">Ukryj składową bazową</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Właściwości</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu deklaracji przestrzeni nazw.</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;nazwa przestrzeni nazw&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">Funkcja automatycznego wybierania została wyłączona z powodu deklaracji typu.</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">Automatyczne wybieranie jest wyłączone z powodu możliwej deklaracji dekonstrukcji.</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">Uaktualnij ten projekt do wersji „{0}” języka C#</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">Uaktualnij wszystkie projekty C# do wersji „{0}” języka</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;nazwa klasy&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;nazwa interfejsu&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;nazwa oznaczenia&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;nazwa struktury&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">Ustaw metodę jako asynchroniczną</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">Ustaw metodę jako asynchroniczną (pozostaw jako unieważnioną)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;Nazwa&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">Funkcja automatycznego wybierania została wyłączona z powodu deklaracji składowej</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(Sugerowana nazwa)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">Usuń nieużywaną funkcję</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">Dodaj nawiasy</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">Konwertuj na wyrażenie „foreach”</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">Konwertuj na wyrażenie „for”</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">Odwróć instrukcję if</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">Dodaj [przestarzałe]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">Użyj elementu „{0}”</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">Wprowadź instrukcję „using”</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">instrukcja yield break</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">instrukcja yield return</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../CSharpFeaturesResources.resx"> <body> <trans-unit id="Add_await"> <source>Add 'await'</source> <target state="translated">Dodaj operator „await”</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_await_and_ConfigureAwaitFalse"> <source>Add 'await' and 'ConfigureAwait(false)'</source> <target state="translated">Dodaj elementy „await” i „ConfigureAwait(false)”</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_missing_usings"> <source>Add missing usings</source> <target state="translated">Dodaj brakujące instrukcje using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Add_remove_braces_for_single_line_control_statements"> <source>Add/remove braces for single-line control statements</source> <target state="translated">Dodaj/usuń nawiasy klamrowe w przypadku jednowierszowych instrukcji sterowania</target> <note /> </trans-unit> <trans-unit id="Allow_unsafe_code_in_this_project"> <source>Allow unsafe code in this project</source> <target state="translated">Zezwalaj na niebezpieczny kod w tym projekcie</target> <note /> </trans-unit> <trans-unit id="Apply_expression_block_body_preferences"> <source>Apply expression/block body preferences</source> <target state="translated">Zastosuj preferencje treści wyrażenia/bloku</target> <note /> </trans-unit> <trans-unit id="Apply_implicit_explicit_type_preferences"> <source>Apply implicit/explicit type preferences</source> <target state="translated">Zastosuj preferencje niejawnego/jawnego typu</target> <note /> </trans-unit> <trans-unit id="Apply_inline_out_variable_preferences"> <source>Apply inline 'out' variables preferences</source> <target state="translated">Zastosuj preferencje wstawionych zmiennych „out”</target> <note /> </trans-unit> <trans-unit id="Apply_language_framework_type_preferences"> <source>Apply language/framework type preferences</source> <target state="translated">Zastosuj preferencje typu języka/platformy</target> <note /> </trans-unit> <trans-unit id="Apply_this_qualification_preferences"> <source>Apply 'this.' qualification preferences</source> <target state="translated">Zastosuj preferencje kwalifikacji „this.”</target> <note /> </trans-unit> <trans-unit id="Apply_using_directive_placement_preferences"> <source>Apply preferred 'using' placement preferences</source> <target state="translated">Zastosuj preferowane preferencje umieszczania elementu „using”</target> <note>'using' is a C# keyword and should not be localized</note> </trans-unit> <trans-unit id="Assign_out_parameters"> <source>Assign 'out' parameters</source> <target state="translated">Przypisz parametry „out”</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_out_parameters_at_start"> <source>Assign 'out' parameters (at start)</source> <target state="translated">Przypisz parametry „out” (na początku)</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Assign_to_0"> <source>Assign to '{0}'</source> <target state="translated">Przypisz do „{0}”</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_pattern_variable_declaration"> <source>Autoselect disabled due to potential pattern variable declaration.</source> <target state="translated">Automatyczne wybieranie zostało wyłączone z powodu możliwej deklaracji zmiennej wzorca.</target> <note /> </trans-unit> <trans-unit id="Change_to_as_expression"> <source>Change to 'as' expression</source> <target state="translated">Zmień na wyrażenie „as”</target> <note /> </trans-unit> <trans-unit id="Change_to_cast"> <source>Change to cast</source> <target state="translated">Zmień na rzutowanie</target> <note /> </trans-unit> <trans-unit id="Compare_to_0"> <source>Compare to '{0}'</source> <target state="translated">Porównaj z „{0}”</target> <note /> </trans-unit> <trans-unit id="Convert_to_method"> <source>Convert to method</source> <target state="translated">Konwertuj na metodę</target> <note /> </trans-unit> <trans-unit id="Convert_to_regular_string"> <source>Convert to regular string</source> <target state="translated">Konwertuj na zwykły ciąg</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_expression"> <source>Convert to 'switch' expression</source> <target state="translated">Konwertuj na wyrażenie „switch”</target> <note /> </trans-unit> <trans-unit id="Convert_to_switch_statement"> <source>Convert to 'switch' statement</source> <target state="translated">Konwertuj na instrukcję „switch”</target> <note /> </trans-unit> <trans-unit id="Convert_to_verbatim_string"> <source>Convert to verbatim string</source> <target state="translated">Konwertuj na ciąg dosłowny</target> <note /> </trans-unit> <trans-unit id="Declare_as_nullable"> <source>Declare as nullable</source> <target state="translated">Zadeklaruj jako dopuszczający wartość null</target> <note /> </trans-unit> <trans-unit id="Fix_return_type"> <source>Fix return type</source> <target state="translated">Napraw zwracany typ</target> <note /> </trans-unit> <trans-unit id="Inline_temporary_variable"> <source>Inline temporary variable</source> <target state="translated">Wstawiona zmienna tymczasowa</target> <note /> </trans-unit> <trans-unit id="Conflict_s_detected"> <source>Conflict(s) detected.</source> <target state="translated">Wykryto konflikty.</target> <note /> </trans-unit> <trans-unit id="Make_private_field_readonly_when_possible"> <source>Make private fields readonly when possible</source> <target state="translated">Ustawiaj pola prywatne jako tylko do odczytu, gdy to możliwe</target> <note /> </trans-unit> <trans-unit id="Make_ref_struct"> <source>Make 'ref struct'</source> <target state="translated">Ustaw jako „ref struct”</target> <note>{Locked="ref"}{Locked="struct"} "ref" and "struct" are C# keywords and should not be localized.</note> </trans-unit> <trans-unit id="Remove_in_keyword"> <source>Remove 'in' keyword</source> <target state="translated">Usuń słowo kluczowe „in”</target> <note>{Locked="in"} "in" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Remove_new_modifier"> <source>Remove 'new' modifier</source> <target state="translated">Usuń modyfikator „new”</target> <note /> </trans-unit> <trans-unit id="Reverse_for_statement"> <source>Reverse 'for' statement</source> <target state="translated">Odwróć instrukcję „for”</target> <note>{Locked="for"} "for" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="Simplify_lambda_expression"> <source>Simplify lambda expression</source> <target state="translated">Uprość wyrażenie lambda</target> <note /> </trans-unit> <trans-unit id="Simplify_all_occurrences"> <source>Simplify all occurrences</source> <target state="translated">Uprość wszystkie wystąpienia</target> <note /> </trans-unit> <trans-unit id="Sort_accessibility_modifiers"> <source>Sort accessibility modifiers</source> <target state="translated">Sortuj modyfikatory dostępności</target> <note /> </trans-unit> <trans-unit id="Unseal_class_0"> <source>Unseal class '{0}'</source> <target state="translated">Odpieczętuj klasę „{0}”</target> <note /> </trans-unit> <trans-unit id="Use_recursive_patterns"> <source>Use recursive patterns</source> <target state="translated">Używanie wzorców rekursywnych</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_into_conditional_method_call"> <source>Warning: Inlining temporary into conditional method call.</source> <target state="translated">Ostrzeżenie: tymczasowe wbudowywanie do wywołania metody warunkowej.</target> <note /> </trans-unit> <trans-unit id="Warning_Inlining_temporary_variable_may_change_code_meaning"> <source>Warning: Inlining temporary variable may change code meaning.</source> <target state="translated">Ostrzeżenie: śródwierszowe użycie zmiennej tymczasowej może zmienić znaczenie kodu.</target> <note /> </trans-unit> <trans-unit id="asynchronous_foreach_statement"> <source>asynchronous foreach statement</source> <target state="translated">asynchroniczna instrukcja foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="asynchronous_using_declaration"> <source>asynchronous using declaration</source> <target state="translated">asynchroniczna deklaracja using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="extern_alias"> <source>extern alias</source> <target state="translated">alias zewnętrzny</target> <note /> </trans-unit> <trans-unit id="lambda_expression"> <source>&lt;lambda expression&gt;</source> <target state="translated">&lt;wyrażenie lambda&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_lambda_declaration"> <source>Autoselect disabled due to potential lambda declaration.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu możliwej deklaracji lambda.</target> <note /> </trans-unit> <trans-unit id="local_variable_declaration"> <source>local variable declaration</source> <target state="translated">deklaracja zmiennej lokalnej</target> <note /> </trans-unit> <trans-unit id="member_name"> <source>&lt;member name&gt; = </source> <target state="translated">&lt;nazwa składowej&gt; =</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_explicitly_named_anonymous_type_member_creation"> <source>Autoselect disabled due to possible explicitly named anonymous type member creation.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu możliwego utworzenia jawnie nazwanej anonimowej składowej typu.</target> <note /> </trans-unit> <trans-unit id="element_name"> <source>&lt;element name&gt; : </source> <target state="translated">&lt;nazwa elementu&gt;:</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_tuple_type_element_creation"> <source>Autoselect disabled due to possible tuple type element creation.</source> <target state="translated">Funkcja automatycznego wyboru została wyłączona ze względu na prawdopodobne utworzenie elementu typu krotki.</target> <note /> </trans-unit> <trans-unit id="pattern_variable"> <source>&lt;pattern variable&gt;</source> <target state="translated">&lt;zmienna wzorca&gt;</target> <note /> </trans-unit> <trans-unit id="range_variable"> <source>&lt;range variable&gt;</source> <target state="translated">&lt;zmienna zakresu&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_potential_range_variable_declaration"> <source>Autoselect disabled due to potential range variable declaration.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu możliwej deklaracji zmiennej zakresu.</target> <note /> </trans-unit> <trans-unit id="Simplify_name_0"> <source>Simplify name '{0}'</source> <target state="translated">Uprość nazwę „{0}”</target> <note /> </trans-unit> <trans-unit id="Simplify_member_access_0"> <source>Simplify member access '{0}'</source> <target state="translated">Uprość dostęp do składowej „{0}”</target> <note /> </trans-unit> <trans-unit id="Remove_this_qualification"> <source>Remove 'this' qualification</source> <target state="translated">Usuń kwalifikację „this”</target> <note /> </trans-unit> <trans-unit id="Name_can_be_simplified"> <source>Name can be simplified</source> <target state="translated">Nazwę można uprościć</target> <note /> </trans-unit> <trans-unit id="Can_t_determine_valid_range_of_statements_to_extract"> <source>Can't determine valid range of statements to extract</source> <target state="translated">Nie można określić prawidłowego zakresu instrukcji do wyodrębnienia</target> <note /> </trans-unit> <trans-unit id="Not_all_code_paths_return"> <source>Not all code paths return</source> <target state="translated">Nie wszystkie ścieżki w kodzie zwracają wartość</target> <note /> </trans-unit> <trans-unit id="Selection_does_not_contain_a_valid_node"> <source>Selection does not contain a valid node</source> <target state="translated">Zaznaczenie nie zawiera prawidłowego węzła</target> <note /> </trans-unit> <trans-unit id="Invalid_selection"> <source>Invalid selection.</source> <target state="translated">Nieprawidłowe zaznaczenie.</target> <note /> </trans-unit> <trans-unit id="Contains_invalid_selection"> <source>Contains invalid selection.</source> <target state="translated">Zawiera nieprawidłowe zaznaczenie.</target> <note /> </trans-unit> <trans-unit id="The_selection_contains_syntactic_errors"> <source>The selection contains syntactic errors</source> <target state="translated">Zaznaczenie zawiera błędy składni</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_cross_over_preprocessor_directives"> <source>Selection can not cross over preprocessor directives.</source> <target state="translated">Zaznaczenie nie może zawierać dyrektyw preprocesora.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_yield_statement"> <source>Selection can not contain a yield statement.</source> <target state="translated">Zaznaczenie nie może zawierać instrukcji yield.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_throw_statement"> <source>Selection can not contain throw statement.</source> <target state="translated">Zaznaczenie nie może zawierać instrukcji throw.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_be_part_of_constant_initializer_expression"> <source>Selection can not be part of constant initializer expression.</source> <target state="translated">Zaznaczenie nie może być częścią wyrażenia inicjatora stałej.</target> <note /> </trans-unit> <trans-unit id="Selection_can_not_contain_a_pattern_expression"> <source>Selection can not contain a pattern expression.</source> <target state="translated">Wybór nie może zawierać wyrażenia wzorca.</target> <note /> </trans-unit> <trans-unit id="The_selected_code_is_inside_an_unsafe_context"> <source>The selected code is inside an unsafe context.</source> <target state="translated">Zaznaczony kod znajduje się w niebezpiecznym kontekście.</target> <note /> </trans-unit> <trans-unit id="No_valid_statement_range_to_extract"> <source>No valid statement range to extract</source> <target state="translated">Brak prawidłowego zakresu instrukcji do wyodrębnienia</target> <note /> </trans-unit> <trans-unit id="deprecated"> <source>deprecated</source> <target state="translated">przestarzałe</target> <note /> </trans-unit> <trans-unit id="extension"> <source>extension</source> <target state="translated">rozszerzenie</target> <note /> </trans-unit> <trans-unit id="awaitable"> <source>awaitable</source> <target state="translated">oczekujący</target> <note /> </trans-unit> <trans-unit id="awaitable_extension"> <source>awaitable, extension</source> <target state="translated">oczekujący, rozszerzenie</target> <note /> </trans-unit> <trans-unit id="Organize_Usings"> <source>Organize Usings</source> <target state="translated">Organizuj użycia</target> <note /> </trans-unit> <trans-unit id="Insert_await"> <source>Insert 'await'.</source> <target state="translated">Wstaw element „await”.</target> <note /> </trans-unit> <trans-unit id="Make_0_return_Task_instead_of_void"> <source>Make {0} return Task instead of void.</source> <target state="translated">Ustaw element {0}, aby zwracał zadanie zamiast elementu void.</target> <note /> </trans-unit> <trans-unit id="Change_return_type_from_0_to_1"> <source>Change return type from {0} to {1}</source> <target state="translated">Zmień zwracany typ z {0} na {1}</target> <note /> </trans-unit> <trans-unit id="Replace_return_with_yield_return"> <source>Replace return with yield return</source> <target state="translated">Zamień instrukcję return na instrukcję yield return</target> <note /> </trans-unit> <trans-unit id="Generate_explicit_conversion_operator_in_0"> <source>Generate explicit conversion operator in '{0}'</source> <target state="translated">Generuj operator jawnej konwersji w elemencie „{0}”</target> <note /> </trans-unit> <trans-unit id="Generate_implicit_conversion_operator_in_0"> <source>Generate implicit conversion operator in '{0}'</source> <target state="translated">Generuj operator niejawnej konwersji w elemencie „{0}”</target> <note /> </trans-unit> <trans-unit id="record_"> <source>record</source> <target state="translated">rekord</target> <note /> </trans-unit> <trans-unit id="record_struct"> <source>record struct</source> <target state="translated">struktura rekordów</target> <note /> </trans-unit> <trans-unit id="switch_statement"> <source>switch statement</source> <target state="translated">instrukcja switch</target> <note>{Locked="switch"} "switch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="switch_statement_case_clause"> <source>switch statement case clause</source> <target state="translated">klauzula case instrukcji switch</target> <note>{Locked="switch"}{Locked="case"} "switch" and "case" are a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="try_block"> <source>try block</source> <target state="translated">blok try</target> <note>{Locked="try"} "try" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="catch_clause"> <source>catch clause</source> <target state="translated">klauzula catch</target> <note>{Locked="catch"} "catch" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="filter_clause"> <source>filter clause</source> <target state="translated">klauzula filter</target> <note /> </trans-unit> <trans-unit id="finally_clause"> <source>finally clause</source> <target state="translated">klauzula finally</target> <note>{Locked="finally"} "finally" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="fixed_statement"> <source>fixed statement</source> <target state="translated">instrukcja fixed</target> <note>{Locked="fixed"} "fixed" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_declaration"> <source>using declaration</source> <target state="translated">deklaracja using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_statement"> <source>using statement</source> <target state="translated">instrukcja using</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lock_statement"> <source>lock statement</source> <target state="translated">instrukcja lock</target> <note>{Locked="lock"} "lock" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="foreach_statement"> <source>foreach statement</source> <target state="translated">instrukcja foreach</target> <note>{Locked="foreach"} "foreach" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="checked_statement"> <source>checked statement</source> <target state="translated">instrukcja checked</target> <note>{Locked="checked"} "checked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="unchecked_statement"> <source>unchecked statement</source> <target state="translated">instrukcja unchecked</target> <note>{Locked="unchecked"} "unchecked" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="await_expression"> <source>await expression</source> <target state="translated">wyrażenie await</target> <note>{Locked="await"} "await" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="lambda"> <source>lambda</source> <target state="translated">lambda</target> <note /> </trans-unit> <trans-unit id="anonymous_method"> <source>anonymous method</source> <target state="translated">metoda anonimowa</target> <note /> </trans-unit> <trans-unit id="from_clause"> <source>from clause</source> <target state="translated">klauzula from</target> <note /> </trans-unit> <trans-unit id="join_clause"> <source>join clause</source> <target state="translated">klauzula join</target> <note>{Locked="join"} "join" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="let_clause"> <source>let clause</source> <target state="translated">klauzula let</target> <note>{Locked="let"} "let" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="where_clause"> <source>where clause</source> <target state="translated">klauzula where</target> <note>{Locked="where"} "where" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="orderby_clause"> <source>orderby clause</source> <target state="translated">klauzula orderby</target> <note>{Locked="orderby"} "orderby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="select_clause"> <source>select clause</source> <target state="translated">klauzula select</target> <note>{Locked="select"} "select" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="groupby_clause"> <source>groupby clause</source> <target state="translated">klauzula groupby</target> <note>{Locked="groupby"} "groupby" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="query_body"> <source>query body</source> <target state="translated">treść zapytania</target> <note /> </trans-unit> <trans-unit id="into_clause"> <source>into clause</source> <target state="translated">klauzula into</target> <note>{Locked="into"} "into" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="is_pattern"> <source>is pattern</source> <target state="translated">wzorzec is</target> <note>{Locked="is"} "is" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="deconstruction"> <source>deconstruction</source> <target state="translated">dekonstrukcja</target> <note /> </trans-unit> <trans-unit id="tuple"> <source>tuple</source> <target state="translated">krotka</target> <note /> </trans-unit> <trans-unit id="local_function"> <source>local function</source> <target state="translated">funkcja lokalna</target> <note /> </trans-unit> <trans-unit id="out_var"> <source>out variable</source> <target state="translated">zmienna „out”</target> <note>{Locked="out"} "out" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="ref_local_or_expression"> <source>ref local or expression</source> <target state="translated">ref — lokalna zmienna lub wyrażenie</target> <note>{Locked="ref"} "ref" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="global_statement"> <source>global statement</source> <target state="translated">instrukcja global</target> <note>{Locked="global"} "global" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="using_directive"> <source>using directive</source> <target state="translated">dyrektywa using</target> <note /> </trans-unit> <trans-unit id="event_field"> <source>event field</source> <target state="translated">pole event</target> <note /> </trans-unit> <trans-unit id="conversion_operator"> <source>conversion operator</source> <target state="translated">operator konwersji</target> <note /> </trans-unit> <trans-unit id="destructor"> <source>destructor</source> <target state="translated">destruktor</target> <note /> </trans-unit> <trans-unit id="indexer"> <source>indexer</source> <target state="translated">indeksator</target> <note /> </trans-unit> <trans-unit id="property_getter"> <source>property getter</source> <target state="translated">metoda pobierająca właściwości</target> <note /> </trans-unit> <trans-unit id="indexer_getter"> <source>indexer getter</source> <target state="translated">metoda pobierająca indeksatora</target> <note /> </trans-unit> <trans-unit id="property_setter"> <source>property setter</source> <target state="translated">metoda ustawiająca właściwości</target> <note /> </trans-unit> <trans-unit id="indexer_setter"> <source>indexer setter</source> <target state="translated">metoda ustawiająca indeksatora</target> <note /> </trans-unit> <trans-unit id="attribute_target"> <source>attribute target</source> <target state="translated">cel atrybutu</target> <note /> </trans-unit> <trans-unit id="_0_does_not_contain_a_constructor_that_takes_that_many_arguments"> <source>'{0}' does not contain a constructor that takes that many arguments.</source> <target state="translated">'Element „{0}” nie zawiera konstruktora, który przyjmuje wiele argumentów.</target> <note /> </trans-unit> <trans-unit id="The_name_0_does_not_exist_in_the_current_context"> <source>The name '{0}' does not exist in the current context.</source> <target state="translated">Nazwa „{0}” nie istnieje w bieżącym kontekście.</target> <note /> </trans-unit> <trans-unit id="Hide_base_member"> <source>Hide base member</source> <target state="translated">Ukryj składową bazową</target> <note /> </trans-unit> <trans-unit id="Properties"> <source>Properties</source> <target state="translated">Właściwości</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_namespace_declaration"> <source>Autoselect disabled due to namespace declaration.</source> <target state="translated">Automatyczne zaznaczanie zostało wyłączone z powodu deklaracji przestrzeni nazw.</target> <note /> </trans-unit> <trans-unit id="namespace_name"> <source>&lt;namespace name&gt;</source> <target state="translated">&lt;nazwa przestrzeni nazw&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_type_declaration"> <source>Autoselect disabled due to type declaration.</source> <target state="translated">Funkcja automatycznego wybierania została wyłączona z powodu deklaracji typu.</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_possible_deconstruction_declaration"> <source>Autoselect disabled due to possible deconstruction declaration.</source> <target state="translated">Automatyczne wybieranie jest wyłączone z powodu możliwej deklaracji dekonstrukcji.</target> <note /> </trans-unit> <trans-unit id="Upgrade_this_project_to_csharp_language_version_0"> <source>Upgrade this project to C# language version '{0}'</source> <target state="translated">Uaktualnij ten projekt do wersji „{0}” języka C#</target> <note /> </trans-unit> <trans-unit id="Upgrade_all_csharp_projects_to_language_version_0"> <source>Upgrade all C# projects to language version '{0}'</source> <target state="translated">Uaktualnij wszystkie projekty C# do wersji „{0}” języka</target> <note /> </trans-unit> <trans-unit id="class_name"> <source>&lt;class name&gt;</source> <target state="translated">&lt;nazwa klasy&gt;</target> <note /> </trans-unit> <trans-unit id="interface_name"> <source>&lt;interface name&gt;</source> <target state="translated">&lt;nazwa interfejsu&gt;</target> <note /> </trans-unit> <trans-unit id="designation_name"> <source>&lt;designation name&gt;</source> <target state="translated">&lt;nazwa oznaczenia&gt;</target> <note /> </trans-unit> <trans-unit id="struct_name"> <source>&lt;struct name&gt;</source> <target state="translated">&lt;nazwa struktury&gt;</target> <note /> </trans-unit> <trans-unit id="Make_method_async"> <source>Make method async</source> <target state="translated">Ustaw metodę jako asynchroniczną</target> <note /> </trans-unit> <trans-unit id="Make_method_async_remain_void"> <source>Make method async (stay void)</source> <target state="translated">Ustaw metodę jako asynchroniczną (pozostaw jako unieważnioną)</target> <note /> </trans-unit> <trans-unit id="Name"> <source>&lt;Name&gt;</source> <target state="translated">&lt;Nazwa&gt;</target> <note /> </trans-unit> <trans-unit id="Autoselect_disabled_due_to_member_declaration"> <source>Autoselect disabled due to member declaration</source> <target state="translated">Funkcja automatycznego wybierania została wyłączona z powodu deklaracji składowej</target> <note /> </trans-unit> <trans-unit id="Suggested_name"> <source>(Suggested name)</source> <target state="translated">(Sugerowana nazwa)</target> <note /> </trans-unit> <trans-unit id="Remove_unused_function"> <source>Remove unused function</source> <target state="translated">Usuń nieużywaną funkcję</target> <note /> </trans-unit> <trans-unit id="Add_parentheses_around_conditional_expression_in_interpolated_string"> <source>Add parentheses</source> <target state="translated">Dodaj nawiasy</target> <note /> </trans-unit> <trans-unit id="Convert_to_foreach"> <source>Convert to 'foreach'</source> <target state="translated">Konwertuj na wyrażenie „foreach”</target> <note /> </trans-unit> <trans-unit id="Convert_to_for"> <source>Convert to 'for'</source> <target state="translated">Konwertuj na wyrażenie „for”</target> <note /> </trans-unit> <trans-unit id="Invert_if"> <source>Invert if</source> <target state="translated">Odwróć instrukcję if</target> <note /> </trans-unit> <trans-unit id="Add_Obsolete"> <source>Add [Obsolete]</source> <target state="translated">Dodaj [przestarzałe]</target> <note /> </trans-unit> <trans-unit id="Use_0"> <source>Use '{0}'</source> <target state="translated">Użyj elementu „{0}”</target> <note /> </trans-unit> <trans-unit id="Introduce_using_statement"> <source>Introduce 'using' statement</source> <target state="translated">Wprowadź instrukcję „using”</target> <note>{Locked="using"} "using" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_break_statement"> <source>yield break statement</source> <target state="translated">instrukcja yield break</target> <note>{Locked="yield break"} "yield break" is a C# keyword and should not be localized.</note> </trans-unit> <trans-unit id="yield_return_statement"> <source>yield return statement</source> <target state="translated">instrukcja yield return</target> <note>{Locked="yield return"} "yield return" is a C# keyword and should not be localized.</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/Core/Portable/Options/DocumentOptionSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// An <see cref="OptionSet"/> that comes from <see cref="Document.GetOptionsAsync(System.Threading.CancellationToken)"/>. It behaves just like a normal /// <see cref="OptionSet"/> but remembers which language the <see cref="Document"/> is, so you don't have to /// pass that information redundantly when calling <see cref="GetOption{T}(PerLanguageOption{T})"/>. /// </summary> public sealed class DocumentOptionSet : OptionSet { private readonly OptionSet _backingOptionSet; private readonly string _language; internal DocumentOptionSet(OptionSet backingOptionSet, string language) { _backingOptionSet = backingOptionSet; _language = language; } private protected override object? GetOptionCore(OptionKey optionKey) => _backingOptionSet.GetOption(optionKey); public T GetOption<T>(PerLanguageOption<T> option) => _backingOptionSet.GetOption(option, _language); internal T GetOption<T>(PerLanguageOption2<T> option) => _backingOptionSet.GetOption(option, _language); public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => new DocumentOptionSet(_backingOptionSet.WithChangedOption(optionAndLanguage, value), _language); /// <summary> /// Creates a new <see cref="DocumentOptionSet" /> that contains the changed value. /// </summary> public DocumentOptionSet WithChangedOption<T>(PerLanguageOption<T> option, T value) => (DocumentOptionSet)WithChangedOption(option, _language, value); /// <summary> /// Creates a new <see cref="DocumentOptionSet" /> that contains the changed value. /// </summary> internal DocumentOptionSet WithChangedOption<T>(PerLanguageOption2<T> option, T value) => (DocumentOptionSet)WithChangedOption(option, _language, value); private protected override AnalyzerConfigOptions CreateAnalyzerConfigOptions(IOptionService optionService, string? language) { Debug.Assert((language ?? _language) == _language, $"Use of a {nameof(DocumentOptionSet)} is not expected to differ from the language it was constructed with."); return _backingOptionSet.AsAnalyzerConfigOptions(optionService, language ?? _language); } internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) => _backingOptionSet.GetChangedOptions(optionSet); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// An <see cref="OptionSet"/> that comes from <see cref="Document.GetOptionsAsync(System.Threading.CancellationToken)"/>. It behaves just like a normal /// <see cref="OptionSet"/> but remembers which language the <see cref="Document"/> is, so you don't have to /// pass that information redundantly when calling <see cref="GetOption{T}(PerLanguageOption{T})"/>. /// </summary> public sealed class DocumentOptionSet : OptionSet { private readonly OptionSet _backingOptionSet; private readonly string _language; internal DocumentOptionSet(OptionSet backingOptionSet, string language) { _backingOptionSet = backingOptionSet; _language = language; } private protected override object? GetOptionCore(OptionKey optionKey) => _backingOptionSet.GetOption(optionKey); public T GetOption<T>(PerLanguageOption<T> option) => _backingOptionSet.GetOption(option, _language); internal T GetOption<T>(PerLanguageOption2<T> option) => _backingOptionSet.GetOption(option, _language); public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => new DocumentOptionSet(_backingOptionSet.WithChangedOption(optionAndLanguage, value), _language); /// <summary> /// Creates a new <see cref="DocumentOptionSet" /> that contains the changed value. /// </summary> public DocumentOptionSet WithChangedOption<T>(PerLanguageOption<T> option, T value) => (DocumentOptionSet)WithChangedOption(option, _language, value); /// <summary> /// Creates a new <see cref="DocumentOptionSet" /> that contains the changed value. /// </summary> internal DocumentOptionSet WithChangedOption<T>(PerLanguageOption2<T> option, T value) => (DocumentOptionSet)WithChangedOption(option, _language, value); private protected override AnalyzerConfigOptions CreateAnalyzerConfigOptions(IOptionService optionService, string? language) { Debug.Assert((language ?? _language) == _language, $"Use of a {nameof(DocumentOptionSet)} is not expected to differ from the language it was constructed with."); return _backingOptionSet.AsAnalyzerConfigOptions(optionService, language ?? _language); } internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) => _backingOptionSet.GetChangedOptions(optionSet); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/Core/Portable/ExtensionOrderAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class ExtensionOrderAttribute : Attribute { public ExtensionOrderAttribute() { } public string After { get; set; } public string Before { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis { [MetadataAttribute] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class ExtensionOrderAttribute : Attribute { public ExtensionOrderAttribute() { } public string After { get; set; } public string Before { get; set; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.ParsedSyntaxTree.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree ''' <summary> ''' A SyntaxTree is a tree of nodes that represents an entire file of VB ''' code, and is parsed by the parser. ''' </summary> Partial Private Class ParsedSyntaxTree Inherits VisualBasicSyntaxTree Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _path As String Private ReadOnly _root As VisualBasicSyntaxNode Private ReadOnly _hasCompilationUnitRoot As Boolean Private ReadOnly _isMyTemplate As Boolean Private ReadOnly _encodingOpt As Encoding Private ReadOnly _checksumAlgorithm As SourceHashAlgorithm Private ReadOnly _diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Private _lazyText As SourceText ''' <summary> ''' Used to create new tree incrementally. ''' </summary> Friend Sub New(textOpt As SourceText, encodingOpt As Encoding, checksumAlgorithm As SourceHashAlgorithm, path As String, options As VisualBasicParseOptions, syntaxRoot As VisualBasicSyntaxNode, isMyTemplate As Boolean, diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic), Optional cloneRoot As Boolean = True) Debug.Assert(syntaxRoot IsNot Nothing) Debug.Assert(options IsNot Nothing) Debug.Assert(textOpt Is Nothing OrElse textOpt.Encoding Is encodingOpt AndAlso textOpt.ChecksumAlgorithm = checksumAlgorithm) _lazyText = textOpt _encodingOpt = If(encodingOpt, textOpt?.Encoding) _checksumAlgorithm = checksumAlgorithm _options = options _path = If(path, String.Empty) _root = If(cloneRoot, Me.CloneNodeAsRoot(syntaxRoot), syntaxRoot) _hasCompilationUnitRoot = (syntaxRoot.Kind = SyntaxKind.CompilationUnit) _isMyTemplate = isMyTemplate _diagnosticOptions = If(diagnosticOptions, EmptyDiagnosticOptions) End Sub Public Overrides ReadOnly Property FilePath As String Get Return _path End Get End Property Friend Overrides ReadOnly Property IsMyTemplate As Boolean Get Return _isMyTemplate End Get End Property Public Overrides Function GetText(Optional cancellationToken As CancellationToken = Nothing) As SourceText If _lazyText Is Nothing Then Dim treeText = Me.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm) Interlocked.CompareExchange(_lazyText, treeText, Nothing) End If Return _lazyText End Function Public Overrides Function TryGetText(ByRef text As SourceText) As Boolean text = _lazyText Return text IsNot Nothing End Function Public Overrides ReadOnly Property Encoding As Encoding Get Return _encodingOpt End Get End Property Public Overrides ReadOnly Property Length As Integer Get Return _root.FullSpan.Length End Get End Property Public Overrides Function GetRoot(Optional cancellationToken As CancellationToken = Nothing) As VisualBasicSyntaxNode Return _root End Function Public Overrides Function GetRootAsync(Optional cancellationToken As CancellationToken = Nothing) As Task(Of VisualBasicSyntaxNode) Return Task.FromResult(_root) End Function Public Overrides Function TryGetRoot(ByRef root As VisualBasicSyntaxNode) As Boolean root = _root Return True End Function Public Overrides ReadOnly Property HasCompilationUnitRoot As Boolean Get Return _hasCompilationUnitRoot End Get End Property Public Overrides ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Public Overrides ReadOnly Property DiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Get Return _diagnosticOptions End Get End Property ''' <summary> ''' Get a reference to the given node. ''' </summary> Public Overrides Function GetReference(node As SyntaxNode) As SyntaxReference Return New SimpleSyntaxReference(Me, node) End Function Public Overrides Function WithRootAndOptions(root As SyntaxNode, options As ParseOptions) As SyntaxTree If _root Is root AndAlso _options Is options Then Return Me End If Return New ParsedSyntaxTree( Nothing, _encodingOpt, _checksumAlgorithm, _path, DirectCast(options, VisualBasicParseOptions), DirectCast(root, VisualBasicSyntaxNode), _isMyTemplate, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithFilePath(path As String) As SyntaxTree If String.Equals(Me._path, path) Then Return Me End If Return New ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, path, _options, _root, _isMyTemplate, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithDiagnosticOptions(options As ImmutableDictionary(Of String, ReportDiagnostic)) As SyntaxTree If options Is Nothing Then options = EmptyDiagnosticOptions End If If ReferenceEquals(_diagnosticOptions, options) Then Return Me End If Return New ParsedSyntaxTree(_lazyText, _encodingOpt, _checksumAlgorithm, _path, _options, _root, _isMyTemplate, options, cloneRoot:=True) End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree ''' <summary> ''' A SyntaxTree is a tree of nodes that represents an entire file of VB ''' code, and is parsed by the parser. ''' </summary> Partial Private Class ParsedSyntaxTree Inherits VisualBasicSyntaxTree Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _path As String Private ReadOnly _root As VisualBasicSyntaxNode Private ReadOnly _hasCompilationUnitRoot As Boolean Private ReadOnly _isMyTemplate As Boolean Private ReadOnly _encodingOpt As Encoding Private ReadOnly _checksumAlgorithm As SourceHashAlgorithm Private ReadOnly _diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Private _lazyText As SourceText ''' <summary> ''' Used to create new tree incrementally. ''' </summary> Friend Sub New(textOpt As SourceText, encodingOpt As Encoding, checksumAlgorithm As SourceHashAlgorithm, path As String, options As VisualBasicParseOptions, syntaxRoot As VisualBasicSyntaxNode, isMyTemplate As Boolean, diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic), Optional cloneRoot As Boolean = True) Debug.Assert(syntaxRoot IsNot Nothing) Debug.Assert(options IsNot Nothing) Debug.Assert(textOpt Is Nothing OrElse textOpt.Encoding Is encodingOpt AndAlso textOpt.ChecksumAlgorithm = checksumAlgorithm) _lazyText = textOpt _encodingOpt = If(encodingOpt, textOpt?.Encoding) _checksumAlgorithm = checksumAlgorithm _options = options _path = If(path, String.Empty) _root = If(cloneRoot, Me.CloneNodeAsRoot(syntaxRoot), syntaxRoot) _hasCompilationUnitRoot = (syntaxRoot.Kind = SyntaxKind.CompilationUnit) _isMyTemplate = isMyTemplate _diagnosticOptions = If(diagnosticOptions, EmptyDiagnosticOptions) End Sub Public Overrides ReadOnly Property FilePath As String Get Return _path End Get End Property Friend Overrides ReadOnly Property IsMyTemplate As Boolean Get Return _isMyTemplate End Get End Property Public Overrides Function GetText(Optional cancellationToken As CancellationToken = Nothing) As SourceText If _lazyText Is Nothing Then Dim treeText = Me.GetRoot(cancellationToken).GetText(_encodingOpt, _checksumAlgorithm) Interlocked.CompareExchange(_lazyText, treeText, Nothing) End If Return _lazyText End Function Public Overrides Function TryGetText(ByRef text As SourceText) As Boolean text = _lazyText Return text IsNot Nothing End Function Public Overrides ReadOnly Property Encoding As Encoding Get Return _encodingOpt End Get End Property Public Overrides ReadOnly Property Length As Integer Get Return _root.FullSpan.Length End Get End Property Public Overrides Function GetRoot(Optional cancellationToken As CancellationToken = Nothing) As VisualBasicSyntaxNode Return _root End Function Public Overrides Function GetRootAsync(Optional cancellationToken As CancellationToken = Nothing) As Task(Of VisualBasicSyntaxNode) Return Task.FromResult(_root) End Function Public Overrides Function TryGetRoot(ByRef root As VisualBasicSyntaxNode) As Boolean root = _root Return True End Function Public Overrides ReadOnly Property HasCompilationUnitRoot As Boolean Get Return _hasCompilationUnitRoot End Get End Property Public Overrides ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Public Overrides ReadOnly Property DiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Get Return _diagnosticOptions End Get End Property ''' <summary> ''' Get a reference to the given node. ''' </summary> Public Overrides Function GetReference(node As SyntaxNode) As SyntaxReference Return New SimpleSyntaxReference(Me, node) End Function Public Overrides Function WithRootAndOptions(root As SyntaxNode, options As ParseOptions) As SyntaxTree If _root Is root AndAlso _options Is options Then Return Me End If Return New ParsedSyntaxTree( Nothing, _encodingOpt, _checksumAlgorithm, _path, DirectCast(options, VisualBasicParseOptions), DirectCast(root, VisualBasicSyntaxNode), _isMyTemplate, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithFilePath(path As String) As SyntaxTree If String.Equals(Me._path, path) Then Return Me End If Return New ParsedSyntaxTree( _lazyText, _encodingOpt, _checksumAlgorithm, path, _options, _root, _isMyTemplate, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithDiagnosticOptions(options As ImmutableDictionary(Of String, ReportDiagnostic)) As SyntaxTree If options Is Nothing Then options = EmptyDiagnosticOptions End If If ReferenceEquals(_diagnosticOptions, options) Then Return Me End If Return New ParsedSyntaxTree(_lazyText, _encodingOpt, _checksumAlgorithm, _path, _options, _root, _isMyTemplate, options, cloneRoot:=True) End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/VisualBasic/Test/Emit/PDB/PDBVariableInitializerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBVariableInitializerTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartialClass() Dim source = <compilation> <file name="a.vb"> Option strict on imports system partial Class C1 public f1 as integer = 23 public f3 As New C1() public f4, f5 As New C1() Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub End Class </file> <file name="b.vb"> Option strict on imports system partial Class C1 ' more lines to see a different span in the sequence points ... public f2 as integer = 42 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="01-41-D1-CA-DD-B0-0B-39-BE-3C-3D-69-AA-18-B3-7A-F5-65-C5-DD"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="FE-FF-3A-FC-5E-54-7C-6D-96-86-05-B8-B6-FD-FC-5F-81-51-AE-FA"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="6" startColumn="12" endLine="6" endColumn="30" document="1"/> <entry offset="0xf" startLine="7" startColumn="12" endLine="7" endColumn="26" document="1"/> <entry offset="0x1a" startLine="8" startColumn="12" endLine="8" endColumn="14" document="1"/> <entry offset="0x25" startLine="8" startColumn="16" endLine="8" endColumn="18" document="1"/> <entry offset="0x30" startLine="11" startColumn="36" endLine="11" endColumn="54" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x39"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty1() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As Integer = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As Integer = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty2() Dim source = <compilation> <file> Interface I Property P As Object End Interface Class C Implements I Property P = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoPropertyAsNew() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As New Integer Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As New Integer".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedField() Dim source = <compilation> <file> Class C Dim F(1), G(2) As Integer End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedLocal() Dim source = <compilation> <file> Class C Sub M Dim F(1), G(2) As Integer End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewMultiInitializer() Dim source = <compilation> <file> Class C Dim F, G As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewMultiInitializer() Dim source = <compilation> <file> Class C Sub M Dim F, G As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewSingleInitializer() Dim source = <compilation> <file> Class C Dim F As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewSingleInitializer() Dim source = <compilation> <file> Class C Sub M Dim F As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldInitializer() Dim source = <compilation> <file> Class C Dim F = 1 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalInitializer() Dim source = <compilation> <file> Class C Sub M Dim F = 1 End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB Public Class PDBVariableInitializerTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub PartialClass() Dim source = <compilation> <file name="a.vb"> Option strict on imports system partial Class C1 public f1 as integer = 23 public f3 As New C1() public f4, f5 As New C1() Public sub DumpFields() Console.WriteLine(f1) Console.WriteLine(f2) End Sub Public shared Sub Main(args() as string) Dim c as new C1 c.DumpFields() End sub End Class </file> <file name="b.vb"> Option strict on imports system partial Class C1 ' more lines to see a different span in the sequence points ... public f2 as integer = 42 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) compilation.VerifyPdb("C1..ctor", <symbols> <files> <file id="1" name="a.vb" language="VB" checksumAlgorithm="SHA1" checksum="01-41-D1-CA-DD-B0-0B-39-BE-3C-3D-69-AA-18-B3-7A-F5-65-C5-DD"/> <file id="2" name="b.vb" language="VB" checksumAlgorithm="SHA1" checksum="FE-FF-3A-FC-5E-54-7C-6D-96-86-05-B8-B6-FD-FC-5F-81-51-AE-FA"/> </files> <entryPoint declaringType="C1" methodName="Main" parameterNames="args"/> <methods> <method containingType="C1" name=".ctor"> <sequencePoints> <entry offset="0x0" hidden="true" document="1"/> <entry offset="0x7" startLine="6" startColumn="12" endLine="6" endColumn="30" document="1"/> <entry offset="0xf" startLine="7" startColumn="12" endLine="7" endColumn="26" document="1"/> <entry offset="0x1a" startLine="8" startColumn="12" endLine="8" endColumn="14" document="1"/> <entry offset="0x25" startLine="8" startColumn="16" endLine="8" endColumn="18" document="1"/> <entry offset="0x30" startLine="11" startColumn="36" endLine="11" endColumn="54" document="2"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x39"> <namespace name="System" importlevel="file"/> <currentnamespace name=""/> </scope> </method> </methods> </symbols>) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty1() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As Integer = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As Integer = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoProperty2() Dim source = <compilation> <file> Interface I Property P As Object End Interface Class C Implements I Property P = 1 Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub AutoPropertyAsNew() Dim source = <compilation> <file> Interface I Property P As Integer End Interface Class C Implements I Property P As New Integer Implements I.P End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Property ".Length + 1 Dim expectedEnd1 = " Property P As New Integer".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="8" startColumn=<%= expectedStart1 %> endLine="8" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedField() Dim source = <compilation> <file> Class C Dim F(1), G(2) As Integer End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub ArrayInitializedLocal() Dim source = <compilation> <file> Class C Sub M Dim F(1), G(2) As Integer End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F(1)".Length + 1 Dim expectedStart2 = " Dim F(1), ".Length + 1 Dim expectedEnd2 = " Dim F(1), G(2)".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewMultiInitializer() Dim source = <compilation> <file> Class C Dim F, G As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> <entry startLine="2" startColumn=<%= expectedStart2 %> endLine="2" endColumn=<%= expectedEnd2 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewMultiInitializer() Dim source = <compilation> <file> Class C Sub M Dim F, G As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F".Length + 1 Dim expectedStart2 = " Dim F, ".Length + 1 Dim expectedEnd2 = " Dim F, G".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="3" startColumn=<%= expectedStart2 %> endLine="3" endColumn=<%= expectedEnd2 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldAsNewSingleInitializer() Dim source = <compilation> <file> Class C Dim F As New C() End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalAsNewSingleInitializer() Dim source = <compilation> <file> Class C Sub M Dim F As New C() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F As New C()".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub FieldInitializer() Dim source = <compilation> <file> Class C Dim F = 1 End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C..ctor")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry/> <entry startLine="2" startColumn=<%= expectedStart1 %> endLine="2" endColumn=<%= expectedEnd1 %>/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub LocalInitializer() Dim source = <compilation> <file> Class C Sub M Dim F = 1 End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.DebugDll) compilation.VerifyDiagnostics() Dim actual = GetSequencePoints(GetPdbXml(compilation, "C.M")) Dim expectedStart1 = " Dim ".Length + 1 Dim expectedEnd1 = " Dim F = 1".Length + 1 Dim expected = <sequencePoints> <entry startLine="2" startColumn="5" endLine="2" endColumn="10"/> <entry startLine="3" startColumn=<%= expectedStart1 %> endLine="3" endColumn=<%= expectedEnd1 %>/> <entry startLine="4" startColumn="5" endLine="4" endColumn="12"/> </sequencePoints> AssertXml.Equal(expected, actual) End Sub End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.ko.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">동적 뷰</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">COM 또는 동적 개체에만 동적 뷰가 있을 수 있습니다.</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">동적 뷰를 확장하면 개체의 동적 멤버를 가져옵니다.</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">오류</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}'이(가) '{1}' 형식의 예외를 throw했습니다.</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">값을 제공할 수 없음: 호스트 값을 찾을 수 없음</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">'{0}'을(를) 역참조할 수 없습니다. 포인터가 잘못되었습니다.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">네이티브 뷰</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">네이티브 개체를 검사하려면 네이티브 코드 디버깅을 사용하세요.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">public이 아닌 멤버</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Raw 뷰</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">결과 뷰</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">결과 뷰를 사용하려면 System.Core.dll을 참조해야 합니다.</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Enumerable 형식만 결과 뷰를 가질 수 있습니다.</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">결과 뷰를 확장하면 IEnumerable이 열거됩니다.</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">공유 멤버</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">정적 멤버</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">형식 변수</target> <note>Type variables result name</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">동적 뷰</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">COM 또는 동적 개체에만 동적 뷰가 있을 수 있습니다.</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">동적 뷰를 확장하면 개체의 동적 멤버를 가져옵니다.</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">오류</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}'이(가) '{1}' 형식의 예외를 throw했습니다.</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">값을 제공할 수 없음: 호스트 값을 찾을 수 없음</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">'{0}'을(를) 역참조할 수 없습니다. 포인터가 잘못되었습니다.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">네이티브 뷰</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">네이티브 개체를 검사하려면 네이티브 코드 디버깅을 사용하세요.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">public이 아닌 멤버</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Raw 뷰</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">결과 뷰</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">결과 뷰를 사용하려면 System.Core.dll을 참조해야 합니다.</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Enumerable 형식만 결과 뷰를 가질 수 있습니다.</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">결과 뷰를 확장하면 IEnumerable이 열거됩니다.</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">공유 멤버</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">정적 멤버</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">형식 변수</target> <note>Type variables result name</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/VisualStudio/Xaml/Impl/Features/Definitions/XamlSourceDefinition.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions { /// <summary> /// XamlDefinition with file path and TextSpan or line and column. /// When XamlSourceDefinition was created, the creator may have had a textSpan or line/column. /// We should either use Span or Line Column. /// </summary> internal sealed class XamlSourceDefinition : XamlDefinition { public XamlSourceDefinition(string filePath, TextSpan span) { FilePath = filePath; Span = span; } public XamlSourceDefinition(string filePath, int line, int column) { FilePath = filePath; Line = line; Column = column; } public string FilePath { get; } public int Line { get; } public int Column { get; } public TextSpan? Span { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Definitions { /// <summary> /// XamlDefinition with file path and TextSpan or line and column. /// When XamlSourceDefinition was created, the creator may have had a textSpan or line/column. /// We should either use Span or Line Column. /// </summary> internal sealed class XamlSourceDefinition : XamlDefinition { public XamlSourceDefinition(string filePath, TextSpan span) { FilePath = filePath; Span = span; } public XamlSourceDefinition(string filePath, int line, int column) { FilePath = filePath; Line = line; Column = column; } public string FilePath { get; } public int Line { get; } public int Column { get; } public TextSpan? Span { get; } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/Serialization/MutableNamingStyle.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.NamingStyles; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal class MutableNamingStyle { public NamingStyle NamingStyle { get; private set; } public Guid ID => NamingStyle.ID; public string Name { get => NamingStyle.Name; set => NamingStyle = NamingStyle.With(name: value); } public string Prefix { get => NamingStyle.Prefix; set => NamingStyle = NamingStyle.With(prefix: value); } public string Suffix { get => NamingStyle.Suffix; set => NamingStyle = NamingStyle.With(suffix: value); } public string WordSeparator { get => NamingStyle.WordSeparator; set => NamingStyle = NamingStyle.With(wordSeparator: value); } public Capitalization CapitalizationScheme { get => NamingStyle.CapitalizationScheme; set => NamingStyle = NamingStyle.With(capitalizationScheme: value); } public MutableNamingStyle() : this(new NamingStyle(Guid.NewGuid())) { } public MutableNamingStyle(NamingStyle namingStyle) => NamingStyle = namingStyle; internal MutableNamingStyle Clone() => new(NamingStyle); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.NamingStyles; namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles { internal class MutableNamingStyle { public NamingStyle NamingStyle { get; private set; } public Guid ID => NamingStyle.ID; public string Name { get => NamingStyle.Name; set => NamingStyle = NamingStyle.With(name: value); } public string Prefix { get => NamingStyle.Prefix; set => NamingStyle = NamingStyle.With(prefix: value); } public string Suffix { get => NamingStyle.Suffix; set => NamingStyle = NamingStyle.With(suffix: value); } public string WordSeparator { get => NamingStyle.WordSeparator; set => NamingStyle = NamingStyle.With(wordSeparator: value); } public Capitalization CapitalizationScheme { get => NamingStyle.CapitalizationScheme; set => NamingStyle = NamingStyle.With(capitalizationScheme: value); } public MutableNamingStyle() : this(new NamingStyle(Guid.NewGuid())) { } public MutableNamingStyle(NamingStyle namingStyle) => NamingStyle = namingStyle; internal MutableNamingStyle Clone() => new(NamingStyle); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/VisualStudio/Core/Test/ObjectBrowser/VisualBasic/ObjectBrowerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ObjectBrowser.VisualBasic Public Class ObjectBrowserTests Inherits AbstractObjectBrowserTests Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property Friend Overrides Function CreateLibraryManager(serviceProvider As IServiceProvider, componentModel As IComponentModel, workspace As VisualStudioWorkspace) As AbstractObjectBrowserLibraryManager Return New ObjectBrowserLibraryManager(serviceProvider, componentModel, workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_NamespaceClassAndMethod() Dim code = <Code> Namespace N Class C Sub M() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list.VerifyNames("VisualBasicAssembly1") list = list.GetNamespaceList(0) list.VerifyNames("N") list = list.GetTypeList(0) list.VerifyNames("C") list = list.GetMemberList(0) list.VerifyNames(AddressOf IsImmediateMember, "M()") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_NoNamespaceWithoutType() Dim code = <Code> Namespace N End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list.VerifyEmpty() End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_InlcudePrivateNestedTypeMembersInSourceCode() Dim code = <Code> Namespace N Class C Private Enum PrivateEnumTest End Enum Private Class PrivateClassTest End Class Private Structure PrivateStructTest End Structure End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0).GetTypeList(0) list.VerifyNames("C", "C.PrivateStructTest", "C.PrivateClassTest", "C.PrivateEnumTest") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_InlcudePrivateDoubleNestedTypeMembersInSourceCode() Dim code = <Code> Namespace N Friend Class C Private Class NestedClass Private Class NestedNestedClass End Class End Class End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0).GetTypeList(0) list.VerifyNames("C", "C.NestedClass", "C.NestedClass.NestedNestedClass") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_InlcudeNoPrivateNestedTypeOfMetaData() Dim metaDatacode = <Code> Namespace N Public Class C Public Enum PublicEnumTest V1 End Enum Private Class PrivateClassTest End Class Private Structure PrivateStructTest End Structure End Class End Namespace </Code> Dim code = <Code></Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code, metaDatacode, False)) Dim library = state.GetLibrary() Dim list = library.GetProjectList().GetReferenceList(0).GetNamespaceList(0).GetTypeList(0) list.VerifyNames("C", "C.PublicEnumTest") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_InheritedMembers1() Dim code = <Code> Class A Protected Overridable Sub Goo() End Sub End Class Class B Inherits A Protected Overrides Sub Goo() MyBase.Goo() End Sub Overridable Sub Bar() End Sub End Class Class C Inherits B Protected Overrides Sub Goo() MyBase.Goo() End Sub Public Overrides Sub Bar() MyBase.Bar() End Sub End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyNames( "Goo()", "ToString() As String", "Equals(Object) As Boolean", "Equals(Object, Object) As Boolean", "ReferenceEquals(Object, Object) As Boolean", "GetHashCode() As Integer", "GetType() As System.Type", "Finalize()", "MemberwiseClone() As Object") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_InheritedMembers2() Dim code = <Code> Class A Protected Overridable Sub Goo() End Sub End Class Class B Inherits A Protected Overrides Sub Goo() MyBase.Goo() End Sub Overridable Sub Bar() End Sub End Class Class C Inherits B Protected Overrides Sub Goo() MyBase.Goo() End Sub Public Overrides Sub Bar() MyBase.Bar() End Sub End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(1) list.VerifyNames( "Goo()", "Bar()", "ToString() As String", "Equals(Object) As Boolean", "Equals(Object, Object) As Boolean", "ReferenceEquals(Object, Object) As Boolean", "GetHashCode() As Integer", "GetType() As System.Type", "Finalize()", "MemberwiseClone() As Object") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_InheritedMembers3() Dim code = <Code> Class A Protected Overridable Sub Goo() End Sub End Class Class B Inherits A Protected Overrides Sub Goo() MyBase.Goo() End Sub Overridable Sub Bar() End Sub End Class Class C Inherits B Protected Overrides Sub Goo() MyBase.Goo() End Sub Public Overrides Sub Bar() MyBase.Bar() End Sub End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(2) list.VerifyNames( "Goo()", "Bar()", "ToString() As String", "Equals(Object) As Boolean", "Equals(Object, Object) As Boolean", "ReferenceEquals(Object, Object) As Boolean", "GetHashCode() As Integer", "GetType() As System.Type", "Finalize()", "MemberwiseClone() As Object") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_HelpKeyword_Ctor() Dim code = <Code> Namespace N Class C Sub New() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyHelpKeywords("N.C.New") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Project() Dim code = <Code> Namespace N End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list.VerifyDescriptions($"{ServicesVSResources.Project}VisualBasicAssembly1") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Namespace() Dim code = <Code> Namespace N Class C End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list.VerifyDescriptions( "Namespace N" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Delegate1() Dim code = <Code> Delegate Function D(x As Integer) As Boolean </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Delegate Function D(x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Delegate2() Dim code = <Code> Delegate Sub D(y As String) </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Delegate Sub D(y As String)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Delegate3() Dim code = <Code> Delegate Function F(Of T As {Class, New}, U As V, V As List(Of T))(x As T, y As U) As V </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Delegate Function F(Of T As {Class, New}, U As V, V As System.Collections.Generic.List(Of T))(x As T, y As U) As V" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class1() Dim code = <Code> Class C End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Class C" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class2() Dim code = <Code> MustInherit Class C End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend MustInherit Class C" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class3() Dim code = <Code> NotInheritable Class C End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend NotInheritable Class C" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class4() Dim code = <Code> Public Class C(Of T As Class) End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Public Class C(Of T As Class)" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class5() Dim code = <Code> Class C(Of T As Class) Inherits B End Class Class B End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Class C(Of T As Class)" & vbCrLf & " Inherits B" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend Class B" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class6() Dim code = <Code> MustInherit Class B End Class NotInheritable Class C Inherits B End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend MustInherit Class B" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend NotInheritable Class C" & vbCrLf & " Inherits B" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Structure1() Dim code = <Code> Structure S End Structure </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Structure S" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Structure2() Dim code = <Code> Public Structure S End Structure </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Public Structure S" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Module1() Dim code = <Code> Module M End Module </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Module M" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Module2() Dim code = <Code> Public Module M End Module </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Public Module M" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Enum1() Dim code = <Code> Enum E A B C End Enum </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Enum E" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Enum2() Dim code = <Code> Enum E As Byte A B C End Enum </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Enum E As Byte" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Interfaces() Dim code = <Code> Interface I1 End Interface Interface I2 Inherits I1 End Interface Interface I3 Inherits I1 Inherits I2 End Interface </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Interface I1" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend Interface I2" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend Interface I3" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub1() Dim code = <Code> Namespace N Class C Sub M() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub2() Dim code = <Code> Namespace N Class C Sub M(x As Integer) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(x As Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub3() Dim code = <Code> Namespace N Class C Sub M(ByRef x As Integer) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(ByRef x As Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub4() Dim code = <Code> Namespace N Class C Sub M(Optional x As Integer = 42) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Integer = 42)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub5() Dim code = <Code> Imports System Namespace N Class C Sub M(Optional x As Double = Math.PI) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)), testCulture As New CultureContext(New CultureInfo("en-US", useUserOverride:=False)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Double = 3.14159265358979)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub6() Dim code = <Code> Namespace N Class C Sub M(Optional x As Double? = Nothing) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Double? = Nothing)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub7() Dim code = <Code> Namespace N Class C Sub M(Optional x As Double? = 42) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Double? = 42)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WorkItem(939739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939739")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_SubInInterface() Dim code = <Code> Namespace N interface I Sub M() End Interface End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Sub M()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.I")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function1() Dim code = <Code> Namespace N Class C Function M() As Integer End Function End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function2() Dim code = <Code> Namespace N Class C Function M%() End Function End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function3() Dim code = <Code> Namespace N MustInherit Class C MustOverride Function M() As Integer End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public MustOverride Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function4() Dim code = <Code> Namespace N MustInherit Class C Protected Overridable Function M() As Integer End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Protected Overridable Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function5() Dim code = <Code> Namespace N MustInherit Class C NotOverridable Function M() As Integer End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public NotOverridable Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_IteratorFunction() Dim code = <Code> Imports System.Collections.Generic Namespace N Class C Iterator Function M() As IEnumerable(Of Integer) End Function End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As System.Collections.Generic.IEnumerable(Of Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Constructor() Dim code = <Code> Imports System.Collections.Generic Namespace N Class C Sub New() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub New()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_SharedConstructor() Dim code = <Code> Imports System.Collections.Generic Namespace N Class C Shared Sub New() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Shared Sub New()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property1() Dim code = <Code> Class C Property P As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property2() Dim code = <Code> Class C Property P() As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property3() Dim code = <Code> Class C Property P% End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property4() Dim code = <Code> Class C Property P As Integer = 42 End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property5() Dim code = <Code> Class C ReadOnly Property P As Integer Get Return 42 End Get End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property6() Dim code = <Code> Class C ReadOnly Property P As Integer Protected Get Return 42 End Get End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property7() Dim code = <Code> Class C WriteOnly Property P As Integer Set(value As Integer) End Set End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public WriteOnly Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property8() Dim code = <Code> Class C Property P As Integer Get End Get Protected Set(value As Integer) End Set End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property9() Dim code = <Code> Class C Property P(index As Integer) As Integer Get End Get Protected Set(value As Integer) End Set End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P(index As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_IteratorProperty() Dim code = <Code> Imports System.Collections.Generic Class C ReadOnly Iterator Property P As IEnumerable(Of Integer) Get End Get End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property P As System.Collections.Generic.IEnumerable(Of Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Const1() Dim code = <Code> Class C Const F As Integer = 42 End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Const F As Integer = 42" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Const2() Dim code = <Code> Class C Const F = 42 End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Const F As Integer = 42" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field1() Dim code = <Code> Class C Dim x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field2() Dim code = <Code> Class C Private x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field3() Dim code = <Code> Class C ReadOnly x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private ReadOnly x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field4() Dim code = <Code> Class C Shared ReadOnly x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Shared ReadOnly x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_EnumMembers() Dim code = <Code> Enum E A B C End Enum </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Const A As E = 0" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "E")}", "Public Const B As E = 1" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "E")}", "Public Const C As E = 2" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "E")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Events() Dim code = <Code> Imports System Class C Event E1() Event E2(i As Integer) Event E3 As EventHandler Custom Event E4 As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Event E1()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}", "Public Event E2(i As Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}", "Public Event E3(sender As Object, e As System.EventArgs)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}", "Public Event E4(sender As Object, e As System.EventArgs)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Add() Dim code = <Code> Class C Shared Operator +(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator +(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Subtract() Dim code = <Code> Class C Shared Operator -(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator -(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Multiply() Dim code = <Code> Class C Shared Operator *(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator *(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Divide() Dim code = <Code> Class C Shared Operator /(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator /(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_IntegerDivide() Dim code = <Code> Class C Shared Operator \(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator \(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Modulus() Dim code = <Code> Class C Shared Operator Mod(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Mod(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Power() Dim code = <Code> Class C Shared Operator ^(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator ^(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Concatenate() Dim code = <Code> Class C Shared Operator &amp;(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator &(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Equality() Dim code = <Code> Class C Shared Operator =(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator =(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Inequality() Dim code = <Code> Class C Shared Operator &lt;&gt;(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <>(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_LessThan() Dim code = <Code> Class C Shared Operator &lt;(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_LessThanOrEqualTo() Dim code = <Code> Class C Shared Operator &lt;=(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <=(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_GreaterThan() Dim code = <Code> Class C Shared Operator &gt;(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator >(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_GreaterThanOrEqualTo() Dim code = <Code> Class C Shared Operator &gt;=(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator >=(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Like() Dim code = <Code> Class C Shared Operator Like(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Like(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Not() Dim code = <Code> Class C Shared Operator Not(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Not(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_And() Dim code = <Code> Class C Shared Operator And(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator And(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Or() Dim code = <Code> Class C Shared Operator Or(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Or(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Xor() Dim code = <Code> Class C Shared Operator Xor(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Xor(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_ShiftLeft() Dim code = <Code> Class C Shared Operator &lt;&lt;(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <<(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Right() Dim code = <Code> Class C Shared Operator &gt;&gt;(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator >>(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_IsTrue() Dim code = <Code> Class C Shared Operator IsTrue(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator IsTrue(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_IsFalse() Dim code = <Code> Class C Shared Operator IsFalse(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator IsFalse(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_CType1() Dim code = <Code> Class C Shared Narrowing Operator CType(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Narrowing Operator CType(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_CType2() Dim code = <Code> Class C Shared Widening Operator CType(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Widening Operator CType(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_DeclareFunction1() ' Note: DllImport functions that are not Declare should appear as normal functions Dim code = <Code> Imports System.Runtime.InteropServices Class C &lt;DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW", SetLastError:=True, CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)&gt; Public Shared Function moveFile(ByVal src As String, ByVal dst As String) As Boolean ' This function copies a file from the path src to the path dst. ' Leave this function empty. The DLLImport attribute forces calls ' to moveFile to be forwarded to MoveFileW in KERNEL32.DLL. End Function End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Function moveFile(src As String, dst As String) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_DeclareFunction2() Dim code = <Code> Class C Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA"(lpBuffer As String, ByRef nSize As Integer) As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Declare Ansi Function getUserName Lib ""advapi32.dll"" Alias ""GetUserNameA""(ByRef lpBuffer As String, ByRef nSize As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' The is my summary! ''' </summary> ''' <typeparam name="T">Hello from a type parameter</typeparam> ''' <param name="i">The parameter i</param> ''' <param name="s">The parameter t</param> ''' <remarks>Takes <paramref name="i"/> and <paramref name="s"/>.</remarks> Sub M(Of T)(i As Integer, s As String) End Sub End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Of T)(i As Integer, s As String)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "The is my summary!" & vbCrLf & "" & vbCrLf & ServicesVSResources.Type_Parameters_colon & vbCrLf & "T: Hello from a type parameter" & vbCrLf & "" & vbCrLf & ServicesVSResources.Parameters_colon1 & vbCrLf & "i: The parameter i" & vbCrLf & "s: The parameter t" & vbCrLf & "" & vbCrLf & ServicesVSResources.Remarks_colon & vbCrLf & "Takes i and s.") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments_Returns1() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' Describes the method. ''' </summary> ''' <returns>Returns a value.</returns> Function M() As Integer Return 0 End Function End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "Describes the method." & vbCrLf & "" & vbCrLf & ServicesVSResources.Returns_colon & vbCrLf & "Returns a value.") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments_Returns2() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' Gets a value. ''' </summary> ''' <returns>Returns a value.</returns> ReadOnly Property M As Integer End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property M As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "Gets a value." & vbCrLf & "" & vbCrLf & ServicesVSResources.Returns_colon & vbCrLf & "Returns a value.") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments_Value() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' Gets a value. ''' </summary> ''' <value>An integer value.</value> ReadOnly Property M As Integer End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property M As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "Gets a value." & vbCrLf & "" & vbCrLf & ServicesVSResources.Value_colon & vbCrLf & "An integer value.") End Using End Sub <WorkItem(942021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942021")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestNavInfo_Class() Dim code = <Code> Namespace EditorFunctionalityHelper Public Class EditorFunctionalityHelper End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list.VerifyCanonicalNodes(0, ProjectNode("VisualBasicAssembly1"), NamespaceNode("EditorFunctionalityHelper"), TypeNode("EditorFunctionalityHelper")) End Using End Sub <WorkItem(942021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942021")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestNavInfo_NestedEnum() Dim code = <Code> Namespace EditorFunctionalityHelper Public Class EditorFunctionalityHelper Public Enum Mapping EnumOne EnumTwo EnumThree End Enum End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list.VerifyCanonicalNodes(1, ' Mapping ProjectNode("VisualBasicAssembly1"), NamespaceNode("EditorFunctionalityHelper"), TypeNode("EditorFunctionalityHelper"), TypeNode("Mapping")) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ObjectBrowser.VisualBasic Public Class ObjectBrowserTests Inherits AbstractObjectBrowserTests Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property Friend Overrides Function CreateLibraryManager(serviceProvider As IServiceProvider, componentModel As IComponentModel, workspace As VisualStudioWorkspace) As AbstractObjectBrowserLibraryManager Return New ObjectBrowserLibraryManager(serviceProvider, componentModel, workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_NamespaceClassAndMethod() Dim code = <Code> Namespace N Class C Sub M() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list.VerifyNames("VisualBasicAssembly1") list = list.GetNamespaceList(0) list.VerifyNames("N") list = list.GetTypeList(0) list.VerifyNames("C") list = list.GetMemberList(0) list.VerifyNames(AddressOf IsImmediateMember, "M()") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_NoNamespaceWithoutType() Dim code = <Code> Namespace N End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list.VerifyEmpty() End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_InlcudePrivateNestedTypeMembersInSourceCode() Dim code = <Code> Namespace N Class C Private Enum PrivateEnumTest End Enum Private Class PrivateClassTest End Class Private Structure PrivateStructTest End Structure End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0).GetTypeList(0) list.VerifyNames("C", "C.PrivateStructTest", "C.PrivateClassTest", "C.PrivateEnumTest") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_InlcudePrivateDoubleNestedTypeMembersInSourceCode() Dim code = <Code> Namespace N Friend Class C Private Class NestedClass Private Class NestedNestedClass End Class End Class End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0).GetTypeList(0) list.VerifyNames("C", "C.NestedClass", "C.NestedClass.NestedNestedClass") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestSimpleContent_InlcudeNoPrivateNestedTypeOfMetaData() Dim metaDatacode = <Code> Namespace N Public Class C Public Enum PublicEnumTest V1 End Enum Private Class PrivateClassTest End Class Private Structure PrivateStructTest End Structure End Class End Namespace </Code> Dim code = <Code></Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code, metaDatacode, False)) Dim library = state.GetLibrary() Dim list = library.GetProjectList().GetReferenceList(0).GetNamespaceList(0).GetTypeList(0) list.VerifyNames("C", "C.PublicEnumTest") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_InheritedMembers1() Dim code = <Code> Class A Protected Overridable Sub Goo() End Sub End Class Class B Inherits A Protected Overrides Sub Goo() MyBase.Goo() End Sub Overridable Sub Bar() End Sub End Class Class C Inherits B Protected Overrides Sub Goo() MyBase.Goo() End Sub Public Overrides Sub Bar() MyBase.Bar() End Sub End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyNames( "Goo()", "ToString() As String", "Equals(Object) As Boolean", "Equals(Object, Object) As Boolean", "ReferenceEquals(Object, Object) As Boolean", "GetHashCode() As Integer", "GetType() As System.Type", "Finalize()", "MemberwiseClone() As Object") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_InheritedMembers2() Dim code = <Code> Class A Protected Overridable Sub Goo() End Sub End Class Class B Inherits A Protected Overrides Sub Goo() MyBase.Goo() End Sub Overridable Sub Bar() End Sub End Class Class C Inherits B Protected Overrides Sub Goo() MyBase.Goo() End Sub Public Overrides Sub Bar() MyBase.Bar() End Sub End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(1) list.VerifyNames( "Goo()", "Bar()", "ToString() As String", "Equals(Object) As Boolean", "Equals(Object, Object) As Boolean", "ReferenceEquals(Object, Object) As Boolean", "GetHashCode() As Integer", "GetType() As System.Type", "Finalize()", "MemberwiseClone() As Object") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_InheritedMembers3() Dim code = <Code> Class A Protected Overridable Sub Goo() End Sub End Class Class B Inherits A Protected Overrides Sub Goo() MyBase.Goo() End Sub Overridable Sub Bar() End Sub End Class Class C Inherits B Protected Overrides Sub Goo() MyBase.Goo() End Sub Public Overrides Sub Bar() MyBase.Bar() End Sub End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(2) list.VerifyNames( "Goo()", "Bar()", "ToString() As String", "Equals(Object) As Boolean", "Equals(Object, Object) As Boolean", "ReferenceEquals(Object, Object) As Boolean", "GetHashCode() As Integer", "GetType() As System.Type", "Finalize()", "MemberwiseClone() As Object") End Using End Sub <WorkItem(932387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/932387")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestContent_HelpKeyword_Ctor() Dim code = <Code> Namespace N Class C Sub New() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyHelpKeywords("N.C.New") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Project() Dim code = <Code> Namespace N End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list.VerifyDescriptions($"{ServicesVSResources.Project}VisualBasicAssembly1") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Namespace() Dim code = <Code> Namespace N Class C End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list.VerifyDescriptions( "Namespace N" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Delegate1() Dim code = <Code> Delegate Function D(x As Integer) As Boolean </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Delegate Function D(x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Delegate2() Dim code = <Code> Delegate Sub D(y As String) </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Delegate Sub D(y As String)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Delegate3() Dim code = <Code> Delegate Function F(Of T As {Class, New}, U As V, V As List(Of T))(x As T, y As U) As V </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Delegate Function F(Of T As {Class, New}, U As V, V As System.Collections.Generic.List(Of T))(x As T, y As U) As V" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class1() Dim code = <Code> Class C End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Class C" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class2() Dim code = <Code> MustInherit Class C End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend MustInherit Class C" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class3() Dim code = <Code> NotInheritable Class C End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend NotInheritable Class C" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class4() Dim code = <Code> Public Class C(Of T As Class) End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Public Class C(Of T As Class)" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class5() Dim code = <Code> Class C(Of T As Class) Inherits B End Class Class B End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Class C(Of T As Class)" & vbCrLf & " Inherits B" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend Class B" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Class6() Dim code = <Code> MustInherit Class B End Class NotInheritable Class C Inherits B End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend MustInherit Class B" & vbCrLf & " Inherits Object" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend NotInheritable Class C" & vbCrLf & " Inherits B" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Structure1() Dim code = <Code> Structure S End Structure </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Structure S" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Structure2() Dim code = <Code> Public Structure S End Structure </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Public Structure S" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Module1() Dim code = <Code> Module M End Module </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Module M" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Module2() Dim code = <Code> Public Module M End Module </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Public Module M" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Enum1() Dim code = <Code> Enum E A B C End Enum </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Enum E" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Enum2() Dim code = <Code> Enum E As Byte A B C End Enum </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Enum E As Byte" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Interfaces() Dim code = <Code> Interface I1 End Interface Interface I2 Inherits I1 End Interface Interface I3 Inherits I1 Inherits I2 End Interface </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list.VerifyDescriptions( "Friend Interface I1" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend Interface I2" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}", "Friend Interface I3" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "VisualBasicAssembly1")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub1() Dim code = <Code> Namespace N Class C Sub M() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub2() Dim code = <Code> Namespace N Class C Sub M(x As Integer) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(x As Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub3() Dim code = <Code> Namespace N Class C Sub M(ByRef x As Integer) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(ByRef x As Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub4() Dim code = <Code> Namespace N Class C Sub M(Optional x As Integer = 42) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Integer = 42)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub5() Dim code = <Code> Imports System Namespace N Class C Sub M(Optional x As Double = Math.PI) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)), testCulture As New CultureContext(New CultureInfo("en-US", useUserOverride:=False)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Double = 3.14159265358979)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub6() Dim code = <Code> Namespace N Class C Sub M(Optional x As Double? = Nothing) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Double? = Nothing)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Sub7() Dim code = <Code> Namespace N Class C Sub M(Optional x As Double? = 42) End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Optional x As Double? = 42)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WorkItem(939739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939739")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_SubInInterface() Dim code = <Code> Namespace N interface I Sub M() End Interface End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Sub M()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.I")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function1() Dim code = <Code> Namespace N Class C Function M() As Integer End Function End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function2() Dim code = <Code> Namespace N Class C Function M%() End Function End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function3() Dim code = <Code> Namespace N MustInherit Class C MustOverride Function M() As Integer End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public MustOverride Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function4() Dim code = <Code> Namespace N MustInherit Class C Protected Overridable Function M() As Integer End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Protected Overridable Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Function5() Dim code = <Code> Namespace N MustInherit Class C NotOverridable Function M() As Integer End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public NotOverridable Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_IteratorFunction() Dim code = <Code> Imports System.Collections.Generic Namespace N Class C Iterator Function M() As IEnumerable(Of Integer) End Function End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As System.Collections.Generic.IEnumerable(Of Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Constructor() Dim code = <Code> Imports System.Collections.Generic Namespace N Class C Sub New() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub New()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_SharedConstructor() Dim code = <Code> Imports System.Collections.Generic Namespace N Class C Shared Sub New() End Sub End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Shared Sub New()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "N.C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property1() Dim code = <Code> Class C Property P As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property2() Dim code = <Code> Class C Property P() As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property3() Dim code = <Code> Class C Property P% End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property4() Dim code = <Code> Class C Property P As Integer = 42 End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property5() Dim code = <Code> Class C ReadOnly Property P As Integer Get Return 42 End Get End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property6() Dim code = <Code> Class C ReadOnly Property P As Integer Protected Get Return 42 End Get End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property7() Dim code = <Code> Class C WriteOnly Property P As Integer Set(value As Integer) End Set End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public WriteOnly Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property8() Dim code = <Code> Class C Property P As Integer Get End Get Protected Set(value As Integer) End Set End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Property9() Dim code = <Code> Class C Property P(index As Integer) As Integer Get End Get Protected Set(value As Integer) End Set End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Property P(index As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_IteratorProperty() Dim code = <Code> Imports System.Collections.Generic Class C ReadOnly Iterator Property P As IEnumerable(Of Integer) Get End Get End Property End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property P As System.Collections.Generic.IEnumerable(Of Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Const1() Dim code = <Code> Class C Const F As Integer = 42 End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Const F As Integer = 42" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Const2() Dim code = <Code> Class C Const F = 42 End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Const F As Integer = 42" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field1() Dim code = <Code> Class C Dim x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field2() Dim code = <Code> Class C Private x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field3() Dim code = <Code> Class C ReadOnly x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private ReadOnly x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Field4() Dim code = <Code> Class C Shared ReadOnly x As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Private Shared ReadOnly x As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_EnumMembers() Dim code = <Code> Enum E A B C End Enum </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Const A As E = 0" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "E")}", "Public Const B As E = 1" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "E")}", "Public Const C As E = 2" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "E")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Events() Dim code = <Code> Imports System Class C Event E1() Event E2(i As Integer) Event E3 As EventHandler Custom Event E4 As EventHandler AddHandler(value As EventHandler) End AddHandler RemoveHandler(value As EventHandler) End RemoveHandler RaiseEvent(sender As Object, e As EventArgs) End RaiseEvent End Event End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Event E1()" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}", "Public Event E2(i As Integer)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}", "Public Event E3(sender As Object, e As System.EventArgs)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}", "Public Event E4(sender As Object, e As System.EventArgs)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Add() Dim code = <Code> Class C Shared Operator +(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator +(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Subtract() Dim code = <Code> Class C Shared Operator -(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator -(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Multiply() Dim code = <Code> Class C Shared Operator *(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator *(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Divide() Dim code = <Code> Class C Shared Operator /(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator /(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_IntegerDivide() Dim code = <Code> Class C Shared Operator \(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator \(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Modulus() Dim code = <Code> Class C Shared Operator Mod(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Mod(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Power() Dim code = <Code> Class C Shared Operator ^(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator ^(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Concatenate() Dim code = <Code> Class C Shared Operator &amp;(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator &(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Equality() Dim code = <Code> Class C Shared Operator =(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator =(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Inequality() Dim code = <Code> Class C Shared Operator &lt;&gt;(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <>(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_LessThan() Dim code = <Code> Class C Shared Operator &lt;(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_LessThanOrEqualTo() Dim code = <Code> Class C Shared Operator &lt;=(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <=(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_GreaterThan() Dim code = <Code> Class C Shared Operator &gt;(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator >(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_GreaterThanOrEqualTo() Dim code = <Code> Class C Shared Operator &gt;=(c As C, x As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator >=(c As C, x As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Like() Dim code = <Code> Class C Shared Operator Like(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Like(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Not() Dim code = <Code> Class C Shared Operator Not(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Not(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_And() Dim code = <Code> Class C Shared Operator And(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator And(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Or() Dim code = <Code> Class C Shared Operator Or(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Or(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Xor() Dim code = <Code> Class C Shared Operator Xor(c As C, i As Integer) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator Xor(c As C, i As Integer) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_ShiftLeft() Dim code = <Code> Class C Shared Operator &lt;&lt;(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator <<(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_Right() Dim code = <Code> Class C Shared Operator &gt;&gt;(c As C, x As Integer) As Integer End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator >>(c As C, x As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_IsTrue() Dim code = <Code> Class C Shared Operator IsTrue(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator IsTrue(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_IsFalse() Dim code = <Code> Class C Shared Operator IsFalse(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Operator IsFalse(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_CType1() Dim code = <Code> Class C Shared Narrowing Operator CType(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Narrowing Operator CType(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_Operator_CType2() Dim code = <Code> Class C Shared Widening Operator CType(c As C) As Boolean End Operator End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Widening Operator CType(c As C) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_DeclareFunction1() ' Note: DllImport functions that are not Declare should appear as normal functions Dim code = <Code> Imports System.Runtime.InteropServices Class C &lt;DllImportAttribute("kernel32.dll", EntryPoint:="MoveFileW", SetLastError:=True, CharSet:=CharSet.Unicode, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)&gt; Public Shared Function moveFile(ByVal src As String, ByVal dst As String) As Boolean ' This function copies a file from the path src to the path dst. ' Leave this function empty. The DLLImport attribute forces calls ' to moveFile to be forwarded to MoveFileW in KERNEL32.DLL. End Function End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Shared Function moveFile(src As String, dst As String) As Boolean" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_DeclareFunction2() Dim code = <Code> Class C Declare Function getUserName Lib "advapi32.dll" Alias "GetUserNameA"(lpBuffer As String, ByRef nSize As Integer) As Integer End Class </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Declare Ansi Function getUserName Lib ""advapi32.dll"" Alias ""GetUserNameA""(ByRef lpBuffer As String, ByRef nSize As Integer) As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' The is my summary! ''' </summary> ''' <typeparam name="T">Hello from a type parameter</typeparam> ''' <param name="i">The parameter i</param> ''' <param name="s">The parameter t</param> ''' <remarks>Takes <paramref name="i"/> and <paramref name="s"/>.</remarks> Sub M(Of T)(i As Integer, s As String) End Sub End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Sub M(Of T)(i As Integer, s As String)" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "The is my summary!" & vbCrLf & "" & vbCrLf & ServicesVSResources.Type_Parameters_colon & vbCrLf & "T: Hello from a type parameter" & vbCrLf & "" & vbCrLf & ServicesVSResources.Parameters_colon1 & vbCrLf & "i: The parameter i" & vbCrLf & "s: The parameter t" & vbCrLf & "" & vbCrLf & ServicesVSResources.Remarks_colon & vbCrLf & "Takes i and s.") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments_Returns1() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' Describes the method. ''' </summary> ''' <returns>Returns a value.</returns> Function M() As Integer Return 0 End Function End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public Function M() As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "Describes the method." & vbCrLf & "" & vbCrLf & ServicesVSResources.Returns_colon & vbCrLf & "Returns a value.") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments_Returns2() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' Gets a value. ''' </summary> ''' <returns>Returns a value.</returns> ReadOnly Property M As Integer End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property M As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "Gets a value." & vbCrLf & "" & vbCrLf & ServicesVSResources.Returns_colon & vbCrLf & "Returns a value.") End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestDescription_XmlDocComments_Value() Dim code = <Code> <![CDATA[ Class C ''' <summary> ''' Gets a value. ''' </summary> ''' <value>An integer value.</value> ReadOnly Property M As Integer End Class ]]> </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetTypeList(0) list = list.GetMemberList(0) list.VerifyImmediateMemberDescriptions( "Public ReadOnly Property M As Integer" & vbCrLf & $" {String.Format(ServicesVSResources.Member_of_0, "C")}" & vbCrLf & "" & vbCrLf & ServicesVSResources.Summary_colon & vbCrLf & "Gets a value." & vbCrLf & "" & vbCrLf & ServicesVSResources.Value_colon & vbCrLf & "An integer value.") End Using End Sub <WorkItem(942021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942021")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestNavInfo_Class() Dim code = <Code> Namespace EditorFunctionalityHelper Public Class EditorFunctionalityHelper End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list.VerifyCanonicalNodes(0, ProjectNode("VisualBasicAssembly1"), NamespaceNode("EditorFunctionalityHelper"), TypeNode("EditorFunctionalityHelper")) End Using End Sub <WorkItem(942021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/942021")> <WpfFact, Trait(Traits.Feature, Traits.Features.ObjectBrowser)> Public Sub TestNavInfo_NestedEnum() Dim code = <Code> Namespace EditorFunctionalityHelper Public Class EditorFunctionalityHelper Public Enum Mapping EnumOne EnumTwo EnumThree End Enum End Class End Namespace </Code> Using state = CreateLibraryManager(GetWorkspaceDefinition(code)) Dim library = state.GetLibrary() Dim list = library.GetProjectList() list = list.GetNamespaceList(0) list = list.GetTypeList(0) list.VerifyCanonicalNodes(1, ' Mapping ProjectNode("VisualBasicAssembly1"), NamespaceNode("EditorFunctionalityHelper"), TypeNode("EditorFunctionalityHelper"), TypeNode("Mapping")) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/EditorFeatures/Core.Wpf/QuickInfo/LazyToolTip.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { internal partial class ContentControlService { /// <summary> /// Class which allows us to provide a delay-created tooltip for our reference entries. /// </summary> private class LazyToolTip : ForegroundThreadAffinitizedObject { private readonly Func<DisposableToolTip> _createToolTip; private readonly FrameworkElement _element; private DisposableToolTip _disposableToolTip; private LazyToolTip( IThreadingContext threadingContext, FrameworkElement element, Func<DisposableToolTip> createToolTip) : base(threadingContext, assertIsForeground: true) { _element = element; _createToolTip = createToolTip; // Set ourselves as the tooltip of this text block. This will let WPF know that // it should attempt to show tooltips here. When WPF wants to show the tooltip // though we'll hear about it "ToolTipOpening". When that happens, we'll swap // out ourselves with a real tooltip that is lazily created. When that tooltip // is the dismissed, we'll release the resources associated with it and we'll // reattach ourselves. _element.ToolTip = this; element.ToolTipOpening += this.OnToolTipOpening; element.ToolTipClosing += this.OnToolTipClosing; } public static void AttachTo(FrameworkElement element, IThreadingContext threadingContext, Func<DisposableToolTip> createToolTip) => new LazyToolTip(threadingContext, element, createToolTip); private void OnToolTipOpening(object sender, ToolTipEventArgs e) { try { AssertIsForeground(); Debug.Assert(_element.ToolTip == this); Debug.Assert(_disposableToolTip == null); _disposableToolTip = _createToolTip(); _element.ToolTip = _disposableToolTip.ToolTip; } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { // Do nothing, since this is a WPF event handler and propagating the exception would cause a crash } } private void OnToolTipClosing(object sender, ToolTipEventArgs e) { try { AssertIsForeground(); Debug.Assert(_disposableToolTip != null); Debug.Assert(_element.ToolTip == _disposableToolTip.ToolTip); _element.ToolTip = this; _disposableToolTip.Dispose(); _disposableToolTip = null; } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { // Do nothing, since this is a WPF event handler and propagating the exception would cause a crash } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; namespace Microsoft.CodeAnalysis.Editor.QuickInfo { internal partial class ContentControlService { /// <summary> /// Class which allows us to provide a delay-created tooltip for our reference entries. /// </summary> private class LazyToolTip : ForegroundThreadAffinitizedObject { private readonly Func<DisposableToolTip> _createToolTip; private readonly FrameworkElement _element; private DisposableToolTip _disposableToolTip; private LazyToolTip( IThreadingContext threadingContext, FrameworkElement element, Func<DisposableToolTip> createToolTip) : base(threadingContext, assertIsForeground: true) { _element = element; _createToolTip = createToolTip; // Set ourselves as the tooltip of this text block. This will let WPF know that // it should attempt to show tooltips here. When WPF wants to show the tooltip // though we'll hear about it "ToolTipOpening". When that happens, we'll swap // out ourselves with a real tooltip that is lazily created. When that tooltip // is the dismissed, we'll release the resources associated with it and we'll // reattach ourselves. _element.ToolTip = this; element.ToolTipOpening += this.OnToolTipOpening; element.ToolTipClosing += this.OnToolTipClosing; } public static void AttachTo(FrameworkElement element, IThreadingContext threadingContext, Func<DisposableToolTip> createToolTip) => new LazyToolTip(threadingContext, element, createToolTip); private void OnToolTipOpening(object sender, ToolTipEventArgs e) { try { AssertIsForeground(); Debug.Assert(_element.ToolTip == this); Debug.Assert(_disposableToolTip == null); _disposableToolTip = _createToolTip(); _element.ToolTip = _disposableToolTip.ToolTip; } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { // Do nothing, since this is a WPF event handler and propagating the exception would cause a crash } } private void OnToolTipClosing(object sender, ToolTipEventArgs e) { try { AssertIsForeground(); Debug.Assert(_disposableToolTip != null); Debug.Assert(_element.ToolTip == _disposableToolTip.ToolTip); _element.ToolTip = this; _disposableToolTip.Dispose(); _disposableToolTip = null; } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { // Do nothing, since this is a WPF event handler and propagating the exception would cause a crash } } } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/Shared/NamedPipeUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compiler needs to take advantage of features on named pipes which require target framework /// specific APIs. This class is meant to provide a simple, universal interface on top of the /// multi-targeting code that is needed here. /// </summary> internal static class NamedPipeUtil { // Size of the buffers to use: 64K private const int PipeBufferSize = 0x10000; private static string GetPipeNameOrPath(string pipeName) { if (PlatformInformation.IsUnix) { // If we're on a Unix machine then named pipes are implemented using Unix Domain Sockets. // Most Unix systems have a maximum path length limit for Unix Domain Sockets, with // Mac having a particularly short one. Mac also has a generated temp directory that // can be quite long, leaving very little room for the actual pipe name. Fortunately, // '/tmp' is mandated by POSIX to always be a valid temp directory, so we can use that // instead. return Path.Combine("/tmp", pipeName); } else { return pipeName; } } /// <summary> /// Create a client for the current user only. /// </summary> internal static NamedPipeClientStream CreateClient(string serverName, string pipeName, PipeDirection direction, PipeOptions options) => new NamedPipeClientStream(serverName, GetPipeNameOrPath(pipeName), direction, options | CurrentUserOption); /// <summary> /// Does the client of "pipeStream" have the same identity and elevation as we do? The <see cref="CreateClient"/> and /// <see cref="CreateServer(string, PipeDirection?)" /> methods will already guarantee that the identity of the client and server are the /// same. This method is attempting to validate that the elevation level is the same between both ends of the /// named pipe (want to disallow low priv session sending compilation requests to an elevated one). /// </summary> internal static bool CheckClientElevationMatches(NamedPipeServerStream pipeStream) { if (PlatformInformation.IsWindows) { var serverIdentity = getIdentity(impersonating: false); (string name, bool admin) clientIdentity = default; pipeStream.RunAsClient(() => { clientIdentity = getIdentity(impersonating: true); }); return StringComparer.OrdinalIgnoreCase.Equals(serverIdentity.name, clientIdentity.name) && serverIdentity.admin == clientIdentity.admin; (string name, bool admin) getIdentity(bool impersonating) { var currentIdentity = WindowsIdentity.GetCurrent(impersonating); var currentPrincipal = new WindowsPrincipal(currentIdentity); var elevatedToAdmin = currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator); return (currentIdentity.Name, elevatedToAdmin); } } return true; } /// <summary> /// Create a server for the current user only /// </summary> internal static NamedPipeServerStream CreateServer(string pipeName, PipeDirection? pipeDirection = null) { var pipeOptions = PipeOptions.Asynchronous | PipeOptions.WriteThrough; return CreateServer( pipeName, pipeDirection ?? PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, pipeOptions, PipeBufferSize, PipeBufferSize); } #if NET472 const int s_currentUserOnlyValue = 0x20000000; /// <summary> /// Mono supports CurrentUserOnly even though it's not exposed on the reference assemblies for net472. This /// must be used because ACL security does not work. /// </summary> private static readonly PipeOptions CurrentUserOption = PlatformInformation.IsRunningOnMono ? (PipeOptions)s_currentUserOnlyValue : PipeOptions.None; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize, CreatePipeSecurity(), HandleInheritability.None); /// <summary> /// Check to ensure that the named pipe server we connected to is owned by the same /// user. /// </summary> internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) { if (PlatformInformation.IsWindows) { var currentIdentity = WindowsIdentity.GetCurrent(); var currentOwner = currentIdentity.Owner; var remotePipeSecurity = pipeStream.GetAccessControl(); var remoteOwner = remotePipeSecurity.GetOwner(typeof(SecurityIdentifier)); return currentOwner.Equals(remoteOwner); } // Client side validation isn't supported on Unix. The model relies on the server side // security here. return true; } internal static PipeSecurity? CreatePipeSecurity() { if (PlatformInformation.IsRunningOnMono) { // Pipe security and additional access rights constructor arguments // are not supported by Mono // https://github.com/dotnet/roslyn/pull/30810 // https://github.com/mono/mono/issues/11406 return null; } var security = new PipeSecurity(); SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; // Restrict access to just this account. PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); security.AddAccessRule(rule); security.SetOwner(identifier); return security; } #elif NETCOREAPP private const PipeOptions CurrentUserOption = PipeOptions.CurrentUserOnly; // Validation is handled by CurrentUserOnly internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) => true; // Validation is handled by CurrentUserOnly internal static PipeSecurity? CreatePipeSecurity() => null; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize); #else #error Unsupported configuration #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Principal; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compiler needs to take advantage of features on named pipes which require target framework /// specific APIs. This class is meant to provide a simple, universal interface on top of the /// multi-targeting code that is needed here. /// </summary> internal static class NamedPipeUtil { // Size of the buffers to use: 64K private const int PipeBufferSize = 0x10000; private static string GetPipeNameOrPath(string pipeName) { if (PlatformInformation.IsUnix) { // If we're on a Unix machine then named pipes are implemented using Unix Domain Sockets. // Most Unix systems have a maximum path length limit for Unix Domain Sockets, with // Mac having a particularly short one. Mac also has a generated temp directory that // can be quite long, leaving very little room for the actual pipe name. Fortunately, // '/tmp' is mandated by POSIX to always be a valid temp directory, so we can use that // instead. return Path.Combine("/tmp", pipeName); } else { return pipeName; } } /// <summary> /// Create a client for the current user only. /// </summary> internal static NamedPipeClientStream CreateClient(string serverName, string pipeName, PipeDirection direction, PipeOptions options) => new NamedPipeClientStream(serverName, GetPipeNameOrPath(pipeName), direction, options | CurrentUserOption); /// <summary> /// Does the client of "pipeStream" have the same identity and elevation as we do? The <see cref="CreateClient"/> and /// <see cref="CreateServer(string, PipeDirection?)" /> methods will already guarantee that the identity of the client and server are the /// same. This method is attempting to validate that the elevation level is the same between both ends of the /// named pipe (want to disallow low priv session sending compilation requests to an elevated one). /// </summary> internal static bool CheckClientElevationMatches(NamedPipeServerStream pipeStream) { if (PlatformInformation.IsWindows) { var serverIdentity = getIdentity(impersonating: false); (string name, bool admin) clientIdentity = default; pipeStream.RunAsClient(() => { clientIdentity = getIdentity(impersonating: true); }); return StringComparer.OrdinalIgnoreCase.Equals(serverIdentity.name, clientIdentity.name) && serverIdentity.admin == clientIdentity.admin; (string name, bool admin) getIdentity(bool impersonating) { var currentIdentity = WindowsIdentity.GetCurrent(impersonating); var currentPrincipal = new WindowsPrincipal(currentIdentity); var elevatedToAdmin = currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator); return (currentIdentity.Name, elevatedToAdmin); } } return true; } /// <summary> /// Create a server for the current user only /// </summary> internal static NamedPipeServerStream CreateServer(string pipeName, PipeDirection? pipeDirection = null) { var pipeOptions = PipeOptions.Asynchronous | PipeOptions.WriteThrough; return CreateServer( pipeName, pipeDirection ?? PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, pipeOptions, PipeBufferSize, PipeBufferSize); } #if NET472 const int s_currentUserOnlyValue = 0x20000000; /// <summary> /// Mono supports CurrentUserOnly even though it's not exposed on the reference assemblies for net472. This /// must be used because ACL security does not work. /// </summary> private static readonly PipeOptions CurrentUserOption = PlatformInformation.IsRunningOnMono ? (PipeOptions)s_currentUserOnlyValue : PipeOptions.None; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize, CreatePipeSecurity(), HandleInheritability.None); /// <summary> /// Check to ensure that the named pipe server we connected to is owned by the same /// user. /// </summary> internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) { if (PlatformInformation.IsWindows) { var currentIdentity = WindowsIdentity.GetCurrent(); var currentOwner = currentIdentity.Owner; var remotePipeSecurity = pipeStream.GetAccessControl(); var remoteOwner = remotePipeSecurity.GetOwner(typeof(SecurityIdentifier)); return currentOwner.Equals(remoteOwner); } // Client side validation isn't supported on Unix. The model relies on the server side // security here. return true; } internal static PipeSecurity? CreatePipeSecurity() { if (PlatformInformation.IsRunningOnMono) { // Pipe security and additional access rights constructor arguments // are not supported by Mono // https://github.com/dotnet/roslyn/pull/30810 // https://github.com/mono/mono/issues/11406 return null; } var security = new PipeSecurity(); SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner; // Restrict access to just this account. PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow); security.AddAccessRule(rule); security.SetOwner(identifier); return security; } #elif NETCOREAPP private const PipeOptions CurrentUserOption = PipeOptions.CurrentUserOnly; // Validation is handled by CurrentUserOnly internal static bool CheckPipeConnectionOwnership(NamedPipeClientStream pipeStream) => true; // Validation is handled by CurrentUserOnly internal static PipeSecurity? CreatePipeSecurity() => null; private static NamedPipeServerStream CreateServer( string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize) => new NamedPipeServerStream( GetPipeNameOrPath(pipeName), direction, maxNumberOfServerInstances, transmissionMode, options | CurrentUserOption, inBufferSize, outBufferSize); #else #error Unsupported configuration #endif } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Engine/CSharpStructuredTriviaFormatEngine.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class CSharpStructuredTriviaFormatEngine : AbstractFormatEngine { public static IFormattingResult Format( SyntaxTrivia trivia, int initialColumn, AnalyzerConfigOptions options, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { var root = trivia.GetStructure() ?? throw new ArgumentException(); var formatter = new CSharpStructuredTriviaFormatEngine(trivia, initialColumn, options, formattingRules, root.GetFirstToken(includeZeroWidth: true), root.GetLastToken(includeZeroWidth: true)); return formatter.Format(cancellationToken); } private CSharpStructuredTriviaFormatEngine( SyntaxTrivia trivia, int initialColumn, AnalyzerConfigOptions options, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2) : base(TreeData.Create(trivia, initialColumn), options, formattingRules, token1, token2) { } internal override IHeaderFacts HeaderFacts => CSharpHeaderFacts.Instance; protected override AbstractTriviaDataFactory CreateTriviaFactory() => new TriviaDataFactory(this.TreeData, this.Options); protected override FormattingContext CreateFormattingContext(TokenStream tokenStream, CancellationToken cancellationToken) => new(this, tokenStream); protected override NodeOperations CreateNodeOperations(CancellationToken cancellationToken) { // ignore all node operations for structured trivia since it is not possible for this to have any impact currently. return NodeOperations.Empty; } protected override AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream) => new FormattingResult(this.TreeData, tokenStream, this.SpanToFormat); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.Formatting { internal class CSharpStructuredTriviaFormatEngine : AbstractFormatEngine { public static IFormattingResult Format( SyntaxTrivia trivia, int initialColumn, AnalyzerConfigOptions options, ChainedFormattingRules formattingRules, CancellationToken cancellationToken) { var root = trivia.GetStructure() ?? throw new ArgumentException(); var formatter = new CSharpStructuredTriviaFormatEngine(trivia, initialColumn, options, formattingRules, root.GetFirstToken(includeZeroWidth: true), root.GetLastToken(includeZeroWidth: true)); return formatter.Format(cancellationToken); } private CSharpStructuredTriviaFormatEngine( SyntaxTrivia trivia, int initialColumn, AnalyzerConfigOptions options, ChainedFormattingRules formattingRules, SyntaxToken token1, SyntaxToken token2) : base(TreeData.Create(trivia, initialColumn), options, formattingRules, token1, token2) { } internal override IHeaderFacts HeaderFacts => CSharpHeaderFacts.Instance; protected override AbstractTriviaDataFactory CreateTriviaFactory() => new TriviaDataFactory(this.TreeData, this.Options); protected override FormattingContext CreateFormattingContext(TokenStream tokenStream, CancellationToken cancellationToken) => new(this, tokenStream); protected override NodeOperations CreateNodeOperations(CancellationToken cancellationToken) { // ignore all node operations for structured trivia since it is not possible for this to have any impact currently. return NodeOperations.Empty; } protected override AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream) => new FormattingResult(this.TreeData, tokenStream, this.SpanToFormat); } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Analyzers/CSharp/CodeFixes/UsePatternMatching/CSharpIsAndCastCheckCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePatternMatchingIsAndCastCheck), Shared] internal partial class CSharpIsAndCastCheckCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpIsAndCastCheckCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.InlineIsTypeCheckId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } return Task.CompletedTask; } private static void AddEdits( SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken) { var ifStatementLocation = diagnostic.AdditionalLocations[0]; var localDeclarationLocation = diagnostic.AdditionalLocations[1]; var ifStatement = (IfStatementSyntax)ifStatementLocation.FindNode(cancellationToken); var localDeclaration = (LocalDeclarationStatementSyntax)localDeclarationLocation.FindNode(cancellationToken); var isExpression = (BinaryExpressionSyntax)ifStatement.Condition; var updatedCondition = SyntaxFactory.IsPatternExpression( isExpression.Left, SyntaxFactory.DeclarationPattern( ((TypeSyntax)isExpression.Right).WithoutTrivia(), SyntaxFactory.SingleVariableDesignation( localDeclaration.Declaration.Variables[0].Identifier.WithoutTrivia()))); var trivia = localDeclaration.GetLeadingTrivia().Concat(localDeclaration.GetTrailingTrivia()) .Where(t => t.IsSingleOrMultiLineComment()) .SelectMany(t => ImmutableArray.Create(SyntaxFactory.Space, t, SyntaxFactory.ElasticCarriageReturnLineFeed)) .ToImmutableArray(); editor.RemoveNode(localDeclaration); editor.ReplaceNode(ifStatement, (i, g) => { // Because the local declaration is *inside* the 'if', we need to get the 'if' // statement after it was already modified and *then* update the condition // portion of it. var currentIf = (IfStatementSyntax)i; return GetUpdatedIfStatement(updatedCondition, trivia, ifStatement, currentIf); }); } private static IfStatementSyntax GetUpdatedIfStatement( IsPatternExpressionSyntax updatedCondition, ImmutableArray<SyntaxTrivia> trivia, IfStatementSyntax originalIf, IfStatementSyntax currentIf) { var newIf = currentIf.ReplaceNode(currentIf.Condition, updatedCondition); newIf = originalIf.IsParentKind(SyntaxKind.ElseClause) ? newIf.ReplaceToken(newIf.CloseParenToken, newIf.CloseParenToken.WithTrailingTrivia(trivia)) : newIf.WithPrependedLeadingTrivia(trivia); return newIf.WithAdditionalAnnotations(Formatter.Annotation); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_pattern_matching, createChangedDocument, nameof(CSharpIsAndCastCheckCodeFixProvider)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UsePatternMatching { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UsePatternMatchingIsAndCastCheck), Shared] internal partial class CSharpIsAndCastCheckCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpIsAndCastCheckCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.InlineIsTypeCheckId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { cancellationToken.ThrowIfCancellationRequested(); AddEdits(editor, diagnostic, cancellationToken); } return Task.CompletedTask; } private static void AddEdits( SyntaxEditor editor, Diagnostic diagnostic, CancellationToken cancellationToken) { var ifStatementLocation = diagnostic.AdditionalLocations[0]; var localDeclarationLocation = diagnostic.AdditionalLocations[1]; var ifStatement = (IfStatementSyntax)ifStatementLocation.FindNode(cancellationToken); var localDeclaration = (LocalDeclarationStatementSyntax)localDeclarationLocation.FindNode(cancellationToken); var isExpression = (BinaryExpressionSyntax)ifStatement.Condition; var updatedCondition = SyntaxFactory.IsPatternExpression( isExpression.Left, SyntaxFactory.DeclarationPattern( ((TypeSyntax)isExpression.Right).WithoutTrivia(), SyntaxFactory.SingleVariableDesignation( localDeclaration.Declaration.Variables[0].Identifier.WithoutTrivia()))); var trivia = localDeclaration.GetLeadingTrivia().Concat(localDeclaration.GetTrailingTrivia()) .Where(t => t.IsSingleOrMultiLineComment()) .SelectMany(t => ImmutableArray.Create(SyntaxFactory.Space, t, SyntaxFactory.ElasticCarriageReturnLineFeed)) .ToImmutableArray(); editor.RemoveNode(localDeclaration); editor.ReplaceNode(ifStatement, (i, g) => { // Because the local declaration is *inside* the 'if', we need to get the 'if' // statement after it was already modified and *then* update the condition // portion of it. var currentIf = (IfStatementSyntax)i; return GetUpdatedIfStatement(updatedCondition, trivia, ifStatement, currentIf); }); } private static IfStatementSyntax GetUpdatedIfStatement( IsPatternExpressionSyntax updatedCondition, ImmutableArray<SyntaxTrivia> trivia, IfStatementSyntax originalIf, IfStatementSyntax currentIf) { var newIf = currentIf.ReplaceNode(currentIf.Condition, updatedCondition); newIf = originalIf.IsParentKind(SyntaxKind.ElseClause) ? newIf.ReplaceToken(newIf.CloseParenToken, newIf.CloseParenToken.WithTrailingTrivia(trivia)) : newIf.WithPrependedLeadingTrivia(trivia); return newIf.WithAdditionalAnnotations(Formatter.Annotation); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_pattern_matching, createChangedDocument, nameof(CSharpIsAndCastCheckCodeFixProvider)) { } } } }
-1
dotnet/roslyn
56,285
Unify code for pragma placements
Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
davidwengier
"2021-09-09T08:05:52Z"
"2021-10-06T10:16:53Z"
a9d93d2049296c31e159fdd75e638aad4b5c8989
83bddcb0b52a206a4033eb6f3f074ebebbcdd6de
Unify code for pragma placements. Fixes https://github.com/dotnet/roslyn/issues/56165 The VB code was already doing what seemed like the right thing, so pretty much just moved it up 🤷‍♂️
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinueTestBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Metadata.Tools; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public abstract class EditAndContinueTestBase : EmitMetadataTestBase { // PDB reader can only be accessed from a single thread, so avoid concurrent compilation: protected readonly CSharpCompilationOptions ComSafeDebugDll = TestOptions.DebugDll.WithConcurrentBuild(false); internal static readonly Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> EmptyLocalsProvider = handle => default(EditAndContinueMethodDebugInformation); internal static string Visualize(ModuleMetadata baseline, params PinnedMetadata[] deltas) { var result = new StringWriter(); new MetadataVisualizer(new[] { baseline.MetadataReader }.Concat(deltas.Select(d => d.Reader)).ToArray(), result).VisualizeAllGenerations(); return result.ToString(); } internal static SourceWithMarkedNodes MarkedSource(string markedSource, string fileName = "", CSharpParseOptions options = null, bool removeTags = false) { return new SourceWithMarkedNodes(markedSource, s => Parse(s, fileName, options), s => (int)(SyntaxKind)typeof(SyntaxKind).GetField(s).GetValue(null), removeTags); } internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapFromMarkers(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1) { return SourceWithMarkedNodes.GetSyntaxMap(source0, source1); } internal static ImmutableArray<SyntaxNode> GetAllLocals(MethodSymbol method) { var sourceMethod = method as SourceMemberMethodSymbol; if (sourceMethod == null) { return ImmutableArray<SyntaxNode>.Empty; } return LocalVariableDeclaratorsCollector.GetDeclarators(sourceMethod); } internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapByKind(MethodSymbol method0, params SyntaxKind[] kinds) { return newNode => { foreach (SyntaxKind kind in kinds) { if (newNode.IsKind(kind)) { return method0.DeclaringSyntaxReferences.Single().SyntaxTree.GetRoot().DescendantNodes().Single(n => n.IsKind(kind)); } } return null; }; } internal static Func<SyntaxNode, SyntaxNode> GetEquivalentNodesMap(MethodSymbol method1, MethodSymbol method0) { var tree1 = method1.Locations[0].SourceTree; var tree0 = method0.Locations[0].SourceTree; Assert.NotEqual(tree1, tree0); var locals0 = GetAllLocals(method0); return s => { var s1 = s; Assert.Equal(s1.SyntaxTree, tree1); foreach (var s0 in locals0) { if (!SyntaxFactory.AreEquivalent(s0, s1)) { continue; } // Make sure the containing statements are the same. var p0 = GetNearestStatement(s0); var p1 = GetNearestStatement(s1); if (SyntaxFactory.AreEquivalent(p0, p1)) { return s0; } } return null; }; } internal static string GetLocalName(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)node).Identifier.ToString(); default: throw new NotImplementedException(); } } internal static StatementSyntax GetNearestStatement(SyntaxNode node) { while (node != null) { var statement = node as StatementSyntax; if (statement != null) { return statement; } node = node.Parent; } return null; } internal static SemanticEditDescription Edit(SemanticEditKind kind, Func<Compilation, ISymbol> symbolProvider) => new(kind, symbolProvider); internal static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) { return new EditAndContinueLogEntry(MetadataTokens.Handle(table, rowNumber), operation); } internal static EntityHandle Handle(int rowNumber, TableIndex table) { return MetadataTokens.Handle(table, rowNumber); } internal static bool IsDefinition(HandleKind kind) => kind is not (HandleKind.AssemblyReference or HandleKind.ModuleReference or HandleKind.TypeReference or HandleKind.MemberReference or HandleKind.TypeSpecification or HandleKind.MethodSpecification); internal static void CheckEncLog(MetadataReader reader, params EditAndContinueLogEntry[] rows) { AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } /// <summary> /// Checks that the EncLog contains specified definition rows. References are ignored as they are usually not interesting to validate. They are emitted as needed. /// </summary> internal static void CheckEncLogDefinitions(MetadataReader reader, params EditAndContinueLogEntry[] rows) { AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString); } internal static void CheckEncMap(MetadataReader reader, params EntityHandle[] handles) { AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString); } internal static void CheckEncMapDefinitions(MetadataReader reader, params EntityHandle[] handles) { AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString); } internal static void CheckAttributes(MetadataReader reader, params CustomAttributeRow[] rows) { AssertEx.Equal(rows, reader.GetCustomAttributeRows(), itemInspector: AttributeRowToString); } internal static void CheckNames(MetadataReader reader, IEnumerable<StringHandle> handles, params string[] expectedNames) { CheckNames(new[] { reader }, handles, expectedNames); } internal static void CheckNames(IEnumerable<MetadataReader> readers, IEnumerable<StringHandle> handles, params string[] expectedNames) { var actualNames = readers.GetStrings(handles); AssertEx.Equal(expectedNames, actualNames); } internal static void CheckNames(IList<MetadataReader> readers, IEnumerable<(StringHandle Namespace, StringHandle Name)> handles, params string[] expectedNames) { var actualNames = handles.Select(handlePair => string.Join(".", readers.GetString(handlePair.Namespace), readers.GetString(handlePair.Name))).ToArray(); AssertEx.Equal(expectedNames, actualNames); } public static void CheckNames(IList<MetadataReader> readers, ImmutableArray<TypeDefinitionHandle> typeHandles, params string[] expectedNames) => CheckNames(readers, typeHandles, (reader, handle) => reader.GetTypeDefinition((TypeDefinitionHandle)handle).Name, handle => handle, expectedNames); public static void CheckNames(IList<MetadataReader> readers, ImmutableArray<MethodDefinitionHandle> methodHandles, params string[] expectedNames) => CheckNames(readers, methodHandles, (reader, handle) => reader.GetMethodDefinition((MethodDefinitionHandle)handle).Name, handle => handle, expectedNames); private static void CheckNames<THandle>( IList<MetadataReader> readers, ImmutableArray<THandle> entityHandles, Func<MetadataReader, Handle, StringHandle> getName, Func<THandle, Handle> toHandle, string[] expectedNames) { var aggregator = new MetadataAggregator(readers[0], readers.Skip(1).ToArray()); AssertEx.Equal(expectedNames, entityHandles.Select(handle => { var genEntityHandle = aggregator.GetGenerationHandle(toHandle(handle), out int typeGeneration); var nameHandle = getName(readers[typeGeneration], genEntityHandle); var genNameHandle = (StringHandle)aggregator.GetGenerationHandle(nameHandle, out int nameGeneration); return readers[nameGeneration].GetString(genNameHandle); })); } internal static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } internal static string EncMapRowToString(EntityHandle handle) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(handle.Kind, out tableIndex); return string.Format( "Handle({0}, TableIndex.{1})", MetadataTokens.GetRowNumber(handle), tableIndex); } internal static string AttributeRowToString(CustomAttributeRow row) { TableIndex parentTableIndex, constructorTableIndex; MetadataTokens.TryGetTableIndex(row.ParentToken.Kind, out parentTableIndex); MetadataTokens.TryGetTableIndex(row.ConstructorToken.Kind, out constructorTableIndex); return string.Format( "new CustomAttributeRow(Handle({0}, TableIndex.{1}), Handle({2}, TableIndex.{3}))", MetadataTokens.GetRowNumber(row.ParentToken), parentTableIndex, MetadataTokens.GetRowNumber(row.ConstructorToken), constructorTableIndex); } internal static void SaveImages(string outputDirectory, CompilationVerifier baseline, params CompilationDifference[] diffs) { bool IsPortablePdb(ImmutableArray<byte> image) => image[0] == 'B' && image[1] == 'S' && image[2] == 'J' && image[3] == 'B'; string baseName = baseline.Compilation.AssemblyName; string extSuffix = IsPortablePdb(baseline.EmittedAssemblyPdb) ? "x" : ""; Directory.CreateDirectory(outputDirectory); File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".dll" + extSuffix), baseline.EmittedAssemblyData.ToArray()); File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".pdb" + extSuffix), baseline.EmittedAssemblyPdb.ToArray()); for (int i = 0; i < diffs.Length; i++) { File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.metadata{extSuffix}"), diffs[i].MetadataDelta.ToArray()); File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.pdb{extSuffix}"), diffs[i].PdbDelta.ToArray()); } } } public static class EditAndContinueTestExtensions { internal static CSharpCompilation WithSource(this CSharpCompilation compilation, CSharpTestSource newSource) { return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newSource.GetSyntaxTrees(TestOptions.Regular)); } internal static CSharpCompilation WithSource(this CSharpCompilation compilation, SyntaxTree newTree) { return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newTree); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.Metadata.Tools; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public abstract class EditAndContinueTestBase : EmitMetadataTestBase { // PDB reader can only be accessed from a single thread, so avoid concurrent compilation: protected readonly CSharpCompilationOptions ComSafeDebugDll = TestOptions.DebugDll.WithConcurrentBuild(false); internal static readonly Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> EmptyLocalsProvider = handle => default(EditAndContinueMethodDebugInformation); internal static string Visualize(ModuleMetadata baseline, params PinnedMetadata[] deltas) { var result = new StringWriter(); new MetadataVisualizer(new[] { baseline.MetadataReader }.Concat(deltas.Select(d => d.Reader)).ToArray(), result).VisualizeAllGenerations(); return result.ToString(); } internal static SourceWithMarkedNodes MarkedSource(string markedSource, string fileName = "", CSharpParseOptions options = null, bool removeTags = false) { return new SourceWithMarkedNodes(markedSource, s => Parse(s, fileName, options), s => (int)(SyntaxKind)typeof(SyntaxKind).GetField(s).GetValue(null), removeTags); } internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapFromMarkers(SourceWithMarkedNodes source0, SourceWithMarkedNodes source1) { return SourceWithMarkedNodes.GetSyntaxMap(source0, source1); } internal static ImmutableArray<SyntaxNode> GetAllLocals(MethodSymbol method) { var sourceMethod = method as SourceMemberMethodSymbol; if (sourceMethod == null) { return ImmutableArray<SyntaxNode>.Empty; } return LocalVariableDeclaratorsCollector.GetDeclarators(sourceMethod); } internal static Func<SyntaxNode, SyntaxNode> GetSyntaxMapByKind(MethodSymbol method0, params SyntaxKind[] kinds) { return newNode => { foreach (SyntaxKind kind in kinds) { if (newNode.IsKind(kind)) { return method0.DeclaringSyntaxReferences.Single().SyntaxTree.GetRoot().DescendantNodes().Single(n => n.IsKind(kind)); } } return null; }; } internal static Func<SyntaxNode, SyntaxNode> GetEquivalentNodesMap(MethodSymbol method1, MethodSymbol method0) { var tree1 = method1.Locations[0].SourceTree; var tree0 = method0.Locations[0].SourceTree; Assert.NotEqual(tree1, tree0); var locals0 = GetAllLocals(method0); return s => { var s1 = s; Assert.Equal(s1.SyntaxTree, tree1); foreach (var s0 in locals0) { if (!SyntaxFactory.AreEquivalent(s0, s1)) { continue; } // Make sure the containing statements are the same. var p0 = GetNearestStatement(s0); var p1 = GetNearestStatement(s1); if (SyntaxFactory.AreEquivalent(p0, p1)) { return s0; } } return null; }; } internal static string GetLocalName(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.VariableDeclarator: return ((VariableDeclaratorSyntax)node).Identifier.ToString(); default: throw new NotImplementedException(); } } internal static StatementSyntax GetNearestStatement(SyntaxNode node) { while (node != null) { var statement = node as StatementSyntax; if (statement != null) { return statement; } node = node.Parent; } return null; } internal static SemanticEditDescription Edit(SemanticEditKind kind, Func<Compilation, ISymbol> symbolProvider) => new(kind, symbolProvider); internal static EditAndContinueLogEntry Row(int rowNumber, TableIndex table, EditAndContinueOperation operation) { return new EditAndContinueLogEntry(MetadataTokens.Handle(table, rowNumber), operation); } internal static EntityHandle Handle(int rowNumber, TableIndex table) { return MetadataTokens.Handle(table, rowNumber); } internal static bool IsDefinition(HandleKind kind) => kind is not (HandleKind.AssemblyReference or HandleKind.ModuleReference or HandleKind.TypeReference or HandleKind.MemberReference or HandleKind.TypeSpecification or HandleKind.MethodSpecification); internal static void CheckEncLog(MetadataReader reader, params EditAndContinueLogEntry[] rows) { AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries(), itemInspector: EncLogRowToString); } /// <summary> /// Checks that the EncLog contains specified definition rows. References are ignored as they are usually not interesting to validate. They are emitted as needed. /// </summary> internal static void CheckEncLogDefinitions(MetadataReader reader, params EditAndContinueLogEntry[] rows) { AssertEx.Equal(rows, reader.GetEditAndContinueLogEntries().Where(e => IsDefinition(e.Handle.Kind)), itemInspector: EncLogRowToString); } internal static void CheckEncMap(MetadataReader reader, params EntityHandle[] handles) { AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries(), itemInspector: EncMapRowToString); } internal static void CheckEncMapDefinitions(MetadataReader reader, params EntityHandle[] handles) { AssertEx.Equal(handles, reader.GetEditAndContinueMapEntries().Where(e => IsDefinition(e.Kind)), itemInspector: EncMapRowToString); } internal static void CheckAttributes(MetadataReader reader, params CustomAttributeRow[] rows) { AssertEx.Equal(rows, reader.GetCustomAttributeRows(), itemInspector: AttributeRowToString); } internal static void CheckNames(MetadataReader reader, IEnumerable<StringHandle> handles, params string[] expectedNames) { CheckNames(new[] { reader }, handles, expectedNames); } internal static void CheckNames(IEnumerable<MetadataReader> readers, IEnumerable<StringHandle> handles, params string[] expectedNames) { var actualNames = readers.GetStrings(handles); AssertEx.Equal(expectedNames, actualNames); } internal static void CheckNames(IList<MetadataReader> readers, IEnumerable<(StringHandle Namespace, StringHandle Name)> handles, params string[] expectedNames) { var actualNames = handles.Select(handlePair => string.Join(".", readers.GetString(handlePair.Namespace), readers.GetString(handlePair.Name))).ToArray(); AssertEx.Equal(expectedNames, actualNames); } public static void CheckNames(IList<MetadataReader> readers, ImmutableArray<TypeDefinitionHandle> typeHandles, params string[] expectedNames) => CheckNames(readers, typeHandles, (reader, handle) => reader.GetTypeDefinition((TypeDefinitionHandle)handle).Name, handle => handle, expectedNames); public static void CheckNames(IList<MetadataReader> readers, ImmutableArray<MethodDefinitionHandle> methodHandles, params string[] expectedNames) => CheckNames(readers, methodHandles, (reader, handle) => reader.GetMethodDefinition((MethodDefinitionHandle)handle).Name, handle => handle, expectedNames); private static void CheckNames<THandle>( IList<MetadataReader> readers, ImmutableArray<THandle> entityHandles, Func<MetadataReader, Handle, StringHandle> getName, Func<THandle, Handle> toHandle, string[] expectedNames) { var aggregator = new MetadataAggregator(readers[0], readers.Skip(1).ToArray()); AssertEx.Equal(expectedNames, entityHandles.Select(handle => { var genEntityHandle = aggregator.GetGenerationHandle(toHandle(handle), out int typeGeneration); var nameHandle = getName(readers[typeGeneration], genEntityHandle); var genNameHandle = (StringHandle)aggregator.GetGenerationHandle(nameHandle, out int nameGeneration); return readers[nameGeneration].GetString(genNameHandle); })); } internal static string EncLogRowToString(EditAndContinueLogEntry row) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(row.Handle.Kind, out tableIndex); return string.Format( "Row({0}, TableIndex.{1}, EditAndContinueOperation.{2})", MetadataTokens.GetRowNumber(row.Handle), tableIndex, row.Operation); } internal static string EncMapRowToString(EntityHandle handle) { TableIndex tableIndex; MetadataTokens.TryGetTableIndex(handle.Kind, out tableIndex); return string.Format( "Handle({0}, TableIndex.{1})", MetadataTokens.GetRowNumber(handle), tableIndex); } internal static string AttributeRowToString(CustomAttributeRow row) { TableIndex parentTableIndex, constructorTableIndex; MetadataTokens.TryGetTableIndex(row.ParentToken.Kind, out parentTableIndex); MetadataTokens.TryGetTableIndex(row.ConstructorToken.Kind, out constructorTableIndex); return string.Format( "new CustomAttributeRow(Handle({0}, TableIndex.{1}), Handle({2}, TableIndex.{3}))", MetadataTokens.GetRowNumber(row.ParentToken), parentTableIndex, MetadataTokens.GetRowNumber(row.ConstructorToken), constructorTableIndex); } internal static void SaveImages(string outputDirectory, CompilationVerifier baseline, params CompilationDifference[] diffs) { bool IsPortablePdb(ImmutableArray<byte> image) => image[0] == 'B' && image[1] == 'S' && image[2] == 'J' && image[3] == 'B'; string baseName = baseline.Compilation.AssemblyName; string extSuffix = IsPortablePdb(baseline.EmittedAssemblyPdb) ? "x" : ""; Directory.CreateDirectory(outputDirectory); File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".dll" + extSuffix), baseline.EmittedAssemblyData.ToArray()); File.WriteAllBytes(Path.Combine(outputDirectory, baseName + ".pdb" + extSuffix), baseline.EmittedAssemblyPdb.ToArray()); for (int i = 0; i < diffs.Length; i++) { File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.metadata{extSuffix}"), diffs[i].MetadataDelta.ToArray()); File.WriteAllBytes(Path.Combine(outputDirectory, $"{baseName}.{i + 1}.pdb{extSuffix}"), diffs[i].PdbDelta.ToArray()); } } } public static class EditAndContinueTestExtensions { internal static CSharpCompilation WithSource(this CSharpCompilation compilation, CSharpTestSource newSource) { return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newSource.GetSyntaxTrees(TestOptions.Regular)); } internal static CSharpCompilation WithSource(this CSharpCompilation compilation, SyntaxTree newTree) { return compilation.RemoveAllSyntaxTrees().AddSyntaxTrees(newTree); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Emitter/Model/PEModuleBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState> { // TODO: Need to estimate amount of elements for this map and pass that value to the constructor. protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>(); private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything); private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>(); private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt; public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt => _embeddedTypesManagerOpt; // Gives the name of this module (may not reflect the name of the underlying symbol). // See Assembly.MetadataName. private readonly string _metadataName; private ImmutableArray<Cci.ExportedType> _lazyExportedTypes; /// <summary> /// The compiler-generated implementation type for each fixed-size buffer. /// </summary> private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return GetNeedsGeneratedAttributesInternal(); } private EmbeddableAttributes GetNeedsGeneratedAttributesInternal() { return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes(); } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal PEModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, new ModuleCompilationState()) { var specifiedName = sourceModule.MetadataName; _metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ? specifiedName : emitOptions.OutputNameOverride ?? specifiedName; AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this); if (sourceModule.AnyReferencedAssembliesAreLinked) { _embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this); } } public override string Name { get { return _metadataName; } } internal sealed override string ModuleName { get { return _metadataName; } } internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor) { return Compilation.TrySynthesizeAttribute(attributeConstructor); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly) { return SourceModule.ContainingSourceAssembly .GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule()); } public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes() { return SourceModule.ContainingSourceAssembly.GetSecurityAttributes(); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes() { return SourceModule.GetCustomAttributesToEmit(this); } internal sealed override AssemblySymbol CorLibrary { get { return SourceModule.ContainingSourceAssembly.CorLibrary; } } public sealed override bool GenerateVisualBasicStylePdb => false; // C# doesn't emit linked assembly names into PDBs. public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>(); // C# currently doesn't emit compilation level imports (TODO: scripting). public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty; // C# doesn't allow to define default namespace for compilation. public sealed override string DefaultNamespace => null; protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules; for (int i = 1; i < modules.Length; i++) { foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols()) { yield return Translate(aRef, diagnostics); } } } private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics) { AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity; AssemblyIdentity refIdentity = asmRef.Identity; if (asmIdentity.IsStrongName && !refIdentity.IsStrongName && asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime) { // Dev12 reported error, we have changed it to a warning to allow referencing libraries // built for platforms that don't support strong names. diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton); } if (OutputKind != OutputKind.NetModule && !string.IsNullOrEmpty(refIdentity.CultureName) && !string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton); } var refMachine = assembly.Machine; // If other assembly is agnostic this is always safe // Also, if no mscorlib was specified for back compat we add a reference to mscorlib // that resolves to the current framework directory. If the compiler is 64-bit // this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is // specified. A reference to the default mscorlib should always succeed without // warning so we ignore it here. if ((object)assembly != (object)assembly.CorLibrary && !(refMachine == Machine.I386 && !assembly.Bit32Required)) { var machine = SourceModule.Machine; if (!(machine == Machine.I386 && !SourceModule.Bit32Required) && machine != refMachine) { // Different machine types, and neither is agnostic diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton); } } if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen) { _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics); } } internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container) { return null; } public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap() { var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>(); var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>(); namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace); Location location = null; while (namespacesAndTypesToProcess.Count > 0) { NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop(); switch (symbol.Kind) { case SymbolKind.Namespace: location = GetSmallestSourceLocationOrNull(symbol); // filtering out synthesized symbols not having real source // locations such as anonymous types, etc... if (location != null) { foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; case SymbolKind.NamedType: location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { // add this named type location AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; case SymbolKind.Method: // NOTE: Dev11 does not add synthesized static constructors to this map, // but adds synthesized instance constructors, Roslyn adds both var method = (MethodSymbol)member; if (!method.ShouldEmit()) { break; } AddSymbolLocation(result, member); break; case SymbolKind.Property: AddSymbolLocation(result, member); break; case SymbolKind.Field: if (member is TupleErrorFieldSymbol) { break; } // NOTE: Dev11 does not add synthesized backing fields for properties, // but adds backing fields for events, Roslyn adds both AddSymbolLocation(result, member); break; case SymbolKind.Event: AddSymbolLocation(result, member); // event backing fields do not show up in GetMembers { FieldSymbol field = ((EventSymbol)member).AssociatedField; if ((object)field != null) { AddSymbolLocation(result, field); } } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } return result; } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol) { var location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); } } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition) { FileLinePositionSpan span = location.GetLineSpan(); Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath); if (doc != null) { result.Add(doc, new Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)); } } private Location GetSmallestSourceLocationOrNull(Symbol symbol) { CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?"); Location result = null; foreach (var loc in symbol.Locations) { if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0)) { result = loc; } } return result; } /// <summary> /// Ignore accessibility when resolving well-known type /// members, in particular for generic type arguments /// (e.g.: binding to internal types in the EE). /// </summary> internal virtual bool IgnoreAccessibility => false; /// <summary> /// Override the dynamic operation context type for all dynamic calls in the module. /// </summary> internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType) { return contextType; } internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return null; } internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray<AnonymousTypeKey>.Empty; } internal virtual ImmutableArray<SynthesizedDelegateKey> GetPreviousSynthesizedDelegates() { return ImmutableArray<SynthesizedDelegateKey>.Empty; } internal virtual int GetNextAnonymousTypeIndex() { return 0; } internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index) { Debug.Assert(Compilation == template.DeclaringCompilation); name = null; index = -1; return false; } public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context) { if (context.MetadataOnly) { return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>(); } return Compilation.AnonymousTypeManager.GetAllCreatedTemplates() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { var namespacesToProcess = new Stack<NamespaceSymbol>(); namespacesToProcess.Push(SourceModule.GlobalNamespace); while (namespacesToProcess.Count > 0) { var ns = namespacesToProcess.Pop(); foreach (var member in ns.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { namespacesToProcess.Push((NamespaceSymbol)member); } else { yield return ((NamedTypeSymbol)member).GetCciAdapter(); } } } } private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder) { int index; if (symbol.Kind == SymbolKind.NamedType) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return; } Debug.Assert(symbol.IsDefinition); index = builder.Count; builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false)); } else { index = -1; } foreach (var member in symbol.GetMembers()) { var namespaceOrType = member as NamespaceOrTypeSymbol; if ((object)namespaceOrType != null) { GetExportedTypes(namespaceOrType, index, builder); } } } public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics) { Debug.Assert(HaveDeterminedTopLevelTypes); if (_lazyExportedTypes.IsDefault) { _lazyExportedTypes = CalculateExportedTypes(); if (_lazyExportedTypes.Length > 0) { ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics); } } return _lazyExportedTypes; } /// <summary> /// Builds an array of public type symbols defined in netmodules included in the compilation /// and type forwarders defined in this compilation or any included netmodule (in this order). /// </summary> private ImmutableArray<Cci.ExportedType> CalculateExportedTypes() { SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly; var builder = ArrayBuilder<Cci.ExportedType>.GetInstance(); if (!OutputKind.IsNetModule()) { var modules = sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0] { GetExportedTypes(modules[i].GlobalNamespace, -1, builder); } } Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()); GetForwardedTypes(sourceAssembly, builder); return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Returns a set of top-level forwarded types /// </summary> internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder) { var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>(); GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder); if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) { GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder); } return seenTopLevelForwardedTypes; } #nullable disable private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics) { var sourceAssembly = SourceModule.ContainingSourceAssembly; var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (var exportedType in exportedTypes) { var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol(); Debug.Assert(type.IsDefinition); if (!type.IsTopLevelType()) { continue; } // exported types are not emitted in EnC deltas (hence generation 0): string fullEmittedName = MetadataHelpers.BuildQualifiedName( ((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName, Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0)); // First check against types declared in the primary module if (ContainsTopLevelType(fullEmittedName)) { if ((object)type.ContainingAssembly == sourceAssembly) { diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule); } else { diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type); } continue; } NamedTypeSymbol contender; // Now check against other exported types if (exportedNamesMap.TryGetValue(fullEmittedName, out contender)) { if ((object)type.ContainingAssembly == sourceAssembly) { // all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly == sourceAssembly); diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule); } else if ((object)contender.ContainingAssembly == sourceAssembly) { // Forwarded type conflicts with exported type diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule); } else { // Forwarded type conflicts with another forwarded type diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly); } continue; } exportedNamesMap.Add(fullEmittedName, type); } } #nullable enable private static void GetForwardedTypes( HashSet<NamedTypeSymbol> seenTopLevelTypes, CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData, ArrayBuilder<Cci.ExportedType>? builder) { if (wellKnownAttributeData?.ForwardedTypes?.Count > 0) { // (type, index of the parent exported type in builder, or -1 if the type is a top-level type) var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance(); // Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes; if (builder is object) { orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); } foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions before emitting. if (!seenTopLevelTypes.Add(originalDefinition)) continue; if (builder is object) { // Return all nested types. // Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count == 0); stack.Push((originalDefinition, -1)); while (stack.Count > 0) { var (type, parentIndex) = stack.Pop(); // In general, we don't want private types to appear in the ExportedTypes table. // BREAK: dev11 emits these types. The problem was discovered in dev10, but failed // to meet the bar Bug: Dev10/258038 and was left as-is. if (type.DeclaredAccessibility == Accessibility.Private) { // NOTE: this will also exclude nested types of type continue; } // NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. int index = builder.Count; builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true)); // Iterate backwards so they get popped in forward order. ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered. for (int i = nested.Length - 1; i >= 0; i--) { stack.Push((nested[i], index)); } } } } stack.Free(); } } #nullable disable internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar() { foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols()) { if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a)) { yield return a; } } } private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType); DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo; if (info != null) { Symbol.ReportUseSiteDiagnostic(info, diagnostics, syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton); } return typeSymbol; } internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), diagnostics: diagnostics, syntaxNodeOpt: syntaxNodeOpt, needDeclaration: true); } public sealed override Cci.IMethodReference GetInitArrayHelper() { return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter(); } public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType) { var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol; if ((object)namedType != null) { if (platformType == Cci.PlatformType.SystemType) { return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type); } return namedType.SpecialType == (SpecialType)platformType; } return false; } protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context) { AssemblySymbol corLibrary = CorLibrary; if (!corLibrary.IsMissing && !corLibrary.IsLinked && !ReferenceEquals(corLibrary, SourceModule.ContainingAssembly)) { return Translate(corLibrary, context.Diagnostics); } return null; } internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule.ContainingAssembly, assembly)) { return (Cci.IAssemblyReference)this; } Cci.IModuleReference reference; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference)) { return (Cci.IAssemblyReference)reference; } AssemblyReference asmRef = new AssemblyReference(assembly); AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef); if (cachedAsmRef == asmRef) { ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics); } // TryAdd because whatever is associated with assembly should be associated with Modules[0] AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef); return cachedAsmRef; } internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule, module)) { return this; } if ((object)module == null) { return null; } Cci.IModuleReference moduleRef; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef)) { return moduleRef; } moduleRef = TranslateModule(module, diagnostics); moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef); return moduleRef; } protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics) { AssemblySymbol container = module.ContainingAssembly; if ((object)container != null && ReferenceEquals(container.Modules[0], module)) { Cci.IModuleReference moduleRef = new AssemblyReference(container); Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef); if (cachedModuleRef == moduleRef) { ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics); } else { moduleRef = cachedModuleRef; } return moduleRef; } else { return new ModuleReference(this, module); } } internal Cci.INamedTypeReference Translate( NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool fromImplements = false, bool needDeclaration = false) { Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct()); Debug.Assert(diagnostics != null); // Anonymous type being translated if (namedTypeSymbol.IsAnonymousType) { Debug.Assert(!needDeclaration); namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol); } else if (namedTypeSymbol.IsTupleType) { CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics); } // Substitute error types with a special singleton object. // Unreported bad types can come through NoPia embedding, for example. if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType) { ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition; DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType) { errorType = (ErrorTypeSymbol)namedTypeSymbol; diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; } // Try to decrease noise by not complaining about the same type over and over again. if (_reportedErrorTypesMap.Add(errorType)) { diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location)); } return CodeAnalysis.Emit.ErrorType.Singleton; } if (!namedTypeSymbol.IsDefinition) { // generic instantiation for sure Debug.Assert(!needDeclaration); if (namedTypeSymbol.IsUnboundGenericType) { namedTypeSymbol = namedTypeSymbol.OriginalDefinition; } else { return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol); } } else if (!needDeclaration) { object reference; Cci.INamedTypeReference typeRef; NamedTypeSymbol container = namedTypeSymbol.ContainingType; if (namedTypeSymbol.Arity > 0) { if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } if ((object)container != null) { if (IsGenericType(container)) { // Container is a generic instance too. typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol); } else { typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol); } } else { typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol); } typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (IsGenericType(container)) { Debug.Assert((object)container != null); if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } typeRef = new SpecializedNestedTypeReference(namedTypeSymbol); typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType) { namedTypeSymbol = underlyingType; } } // NoPia: See if this is a type, which definition we should copy into our assembly. Debug.Assert(namedTypeSymbol.IsDefinition); return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter(); } private object GetCciAdapter(Symbol symbol) { return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter()); } private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // check that underlying type of a ValueTuple is indeed a value type (or error) // this should never happen, in theory, // but if it does happen we should make it a failure. // NOTE: declaredBase could be null for interfaces var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType) { return; } // Try to decrease noise by not complaining about the same type over and over again. if (!_reportedErrorTypesMap.Add(namedTypeSymbol)) { return; } var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location; if ((object)declaredBase != null) { var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo; if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(diagnosticInfo, location); return; } } diagnostics.Add( new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName), location)); } public static bool IsGenericType(NamedTypeSymbol toCheck) { while ((object)toCheck != null) { if (toCheck.Arity > 0) { return true; } toCheck = toCheck.ContainingType; } return false; } internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param) { if (!param.IsDefinition) throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name)); return param.GetCciAdapter(); } internal sealed override Cci.ITypeReference Translate( TypeSymbol typeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); switch (typeSymbol.Kind) { case SymbolKind.DynamicType: return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.ArrayType: return Translate((ArrayTypeSymbol)typeSymbol); case SymbolKind.ErrorType: case SymbolKind.NamedType: return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.PointerType: return Translate((PointerTypeSymbol)typeSymbol); case SymbolKind.TypeParameter: return Translate((TypeParameterSymbol)typeSymbol); case SymbolKind.FunctionPointerType: return Translate((FunctionPointerTypeSymbol)typeSymbol); } throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind); } internal Cci.IFieldReference Translate( FieldSymbol fieldSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration = false) { Debug.Assert(fieldSymbol.IsDefinitionOrDistinct()); Debug.Assert(!fieldSymbol.IsVirtualTupleField && (object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol && fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now"); if (!fieldSymbol.IsDefinition) { Debug.Assert(!needDeclaration); return (Cci.IFieldReference)GetCciAdapter(fieldSymbol); } else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType)) { object reference; Cci.IFieldReference fieldRef; if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference)) { return (Cci.IFieldReference)reference; } fieldRef = new SpecializedFieldReference(fieldSymbol); fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef); return fieldRef; } return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter(); } public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol) { // // We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies. // // Top-level: // private -> public // protected -> public (compiles with a warning) // public // internal -> public // // In a nested class: // // private // protected // public // internal -> public // switch (symbol.DeclaredAccessibility) { case Accessibility.Public: return Cci.TypeMemberVisibility.Public; case Accessibility.Private: if (symbol.ContainingType?.TypeKind == TypeKind.Submission) { // top-level private member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Private; } case Accessibility.Internal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Assembly; } case Accessibility.Protected: if (symbol.ContainingType.TypeKind == TypeKind.Submission) { // top-level protected member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Family; } case Accessibility.ProtectedAndInternal: Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission); return Cci.TypeMemberVisibility.FamilyAndAssembly; case Accessibility.ProtectedOrInternal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested protected internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.FamilyOrAssembly; } default: throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility); } } internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate(symbol, null, diagnostics, null, needDeclaration); } internal Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, BoundArgListOperator optArgList = null, bool needDeclaration = false) { Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true)); Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration)); Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration); if (optArgList != null && optArgList.Arguments.Length > 0) { Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length]; int ordinal = methodSymbol.ParameterCount; for (int i = 0; i < @params.Length; i++) { @params[i] = new ArgListParameterTypeInformation(ordinal, !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None, Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics)); ordinal++; } return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull()); } else { return unexpandedMethodRef; } } private Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration) { object reference; Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; // Method of anonymous type being translated if (container.IsAnonymousType) { Debug.Assert(!needDeclaration); methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol); } Debug.Assert(methodSymbol.IsDefinitionOrDistinct()); if (!methodSymbol.IsDefinition) { Debug.Assert(!needDeclaration); Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol)); Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol)); return (Cci.IMethodReference)GetCciAdapter(methodSymbol); } else if (!needDeclaration) { bool methodIsGeneric = methodSymbol.IsGenericMethod; bool typeIsGeneric = IsGenericType(container); if (methodIsGeneric || typeIsGeneric) { if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { return (Cci.IMethodReference)reference; } if (methodIsGeneric) { if (typeIsGeneric) { // Specialized and generic instance at the same time. methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol); } else { methodRef = new GenericMethodInstanceReference(methodSymbol); } } else { Debug.Assert(typeIsGeneric); methodRef = new SpecializedMethodReference(methodSymbol); } methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); return methodRef; } else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod }) { methodSymbol = underlyingMethod; } } if (_embeddedTypesManagerOpt != null) { return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } return methodSymbol.GetCciAdapter(); } internal Cci.IMethodReference TranslateOverriddenMethodReference( MethodSymbol methodSymbol, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; if (IsGenericType(container)) { if (methodSymbol.IsDefinition) { object reference; if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { methodRef = (Cci.IMethodReference)reference; } else { methodRef = new SpecializedMethodReference(methodSymbol); methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); } } else { methodRef = new SpecializedMethodReference(methodSymbol); } } else { Debug.Assert(methodSymbol.IsDefinition); if (_embeddedTypesManagerOpt != null) { methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } else { methodRef = methodSymbol.GetCciAdapter(); } } return methodRef; } internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params) { Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct())); bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First()); Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating"); if (!mustBeTranslated) { #if DEBUG return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter()); #else return StaticCast<Cci.IParameterTypeInformation>.From(@params); #endif } return TranslateAll(@params); } private static bool MustBeWrapped(ParameterSymbol param) { // we represent parameters of generic methods as definitions // CCI wants them represented as IParameterTypeInformation // so we need to create a wrapper of parameters iff // 1) parameters are definitions and // 2) container is generic // NOTE: all parameters must always agree on whether they need wrapping if (param.IsDefinition) { var container = param.ContainingSymbol; if (ContainerIsGeneric(container)) { return true; } } return false; } private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params) { var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance(); foreach (var param in @params) { builder.Add(CreateParameterTypeInformationWrapper(param)); } return builder.ToImmutableAndFree(); } private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param) { object reference; Cci.IParameterTypeInformation paramRef; if (_genericInstanceMap.TryGetValue(param, out reference)) { return (Cci.IParameterTypeInformation)reference; } paramRef = new ParameterTypeInformation(param); paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef); return paramRef; } private static bool ContainerIsGeneric(Symbol container) { return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod || IsGenericType(container.ContainingType); } internal Cci.ITypeReference Translate( DynamicTypeSymbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table. // We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter // masquerades the TypeRef as System.Object when used to encode signatures. return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics); } internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol) { return (Cci.IArrayTypeReference)GetCciAdapter(symbol); } internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol) { return (Cci.IPointerTypeReference)GetCciAdapter(symbol); } internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol) { return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol); } /// <summary> /// Set the underlying implementation type for a given fixed-size buffer field. /// </summary> public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field) { if (_fixedImplementationTypes == null) { Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null); } lock (_fixedImplementationTypes) { NamedTypeSymbol result; if (_fixedImplementationTypes.TryGetValue(field, out result)) { return result; } result = new FixedFieldImplementationType(field); _fixedImplementationTypes.Add(field, result); AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter()); return result; } } internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field) { // Note that this method is called only after ALL fixed buffer types have been placed in the map. // At that point the map is all filled in and will not change further. Therefore it is safe to // pull values from the map without locking. NamedTypeSymbol result; var found = _fixedImplementationTypes.TryGetValue(field, out result); Debug.Assert(found); return result; } protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics) { return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter(); } internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute(); internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsReadOnlyAttribute(); } internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsUnmanagedAttribute(); } internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsByRefLikeAttribute(); } /// <summary> /// Given a type <paramref name="type"/>, which is either a nullable reference type OR /// is a constructed type with a nullable reference type present in its type argument tree, /// returns a synthesized NullableAttribute with encoded nullable transforms array. /// </summary> internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var flagsBuilder = ArrayBuilder<byte>.GetInstance(); type.AddNullableTransforms(flagsBuilder); SynthesizedAttributeData attribute; if (!flagsBuilder.Any()) { attribute = null; } else { Debug.Assert(flagsBuilder.All(f => f <= 2)); byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder); if (commonValue != null) { attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault()); } else { NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType)); var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType); attribute = SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, ImmutableArray.Create(new TypedConstant(byteArrayType, value))); } } flagsBuilder.Free(); return attribute; } internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue) { if (nullableValue == nullableContextValue || (nullableContextValue == null && nullableValue == 0)) { return null; } NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); return SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue))); } internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value) { var module = Compilation.SourceModule; if ((object)module != symbol && (object)module != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return SynthesizeNullableContextAttribute( ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value))); } internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute() { return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.ContainsNativeInteger()); if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type); Debug.Assert(builder.Any()); Debug.Assert(builder.Contains(true)); SynthesizedAttributeData attribute; if (builder.Count == 1 && builder[0]) { attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty); } else { NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert((object)booleanType != null); var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments); } builder.Free(); return attribute; } internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal bool ShouldEmitNullablePublicOnlyAttribute() { // No need to look at this.GetNeedsGeneratedAttributes() since those bits are // only set for members generated by the rewriter which are not public. return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly; } internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments); } protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0) { return; } // Don't report any errors. They should be reported during binding. if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null)) { SetNeedsGeneratedAttributes(attribute); } } internal void EnsureIsReadOnlyAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute); } internal void EnsureIsUnmanagedAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute); } internal void EnsureNullableAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute); } internal void EnsureNullableContextAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute); } internal void EnsureNativeIntegerAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute); } public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context) { return GetAdditionalTopLevelTypes() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context) { return GetEmbeddedTypes(context.Diagnostics) #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) { return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics)); } internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { return base.GetEmbeddedTypes(diagnostics.DiagnosticBag); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal abstract class PEModuleBuilder : PEModuleBuilder<CSharpCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState> { // TODO: Need to estimate amount of elements for this map and pass that value to the constructor. protected readonly ConcurrentDictionary<Symbol, Cci.IModuleReference> AssemblyOrModuleSymbolToModuleRefMap = new ConcurrentDictionary<Symbol, Cci.IModuleReference>(); private readonly ConcurrentDictionary<Symbol, object> _genericInstanceMap = new ConcurrentDictionary<Symbol, object>(Symbols.SymbolEqualityComparer.ConsiderEverything); private readonly ConcurrentSet<TypeSymbol> _reportedErrorTypesMap = new ConcurrentSet<TypeSymbol>(); private readonly NoPia.EmbeddedTypesManager _embeddedTypesManagerOpt; public override NoPia.EmbeddedTypesManager EmbeddedTypesManagerOpt => _embeddedTypesManagerOpt; // Gives the name of this module (may not reflect the name of the underlying symbol). // See Assembly.MetadataName. private readonly string _metadataName; private ImmutableArray<Cci.ExportedType> _lazyExportedTypes; /// <summary> /// The compiler-generated implementation type for each fixed-size buffer. /// </summary> private Dictionary<FieldSymbol, NamedTypeSymbol> _fixedImplementationTypes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return GetNeedsGeneratedAttributesInternal(); } private EmbeddableAttributes GetNeedsGeneratedAttributesInternal() { return (EmbeddableAttributes)_needsGeneratedAttributes | Compilation.GetNeedsGeneratedAttributes(); } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal PEModuleBuilder( SourceModuleSymbol sourceModule, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources) : base(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, new ModuleCompilationState()) { var specifiedName = sourceModule.MetadataName; _metadataName = specifiedName != Microsoft.CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName ? specifiedName : emitOptions.OutputNameOverride ?? specifiedName; AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, this); if (sourceModule.AnyReferencedAssembliesAreLinked) { _embeddedTypesManagerOpt = new NoPia.EmbeddedTypesManager(this); } } public override string Name { get { return _metadataName; } } internal sealed override string ModuleName { get { return _metadataName; } } internal sealed override Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor) { return Compilation.TrySynthesizeAttribute(attributeConstructor); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly) { return SourceModule.ContainingSourceAssembly .GetCustomAttributesToEmit(this, isRefAssembly, emittingAssemblyAttributesInNetModule: OutputKind.IsNetModule()); } public sealed override IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes() { return SourceModule.ContainingSourceAssembly.GetSecurityAttributes(); } public sealed override IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes() { return SourceModule.GetCustomAttributesToEmit(this); } internal sealed override AssemblySymbol CorLibrary { get { return SourceModule.ContainingSourceAssembly.CorLibrary; } } public sealed override bool GenerateVisualBasicStylePdb => false; // C# doesn't emit linked assembly names into PDBs. public sealed override IEnumerable<string> LinkedAssembliesDebugInfo => SpecializedCollections.EmptyEnumerable<string>(); // C# currently doesn't emit compilation level imports (TODO: scripting). public sealed override ImmutableArray<Cci.UsedNamespaceOrType> GetImports() => ImmutableArray<Cci.UsedNamespaceOrType>.Empty; // C# doesn't allow to define default namespace for compilation. public sealed override string DefaultNamespace => null; protected sealed override IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceModule.ContainingAssembly.Modules; for (int i = 1; i < modules.Length; i++) { foreach (AssemblySymbol aRef in modules[i].GetReferencedAssemblySymbols()) { yield return Translate(aRef, diagnostics); } } } private void ValidateReferencedAssembly(AssemblySymbol assembly, AssemblyReference asmRef, DiagnosticBag diagnostics) { AssemblyIdentity asmIdentity = SourceModule.ContainingAssembly.Identity; AssemblyIdentity refIdentity = asmRef.Identity; if (asmIdentity.IsStrongName && !refIdentity.IsStrongName && asmRef.Identity.ContentType != AssemblyContentType.WindowsRuntime) { // Dev12 reported error, we have changed it to a warning to allow referencing libraries // built for platforms that don't support strong names. diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton); } if (OutputKind != OutputKind.NetModule && !string.IsNullOrEmpty(refIdentity.CultureName) && !string.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase)) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton); } var refMachine = assembly.Machine; // If other assembly is agnostic this is always safe // Also, if no mscorlib was specified for back compat we add a reference to mscorlib // that resolves to the current framework directory. If the compiler is 64-bit // this is a 64-bit mscorlib, which will produce a warning if /platform:x86 is // specified. A reference to the default mscorlib should always succeed without // warning so we ignore it here. if ((object)assembly != (object)assembly.CorLibrary && !(refMachine == Machine.I386 && !assembly.Bit32Required)) { var machine = SourceModule.Machine; if (!(machine == Machine.I386 && !SourceModule.Bit32Required) && machine != refMachine) { // Different machine types, and neither is agnostic diagnostics.Add(new CSDiagnosticInfo(ErrorCode.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton); } } if (_embeddedTypesManagerOpt != null && _embeddedTypesManagerOpt.IsFrozen) { _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics); } } internal sealed override IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(NamedTypeSymbol container) { return null; } public sealed override IEnumerable<(Cci.ITypeDefinition, ImmutableArray<Cci.DebugSourceDocument>)> GetTypeToDebugDocumentMap(EmitContext context) { var typesToProcess = ArrayBuilder<Cci.ITypeDefinition>.GetInstance(); var debugDocuments = ArrayBuilder<Cci.DebugSourceDocument>.GetInstance(); var methodDocumentList = PooledHashSet<Cci.DebugSourceDocument>.GetInstance(); var namespacesAndTopLevelTypesToProcess = ArrayBuilder<NamespaceOrTypeSymbol>.GetInstance(); namespacesAndTopLevelTypesToProcess.Push(SourceModule.GlobalNamespace); while (namespacesAndTopLevelTypesToProcess.Count > 0) { var symbol = namespacesAndTopLevelTypesToProcess.Pop(); switch (symbol.Kind) { case SymbolKind.Namespace: var location = GetSmallestSourceLocationOrNull(symbol); // filtering out synthesized symbols not having real source // locations such as anonymous types, etc... if (location != null) { foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: namespacesAndTopLevelTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; case SymbolKind.NamedType: Debug.Assert(debugDocuments.Count == 0); Debug.Assert(methodDocumentList.Count == 0); Debug.Assert(typesToProcess.Count == 0); var typeDefinition = (Cci.ITypeDefinition)symbol.GetCciAdapter(); typesToProcess.Push(typeDefinition); GetDocumentsForMethodsAndNestedTypes(methodDocumentList, typesToProcess, context); foreach (var loc in symbol.Locations) { if (!loc.IsInSource) { continue; } var span = loc.GetLineSpan(); var debugDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: null); // If we have a debug document that is already referenced by method debug info in this type, or a nested type, // then we don't need to include it. Since its impossible to declare a nested type without also including // a declaration for its containing type, we don't need to consider nested types in this method itself. if (debugDocument is not null && !methodDocumentList.Contains(debugDocument)) { debugDocuments.Add(debugDocument); } } if (debugDocuments.Count > 0) { yield return (typeDefinition, debugDocuments.ToImmutable()); } debugDocuments.Clear(); methodDocumentList.Clear(); break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } namespacesAndTopLevelTypesToProcess.Free(); debugDocuments.Free(); methodDocumentList.Free(); typesToProcess.Free(); } /// <summary> /// Gets a list of documents from the method definitions in the types in <paramref name="typesToProcess"/> or any /// nested types of those types. /// </summary> private static void GetDocumentsForMethodsAndNestedTypes(PooledHashSet<Cci.DebugSourceDocument> documentList, ArrayBuilder<Cci.ITypeDefinition> typesToProcess, EmitContext context) { while (typesToProcess.Count > 0) { var definition = typesToProcess.Pop(); var typeMethods = definition.GetMethods(context); foreach (var method in typeMethods) { var body = method.GetBody(context); if (body is null) { continue; } foreach (var point in body.SequencePoints) { documentList.Add(point.Document); } } var nestedTypes = definition.GetNestedTypes(context); foreach (var nestedTypeDefinition in nestedTypes) { typesToProcess.Push(nestedTypeDefinition); } } } public sealed override MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap() { var result = new MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation>(); var namespacesAndTypesToProcess = new Stack<NamespaceOrTypeSymbol>(); namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace); Location location = null; while (namespacesAndTypesToProcess.Count > 0) { NamespaceOrTypeSymbol symbol = namespacesAndTypesToProcess.Pop(); switch (symbol.Kind) { case SymbolKind.Namespace: location = GetSmallestSourceLocationOrNull(symbol); // filtering out synthesized symbols not having real source // locations such as anonymous types, etc... if (location != null) { foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.Namespace: case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; case SymbolKind.NamedType: location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { // add this named type location AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); foreach (var member in symbol.GetMembers()) { switch (member.Kind) { case SymbolKind.NamedType: namespacesAndTypesToProcess.Push((NamespaceOrTypeSymbol)member); break; case SymbolKind.Method: // NOTE: Dev11 does not add synthesized static constructors to this map, // but adds synthesized instance constructors, Roslyn adds both var method = (MethodSymbol)member; if (!method.ShouldEmit()) { break; } AddSymbolLocation(result, member); break; case SymbolKind.Property: AddSymbolLocation(result, member); break; case SymbolKind.Field: if (member is TupleErrorFieldSymbol) { break; } // NOTE: Dev11 does not add synthesized backing fields for properties, // but adds backing fields for events, Roslyn adds both AddSymbolLocation(result, member); break; case SymbolKind.Event: AddSymbolLocation(result, member); // event backing fields do not show up in GetMembers { FieldSymbol field = ((EventSymbol)member).AssociatedField; if ((object)field != null) { AddSymbolLocation(result, field); } } break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } } break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } return result; } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Symbol symbol) { var location = GetSmallestSourceLocationOrNull(symbol); if (location != null) { AddSymbolLocation(result, location, (Cci.IDefinition)symbol.GetCciAdapter()); } } private void AddSymbolLocation(MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> result, Location location, Cci.IDefinition definition) { FileLinePositionSpan span = location.GetLineSpan(); Cci.DebugSourceDocument doc = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath: location.SourceTree.FilePath); if (doc != null) { result.Add(doc, new Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)); } } private Location GetSmallestSourceLocationOrNull(Symbol symbol) { CSharpCompilation compilation = symbol.DeclaringCompilation; Debug.Assert(Compilation == compilation, "How did we get symbol from different compilation?"); Location result = null; foreach (var loc in symbol.Locations) { if (loc.IsInSource && (result == null || compilation.CompareSourceLocations(result, loc) > 0)) { result = loc; } } return result; } /// <summary> /// Ignore accessibility when resolving well-known type /// members, in particular for generic type arguments /// (e.g.: binding to internal types in the EE). /// </summary> internal virtual bool IgnoreAccessibility => false; /// <summary> /// Override the dynamic operation context type for all dynamic calls in the module. /// </summary> internal virtual NamedTypeSymbol GetDynamicOperationContextType(NamedTypeSymbol contextType) { return contextType; } internal virtual VariableSlotAllocator TryCreateVariableSlotAllocator(MethodSymbol method, MethodSymbol topLevelMethod, DiagnosticBag diagnostics) { return null; } internal virtual ImmutableArray<AnonymousTypeKey> GetPreviousAnonymousTypes() { return ImmutableArray<AnonymousTypeKey>.Empty; } internal virtual ImmutableArray<SynthesizedDelegateKey> GetPreviousSynthesizedDelegates() { return ImmutableArray<SynthesizedDelegateKey>.Empty; } internal virtual int GetNextAnonymousTypeIndex() { return 0; } internal virtual bool TryGetAnonymousTypeName(AnonymousTypeManager.AnonymousTypeTemplateSymbol template, out string name, out int index) { Debug.Assert(Compilation == template.DeclaringCompilation); name = null; index = -1; return false; } public sealed override IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context) { if (context.MetadataOnly) { return SpecializedCollections.EmptyEnumerable<Cci.INamespaceTypeDefinition>(); } return Compilation.AnonymousTypeManager.GetAllCreatedTemplates() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context) { var namespacesToProcess = new Stack<NamespaceSymbol>(); namespacesToProcess.Push(SourceModule.GlobalNamespace); while (namespacesToProcess.Count > 0) { var ns = namespacesToProcess.Pop(); foreach (var member in ns.GetMembers()) { if (member.Kind == SymbolKind.Namespace) { namespacesToProcess.Push((NamespaceSymbol)member); } else { yield return ((NamedTypeSymbol)member).GetCciAdapter(); } } } } private static void GetExportedTypes(NamespaceOrTypeSymbol symbol, int parentIndex, ArrayBuilder<Cci.ExportedType> builder) { int index; if (symbol.Kind == SymbolKind.NamedType) { if (symbol.DeclaredAccessibility != Accessibility.Public) { return; } Debug.Assert(symbol.IsDefinition); index = builder.Count; builder.Add(new Cci.ExportedType((Cci.ITypeReference)symbol.GetCciAdapter(), parentIndex, isForwarder: false)); } else { index = -1; } foreach (var member in symbol.GetMembers()) { var namespaceOrType = member as NamespaceOrTypeSymbol; if ((object)namespaceOrType != null) { GetExportedTypes(namespaceOrType, index, builder); } } } public sealed override ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics) { Debug.Assert(HaveDeterminedTopLevelTypes); if (_lazyExportedTypes.IsDefault) { _lazyExportedTypes = CalculateExportedTypes(); if (_lazyExportedTypes.Length > 0) { ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics); } } return _lazyExportedTypes; } /// <summary> /// Builds an array of public type symbols defined in netmodules included in the compilation /// and type forwarders defined in this compilation or any included netmodule (in this order). /// </summary> private ImmutableArray<Cci.ExportedType> CalculateExportedTypes() { SourceAssemblySymbol sourceAssembly = SourceModule.ContainingSourceAssembly; var builder = ArrayBuilder<Cci.ExportedType>.GetInstance(); if (!OutputKind.IsNetModule()) { var modules = sourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) //NOTE: skipping modules[0] { GetExportedTypes(modules[i].GlobalNamespace, -1, builder); } } Debug.Assert(OutputKind.IsNetModule() == sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()); GetForwardedTypes(sourceAssembly, builder); return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Returns a set of top-level forwarded types /// </summary> internal static HashSet<NamedTypeSymbol> GetForwardedTypes(SourceAssemblySymbol sourceAssembly, ArrayBuilder<Cci.ExportedType>? builder) { var seenTopLevelForwardedTypes = new HashSet<NamedTypeSymbol>(); GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builder); if (!sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) { GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builder); } return seenTopLevelForwardedTypes; } #nullable disable private void ReportExportedTypeNameCollisions(ImmutableArray<Cci.ExportedType> exportedTypes, DiagnosticBag diagnostics) { var sourceAssembly = SourceModule.ContainingSourceAssembly; var exportedNamesMap = new Dictionary<string, NamedTypeSymbol>(StringOrdinalComparer.Instance); foreach (var exportedType in exportedTypes) { var type = (NamedTypeSymbol)exportedType.Type.GetInternalSymbol(); Debug.Assert(type.IsDefinition); if (!type.IsTopLevelType()) { continue; } // exported types are not emitted in EnC deltas (hence generation 0): string fullEmittedName = MetadataHelpers.BuildQualifiedName( ((Cci.INamespaceTypeReference)type.GetCciAdapter()).NamespaceName, Cci.MetadataWriter.GetMangledName(type.GetCciAdapter(), generation: 0)); // First check against types declared in the primary module if (ContainsTopLevelType(fullEmittedName)) { if ((object)type.ContainingAssembly == sourceAssembly) { diagnostics.Add(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule); } else { diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, type); } continue; } NamedTypeSymbol contender; // Now check against other exported types if (exportedNamesMap.TryGetValue(fullEmittedName, out contender)) { if ((object)type.ContainingAssembly == sourceAssembly) { // all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly == sourceAssembly); diagnostics.Add(ErrorCode.ERR_ExportedTypesConflict, NoLocation.Singleton, type, type.ContainingModule, contender, contender.ContainingModule); } else if ((object)contender.ContainingAssembly == sourceAssembly) { // Forwarded type conflicts with exported type diagnostics.Add(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingModule); } else { // Forwarded type conflicts with another forwarded type diagnostics.Add(ErrorCode.ERR_ForwardedTypesConflict, NoLocation.Singleton, type, type.ContainingAssembly, contender, contender.ContainingAssembly); } continue; } exportedNamesMap.Add(fullEmittedName, type); } } #nullable enable private static void GetForwardedTypes( HashSet<NamedTypeSymbol> seenTopLevelTypes, CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> wellKnownAttributeData, ArrayBuilder<Cci.ExportedType>? builder) { if (wellKnownAttributeData?.ForwardedTypes?.Count > 0) { // (type, index of the parent exported type in builder, or -1 if the type is a top-level type) var stack = ArrayBuilder<(NamedTypeSymbol type, int parentIndex)>.GetInstance(); // Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. IEnumerable<NamedTypeSymbol> orderedForwardedTypes = wellKnownAttributeData.ForwardedTypes; if (builder is object) { orderedForwardedTypes = orderedForwardedTypes.OrderBy(t => t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)); } foreach (NamedTypeSymbol forwardedType in orderedForwardedTypes) { NamedTypeSymbol originalDefinition = forwardedType.OriginalDefinition; Debug.Assert((object)originalDefinition.ContainingType == null, "How did a nested type get forwarded?"); // Since we need to allow multiple constructions of the same generic type at the source // level, we need to de-dup the original definitions before emitting. if (!seenTopLevelTypes.Add(originalDefinition)) continue; if (builder is object) { // Return all nested types. // Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count == 0); stack.Push((originalDefinition, -1)); while (stack.Count > 0) { var (type, parentIndex) = stack.Pop(); // In general, we don't want private types to appear in the ExportedTypes table. // BREAK: dev11 emits these types. The problem was discovered in dev10, but failed // to meet the bar Bug: Dev10/258038 and was left as-is. if (type.DeclaredAccessibility == Accessibility.Private) { // NOTE: this will also exclude nested types of type continue; } // NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. int index = builder.Count; builder.Add(new Cci.ExportedType(type.GetCciAdapter(), parentIndex, isForwarder: true)); // Iterate backwards so they get popped in forward order. ImmutableArray<NamedTypeSymbol> nested = type.GetTypeMembers(); // Ordered. for (int i = nested.Length - 1; i >= 0; i--) { stack.Push((nested[i], index)); } } } } stack.Free(); } } #nullable disable internal IEnumerable<AssemblySymbol> GetReferencedAssembliesUsedSoFar() { foreach (AssemblySymbol a in SourceModule.GetReferencedAssemblySymbols()) { if (!a.IsLinked && !a.IsMissing && AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(a)) { yield return a; } } } private NamedTypeSymbol GetUntranslatedSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); var typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType); DiagnosticInfo info = typeSymbol.GetUseSiteInfo().DiagnosticInfo; if (info != null) { Symbol.ReportUseSiteDiagnostic(info, diagnostics, syntaxNodeOpt != null ? syntaxNodeOpt.Location : NoLocation.Singleton); } return typeSymbol; } internal sealed override Cci.INamedTypeReference GetSpecialType(SpecialType specialType, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), diagnostics: diagnostics, syntaxNodeOpt: syntaxNodeOpt, needDeclaration: true); } public sealed override Cci.IMethodReference GetInitArrayHelper() { return ((MethodSymbol)Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle))?.GetCciAdapter(); } public sealed override bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType) { var namedType = typeRef.GetInternalSymbol() as NamedTypeSymbol; if ((object)namedType != null) { if (platformType == Cci.PlatformType.SystemType) { return (object)namedType == (object)Compilation.GetWellKnownType(WellKnownType.System_Type); } return namedType.SpecialType == (SpecialType)platformType; } return false; } protected sealed override Cci.IAssemblyReference GetCorLibraryReferenceToEmit(CodeAnalysis.Emit.EmitContext context) { AssemblySymbol corLibrary = CorLibrary; if (!corLibrary.IsMissing && !corLibrary.IsLinked && !ReferenceEquals(corLibrary, SourceModule.ContainingAssembly)) { return Translate(corLibrary, context.Diagnostics); } return null; } internal sealed override Cci.IAssemblyReference Translate(AssemblySymbol assembly, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule.ContainingAssembly, assembly)) { return (Cci.IAssemblyReference)this; } Cci.IModuleReference reference; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(assembly, out reference)) { return (Cci.IAssemblyReference)reference; } AssemblyReference asmRef = new AssemblyReference(assembly); AssemblyReference cachedAsmRef = (AssemblyReference)AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(assembly, asmRef); if (cachedAsmRef == asmRef) { ValidateReferencedAssembly(assembly, cachedAsmRef, diagnostics); } // TryAdd because whatever is associated with assembly should be associated with Modules[0] AssemblyOrModuleSymbolToModuleRefMap.TryAdd(assembly.Modules[0], cachedAsmRef); return cachedAsmRef; } internal Cci.IModuleReference Translate(ModuleSymbol module, DiagnosticBag diagnostics) { if (ReferenceEquals(SourceModule, module)) { return this; } if ((object)module == null) { return null; } Cci.IModuleReference moduleRef; if (AssemblyOrModuleSymbolToModuleRefMap.TryGetValue(module, out moduleRef)) { return moduleRef; } moduleRef = TranslateModule(module, diagnostics); moduleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(module, moduleRef); return moduleRef; } protected virtual Cci.IModuleReference TranslateModule(ModuleSymbol module, DiagnosticBag diagnostics) { AssemblySymbol container = module.ContainingAssembly; if ((object)container != null && ReferenceEquals(container.Modules[0], module)) { Cci.IModuleReference moduleRef = new AssemblyReference(container); Cci.IModuleReference cachedModuleRef = AssemblyOrModuleSymbolToModuleRefMap.GetOrAdd(container, moduleRef); if (cachedModuleRef == moduleRef) { ValidateReferencedAssembly(container, (AssemblyReference)moduleRef, diagnostics); } else { moduleRef = cachedModuleRef; } return moduleRef; } else { return new ModuleReference(this, module); } } internal Cci.INamedTypeReference Translate( NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool fromImplements = false, bool needDeclaration = false) { Debug.Assert(namedTypeSymbol.IsDefinitionOrDistinct()); Debug.Assert(diagnostics != null); // Anonymous type being translated if (namedTypeSymbol.IsAnonymousType) { Debug.Assert(!needDeclaration); namedTypeSymbol = AnonymousTypeManager.TranslateAnonymousTypeSymbol(namedTypeSymbol); } else if (namedTypeSymbol.IsTupleType) { CheckTupleUnderlyingType(namedTypeSymbol, syntaxNodeOpt, diagnostics); } // Substitute error types with a special singleton object. // Unreported bad types can come through NoPia embedding, for example. if (namedTypeSymbol.OriginalDefinition.Kind == SymbolKind.ErrorType) { ErrorTypeSymbol errorType = (ErrorTypeSymbol)namedTypeSymbol.OriginalDefinition; DiagnosticInfo diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; if (diagInfo == null && namedTypeSymbol.Kind == SymbolKind.ErrorType) { errorType = (ErrorTypeSymbol)namedTypeSymbol; diagInfo = errorType.GetUseSiteInfo().DiagnosticInfo ?? errorType.ErrorInfo; } // Try to decrease noise by not complaining about the same type over and over again. if (_reportedErrorTypesMap.Add(errorType)) { diagnostics.Add(new CSDiagnostic(diagInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty), syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location)); } return CodeAnalysis.Emit.ErrorType.Singleton; } if (!namedTypeSymbol.IsDefinition) { // generic instantiation for sure Debug.Assert(!needDeclaration); if (namedTypeSymbol.IsUnboundGenericType) { namedTypeSymbol = namedTypeSymbol.OriginalDefinition; } else { return (Cci.INamedTypeReference)GetCciAdapter(namedTypeSymbol); } } else if (!needDeclaration) { object reference; Cci.INamedTypeReference typeRef; NamedTypeSymbol container = namedTypeSymbol.ContainingType; if (namedTypeSymbol.Arity > 0) { if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } if ((object)container != null) { if (IsGenericType(container)) { // Container is a generic instance too. typeRef = new SpecializedGenericNestedTypeInstanceReference(namedTypeSymbol); } else { typeRef = new GenericNestedTypeInstanceReference(namedTypeSymbol); } } else { typeRef = new GenericNamespaceTypeInstanceReference(namedTypeSymbol); } typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (IsGenericType(container)) { Debug.Assert((object)container != null); if (_genericInstanceMap.TryGetValue(namedTypeSymbol, out reference)) { return (Cci.INamedTypeReference)reference; } typeRef = new SpecializedNestedTypeReference(namedTypeSymbol); typeRef = (Cci.INamedTypeReference)_genericInstanceMap.GetOrAdd(namedTypeSymbol, typeRef); return typeRef; } else if (namedTypeSymbol.NativeIntegerUnderlyingType is NamedTypeSymbol underlyingType) { namedTypeSymbol = underlyingType; } } // NoPia: See if this is a type, which definition we should copy into our assembly. Debug.Assert(namedTypeSymbol.IsDefinition); return _embeddedTypesManagerOpt?.EmbedTypeIfNeedTo(namedTypeSymbol, fromImplements, syntaxNodeOpt, diagnostics) ?? namedTypeSymbol.GetCciAdapter(); } private object GetCciAdapter(Symbol symbol) { return _genericInstanceMap.GetOrAdd(symbol, s => s.GetCciAdapter()); } private void CheckTupleUnderlyingType(NamedTypeSymbol namedTypeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // check that underlying type of a ValueTuple is indeed a value type (or error) // this should never happen, in theory, // but if it does happen we should make it a failure. // NOTE: declaredBase could be null for interfaces var declaredBase = namedTypeSymbol.BaseTypeNoUseSiteDiagnostics; if ((object)declaredBase != null && declaredBase.SpecialType == SpecialType.System_ValueType) { return; } // Try to decrease noise by not complaining about the same type over and over again. if (!_reportedErrorTypesMap.Add(namedTypeSymbol)) { return; } var location = syntaxNodeOpt == null ? NoLocation.Singleton : syntaxNodeOpt.Location; if ((object)declaredBase != null) { var diagnosticInfo = declaredBase.GetUseSiteInfo().DiagnosticInfo; if (diagnosticInfo != null && diagnosticInfo.Severity == DiagnosticSeverity.Error) { diagnostics.Add(diagnosticInfo, location); return; } } diagnostics.Add( new CSDiagnostic( new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeMustBeStruct, namedTypeSymbol.MetadataName), location)); } public static bool IsGenericType(NamedTypeSymbol toCheck) { while ((object)toCheck != null) { if (toCheck.Arity > 0) { return true; } toCheck = toCheck.ContainingType; } return false; } internal static Cci.IGenericParameterReference Translate(TypeParameterSymbol param) { if (!param.IsDefinition) throw new InvalidOperationException(string.Format(CSharpResources.GenericParameterDefinition, param.Name)); return param.GetCciAdapter(); } internal sealed override Cci.ITypeReference Translate( TypeSymbol typeSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); switch (typeSymbol.Kind) { case SymbolKind.DynamicType: return Translate((DynamicTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.ArrayType: return Translate((ArrayTypeSymbol)typeSymbol); case SymbolKind.ErrorType: case SymbolKind.NamedType: return Translate((NamedTypeSymbol)typeSymbol, syntaxNodeOpt, diagnostics); case SymbolKind.PointerType: return Translate((PointerTypeSymbol)typeSymbol); case SymbolKind.TypeParameter: return Translate((TypeParameterSymbol)typeSymbol); case SymbolKind.FunctionPointerType: return Translate((FunctionPointerTypeSymbol)typeSymbol); } throw ExceptionUtilities.UnexpectedValue(typeSymbol.Kind); } internal Cci.IFieldReference Translate( FieldSymbol fieldSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration = false) { Debug.Assert(fieldSymbol.IsDefinitionOrDistinct()); Debug.Assert(!fieldSymbol.IsVirtualTupleField && (object)(fieldSymbol.TupleUnderlyingField ?? fieldSymbol) == fieldSymbol && fieldSymbol is not TupleErrorFieldSymbol, "tuple fields should be rewritten to underlying by now"); if (!fieldSymbol.IsDefinition) { Debug.Assert(!needDeclaration); return (Cci.IFieldReference)GetCciAdapter(fieldSymbol); } else if (!needDeclaration && IsGenericType(fieldSymbol.ContainingType)) { object reference; Cci.IFieldReference fieldRef; if (_genericInstanceMap.TryGetValue(fieldSymbol, out reference)) { return (Cci.IFieldReference)reference; } fieldRef = new SpecializedFieldReference(fieldSymbol); fieldRef = (Cci.IFieldReference)_genericInstanceMap.GetOrAdd(fieldSymbol, fieldRef); return fieldRef; } return _embeddedTypesManagerOpt?.EmbedFieldIfNeedTo(fieldSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics) ?? fieldSymbol.GetCciAdapter(); } public static Cci.TypeMemberVisibility MemberVisibility(Symbol symbol) { // // We need to relax visibility of members in interactive submissions since they might be emitted into multiple assemblies. // // Top-level: // private -> public // protected -> public (compiles with a warning) // public // internal -> public // // In a nested class: // // private // protected // public // internal -> public // switch (symbol.DeclaredAccessibility) { case Accessibility.Public: return Cci.TypeMemberVisibility.Public; case Accessibility.Private: if (symbol.ContainingType?.TypeKind == TypeKind.Submission) { // top-level private member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Private; } case Accessibility.Internal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Assembly; } case Accessibility.Protected: if (symbol.ContainingType.TypeKind == TypeKind.Submission) { // top-level protected member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.Family; } case Accessibility.ProtectedAndInternal: Debug.Assert(symbol.ContainingType.TypeKind != TypeKind.Submission); return Cci.TypeMemberVisibility.FamilyAndAssembly; case Accessibility.ProtectedOrInternal: if (symbol.ContainingAssembly.IsInteractive) { // top-level or nested protected internal member: return Cci.TypeMemberVisibility.Public; } else { return Cci.TypeMemberVisibility.FamilyOrAssembly; } default: throw ExceptionUtilities.UnexpectedValue(symbol.DeclaredAccessibility); } } internal sealed override Cci.IMethodReference Translate(MethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate(symbol, null, diagnostics, null, needDeclaration); } internal Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, BoundArgListOperator optArgList = null, bool needDeclaration = false) { Debug.Assert(!methodSymbol.IsDefaultValueTypeConstructor(requireZeroInit: true)); Debug.Assert(optArgList == null || (methodSymbol.IsVararg && !needDeclaration)); Cci.IMethodReference unexpandedMethodRef = Translate(methodSymbol, syntaxNodeOpt, diagnostics, needDeclaration); if (optArgList != null && optArgList.Arguments.Length > 0) { Cci.IParameterTypeInformation[] @params = new Cci.IParameterTypeInformation[optArgList.Arguments.Length]; int ordinal = methodSymbol.ParameterCount; for (int i = 0; i < @params.Length; i++) { @params[i] = new ArgListParameterTypeInformation(ordinal, !optArgList.ArgumentRefKindsOpt.IsDefaultOrEmpty && optArgList.ArgumentRefKindsOpt[i] != RefKind.None, Translate(optArgList.Arguments[i].Type, syntaxNodeOpt, diagnostics)); ordinal++; } return new ExpandedVarargsMethodReference(unexpandedMethodRef, @params.AsImmutableOrNull()); } else { return unexpandedMethodRef; } } private Cci.IMethodReference Translate( MethodSymbol methodSymbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics, bool needDeclaration) { object reference; Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; // Method of anonymous type being translated if (container.IsAnonymousType) { Debug.Assert(!needDeclaration); methodSymbol = AnonymousTypeManager.TranslateAnonymousTypeMethodSymbol(methodSymbol); } Debug.Assert(methodSymbol.IsDefinitionOrDistinct()); if (!methodSymbol.IsDefinition) { Debug.Assert(!needDeclaration); Debug.Assert(!(methodSymbol.OriginalDefinition is NativeIntegerMethodSymbol)); Debug.Assert(!(methodSymbol.ConstructedFrom is NativeIntegerMethodSymbol)); return (Cci.IMethodReference)GetCciAdapter(methodSymbol); } else if (!needDeclaration) { bool methodIsGeneric = methodSymbol.IsGenericMethod; bool typeIsGeneric = IsGenericType(container); if (methodIsGeneric || typeIsGeneric) { if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { return (Cci.IMethodReference)reference; } if (methodIsGeneric) { if (typeIsGeneric) { // Specialized and generic instance at the same time. methodRef = new SpecializedGenericMethodInstanceReference(methodSymbol); } else { methodRef = new GenericMethodInstanceReference(methodSymbol); } } else { Debug.Assert(typeIsGeneric); methodRef = new SpecializedMethodReference(methodSymbol); } methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); return methodRef; } else if (methodSymbol is NativeIntegerMethodSymbol { UnderlyingMethod: MethodSymbol underlyingMethod }) { methodSymbol = underlyingMethod; } } if (_embeddedTypesManagerOpt != null) { return _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } return methodSymbol.GetCciAdapter(); } internal Cci.IMethodReference TranslateOverriddenMethodReference( MethodSymbol methodSymbol, CSharpSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { Cci.IMethodReference methodRef; NamedTypeSymbol container = methodSymbol.ContainingType; if (IsGenericType(container)) { if (methodSymbol.IsDefinition) { object reference; if (_genericInstanceMap.TryGetValue(methodSymbol, out reference)) { methodRef = (Cci.IMethodReference)reference; } else { methodRef = new SpecializedMethodReference(methodSymbol); methodRef = (Cci.IMethodReference)_genericInstanceMap.GetOrAdd(methodSymbol, methodRef); } } else { methodRef = new SpecializedMethodReference(methodSymbol); } } else { Debug.Assert(methodSymbol.IsDefinition); if (_embeddedTypesManagerOpt != null) { methodRef = _embeddedTypesManagerOpt.EmbedMethodIfNeedTo(methodSymbol.GetCciAdapter(), syntaxNodeOpt, diagnostics); } else { methodRef = methodSymbol.GetCciAdapter(); } } return methodRef; } internal ImmutableArray<Cci.IParameterTypeInformation> Translate(ImmutableArray<ParameterSymbol> @params) { Debug.Assert(@params.All(p => p.IsDefinitionOrDistinct())); bool mustBeTranslated = @params.Any() && MustBeWrapped(@params.First()); Debug.Assert(@params.All(p => mustBeTranslated == MustBeWrapped(p)), "either all or no parameters need translating"); if (!mustBeTranslated) { #if DEBUG return @params.SelectAsArray<ParameterSymbol, Cci.IParameterTypeInformation>(p => p.GetCciAdapter()); #else return StaticCast<Cci.IParameterTypeInformation>.From(@params); #endif } return TranslateAll(@params); } private static bool MustBeWrapped(ParameterSymbol param) { // we represent parameters of generic methods as definitions // CCI wants them represented as IParameterTypeInformation // so we need to create a wrapper of parameters iff // 1) parameters are definitions and // 2) container is generic // NOTE: all parameters must always agree on whether they need wrapping if (param.IsDefinition) { var container = param.ContainingSymbol; if (ContainerIsGeneric(container)) { return true; } } return false; } private ImmutableArray<Cci.IParameterTypeInformation> TranslateAll(ImmutableArray<ParameterSymbol> @params) { var builder = ArrayBuilder<Cci.IParameterTypeInformation>.GetInstance(); foreach (var param in @params) { builder.Add(CreateParameterTypeInformationWrapper(param)); } return builder.ToImmutableAndFree(); } private Cci.IParameterTypeInformation CreateParameterTypeInformationWrapper(ParameterSymbol param) { object reference; Cci.IParameterTypeInformation paramRef; if (_genericInstanceMap.TryGetValue(param, out reference)) { return (Cci.IParameterTypeInformation)reference; } paramRef = new ParameterTypeInformation(param); paramRef = (Cci.IParameterTypeInformation)_genericInstanceMap.GetOrAdd(param, paramRef); return paramRef; } private static bool ContainerIsGeneric(Symbol container) { return container.Kind == SymbolKind.Method && ((MethodSymbol)container).IsGenericMethod || IsGenericType(container.ContainingType); } internal Cci.ITypeReference Translate( DynamicTypeSymbol symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { // Translate the dynamic type to System.Object special type to avoid duplicate entries in TypeRef table. // We don't need to recursively replace the dynamic type with Object since the DynamicTypeSymbol adapter // masquerades the TypeRef as System.Object when used to encode signatures. return GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics); } internal Cci.IArrayTypeReference Translate(ArrayTypeSymbol symbol) { return (Cci.IArrayTypeReference)GetCciAdapter(symbol); } internal Cci.IPointerTypeReference Translate(PointerTypeSymbol symbol) { return (Cci.IPointerTypeReference)GetCciAdapter(symbol); } internal Cci.IFunctionPointerTypeReference Translate(FunctionPointerTypeSymbol symbol) { return (Cci.IFunctionPointerTypeReference)GetCciAdapter(symbol); } /// <summary> /// Set the underlying implementation type for a given fixed-size buffer field. /// </summary> public NamedTypeSymbol SetFixedImplementationType(SourceMemberFieldSymbol field) { if (_fixedImplementationTypes == null) { Interlocked.CompareExchange(ref _fixedImplementationTypes, new Dictionary<FieldSymbol, NamedTypeSymbol>(), null); } lock (_fixedImplementationTypes) { NamedTypeSymbol result; if (_fixedImplementationTypes.TryGetValue(field, out result)) { return result; } result = new FixedFieldImplementationType(field); _fixedImplementationTypes.Add(field, result); AddSynthesizedDefinition(result.ContainingType, result.GetCciAdapter()); return result; } } internal NamedTypeSymbol GetFixedImplementationType(FieldSymbol field) { // Note that this method is called only after ALL fixed buffer types have been placed in the map. // At that point the map is all filled in and will not change further. Therefore it is safe to // pull values from the map without locking. NamedTypeSymbol result; var found = _fixedImplementationTypes.TryGetValue(field, out result); Debug.Assert(found); return result; } protected override Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, SyntaxNode syntaxOpt, DiagnosticBag diagnostics) { return new SynthesizedPrivateImplementationDetailsStaticConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter(); } internal abstract SynthesizedAttributeData SynthesizeEmbeddedAttribute(); internal SynthesizedAttributeData SynthesizeIsReadOnlyAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsReadOnlyAttribute(); } internal SynthesizedAttributeData SynthesizeIsUnmanagedAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsUnmanagedAttribute(); } internal SynthesizedAttributeData SynthesizeIsByRefLikeAttribute(Symbol symbol) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return TrySynthesizeIsByRefLikeAttribute(); } /// <summary> /// Given a type <paramref name="type"/>, which is either a nullable reference type OR /// is a constructed type with a nullable reference type present in its type argument tree, /// returns a synthesized NullableAttribute with encoded nullable transforms array. /// </summary> internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(Symbol symbol, byte? nullableContextValue, TypeWithAnnotations type) { if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var flagsBuilder = ArrayBuilder<byte>.GetInstance(); type.AddNullableTransforms(flagsBuilder); SynthesizedAttributeData attribute; if (!flagsBuilder.Any()) { attribute = null; } else { Debug.Assert(flagsBuilder.All(f => f <= 2)); byte? commonValue = MostCommonNullableValueBuilder.GetCommonValue(flagsBuilder); if (commonValue != null) { attribute = SynthesizeNullableAttributeIfNecessary(nullableContextValue, commonValue.GetValueOrDefault()); } else { NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); var byteArrayType = ArrayTypeSymbol.CreateSZArray(byteType.ContainingAssembly, TypeWithAnnotations.Create(byteType)); var value = flagsBuilder.SelectAsArray((flag, byteType) => new TypedConstant(byteType, TypedConstantKind.Primitive, flag), byteType); attribute = SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, ImmutableArray.Create(new TypedConstant(byteArrayType, value))); } } flagsBuilder.Free(); return attribute; } internal SynthesizedAttributeData SynthesizeNullableAttributeIfNecessary(byte? nullableContextValue, byte nullableValue) { if (nullableValue == nullableContextValue || (nullableContextValue == null && nullableValue == 0)) { return null; } NamedTypeSymbol byteType = Compilation.GetSpecialType(SpecialType.System_Byte); return SynthesizeNullableAttribute( WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, ImmutableArray.Create(new TypedConstant(byteType, TypedConstantKind.Primitive, nullableValue))); } internal virtual SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNullableContextAttribute(Symbol symbol, byte value) { var module = Compilation.SourceModule; if ((object)module != symbol && (object)module != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } return SynthesizeNullableContextAttribute( ImmutableArray.Create(new TypedConstant(Compilation.GetSpecialType(SpecialType.System_Byte), TypedConstantKind.Primitive, value))); } internal virtual SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, arguments, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizePreserveBaseOverridesAttribute() { return Compilation.TrySynthesizeAttribute(SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor, isOptionalUse: true); } internal SynthesizedAttributeData SynthesizeNativeIntegerAttribute(Symbol symbol, TypeSymbol type) { Debug.Assert((object)type != null); Debug.Assert(type.ContainsNativeInteger()); if ((object)Compilation.SourceModule != symbol.ContainingModule) { // For symbols that are not defined in the same compilation (like NoPia), don't synthesize this attribute. return null; } var builder = ArrayBuilder<bool>.GetInstance(); CSharpCompilation.NativeIntegerTransformsEncoder.Encode(builder, type); Debug.Assert(builder.Any()); Debug.Assert(builder.Contains(true)); SynthesizedAttributeData attribute; if (builder.Count == 1 && builder[0]) { attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, ImmutableArray<TypedConstant>.Empty); } else { NamedTypeSymbol booleanType = Compilation.GetSpecialType(SpecialType.System_Boolean); Debug.Assert((object)booleanType != null); var transformFlags = builder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); attribute = SynthesizeNativeIntegerAttribute(WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, arguments); } builder.Free(); return attribute; } internal virtual SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. // https://github.com/dotnet/roslyn/issues/30062 Should not be optional. return Compilation.TrySynthesizeAttribute(member, arguments, isOptionalUse: true); } internal bool ShouldEmitNullablePublicOnlyAttribute() { // No need to look at this.GetNeedsGeneratedAttributes() since those bits are // only set for members generated by the rewriter which are not public. return Compilation.GetUsesNullableAttributes() && Compilation.EmitNullablePublicOnly; } internal virtual SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments) { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, arguments); } protected virtual SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); } protected virtual SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute() { // For modules, this attribute should be present. Only assemblies generate and embed this type. return Compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); if ((GetNeedsGeneratedAttributesInternal() & attribute) != 0) { return; } // Don't report any errors. They should be reported during binding. if (Compilation.CheckIfAttributeShouldBeEmbedded(attribute, diagnosticsOpt: null, locationOpt: null)) { SetNeedsGeneratedAttributes(attribute); } } internal void EnsureIsReadOnlyAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute); } internal void EnsureIsUnmanagedAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute); } internal void EnsureNullableAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute); } internal void EnsureNullableContextAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute); } internal void EnsureNativeIntegerAttributeExists() { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute); } public override IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context) { return GetAdditionalTopLevelTypes() #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public override IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context) { return GetEmbeddedTypes(context.Diagnostics) #if DEBUG .Select(type => type.GetCciAdapter()) #endif ; } public sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) { return GetEmbeddedTypes(new BindingDiagnosticBag(diagnostics)); } internal virtual ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics) { return base.GetEmbeddedTypes(diagnostics.DiagnosticBag); } } }
1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/Emit/CommonPEModuleBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit.NoPia; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class CommonPEModuleBuilder : Cci.IUnit, Cci.IModuleReference { internal readonly DebugDocumentsBuilder DebugDocumentsBuilder; internal readonly IEnumerable<ResourceDescription> ManifestResources; internal readonly Cci.ModulePropertiesForSerialization SerializationProperties; internal readonly OutputKind OutputKind; internal Stream RawWin32Resources; internal IEnumerable<Cci.IWin32Resource> Win32Resources; internal Cci.ResourceSection Win32ResourceSection; internal Stream SourceLinkStreamOpt; internal Cci.IMethodReference PEEntryPoint; internal Cci.IMethodReference DebugEntryPoint; private readonly ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody> _methodBodyMap; private readonly TokenMap _referencesInILMap = new(); private readonly ItemTokenMap<string> _stringsInILMap = new(); private readonly ItemTokenMap<Cci.DebugSourceDocument> _sourceDocumentsInILMap = new(); private ImmutableArray<Cci.AssemblyReferenceAlias> _lazyAssemblyReferenceAliases; private ImmutableArray<Cci.ManagedResource> _lazyManagedResources; private IEnumerable<EmbeddedText> _embeddedTexts = SpecializedCollections.EmptyEnumerable<EmbeddedText>(); // Only set when running tests to allow realized IL for a given method to be looked up by method. internal ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> TestData { get; private set; } internal EmitOptions EmitOptions { get; } internal DebugInformationFormat DebugInformationFormat => EmitOptions.DebugInformationFormat; internal HashAlgorithmName PdbChecksumAlgorithm => EmitOptions.PdbChecksumAlgorithm; public CommonPEModuleBuilder( IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, Compilation compilation) { Debug.Assert(manifestResources != null); Debug.Assert(serializationProperties != null); Debug.Assert(compilation != null); ManifestResources = manifestResources; DebugDocumentsBuilder = new DebugDocumentsBuilder(compilation.Options.SourceReferenceResolver, compilation.IsCaseSensitive); OutputKind = outputKind; SerializationProperties = serializationProperties; _methodBodyMap = new ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody>(ReferenceEqualityComparer.Instance); EmitOptions = emitOptions; } #nullable enable /// <summary> /// Symbol changes when emitting EnC delta. /// </summary> public abstract SymbolChanges? EncSymbolChanges { get; } /// <summary> /// Previous EnC generation baseline, or null if this is not EnC delta. /// </summary> public abstract EmitBaseline? PreviousGeneration { get; } /// <summary> /// True if this module is an EnC update. /// </summary> public bool IsEncDelta => PreviousGeneration != null; /// <summary> /// EnC generation. 0 if the module is not an EnC delta, 1 if it is the first EnC delta, etc. /// </summary> public int CurrentGenerationOrdinal => (PreviousGeneration?.Ordinal + 1) ?? 0; #nullable disable /// <summary> /// If this module represents an assembly, name of the assembly used in AssemblyDef table. Otherwise name of the module same as <see cref="ModuleName"/>. /// </summary> public abstract string Name { get; } /// <summary> /// Name of the module. Used in ModuleDef table. /// </summary> internal abstract string ModuleName { get; } internal abstract Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration); internal abstract bool SupportsPrivateImplClass { get; } internal abstract Compilation CommonCompilation { get; } internal abstract IModuleSymbolInternal CommonSourceModule { get; } internal abstract IAssemblySymbolInternal CommonCorLibrary { get; } internal abstract CommonModuleCompilationState CommonModuleCompilationState { get; } internal abstract void CompilationFinished(); internal abstract ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers(); internal abstract CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt { get; } internal abstract Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly); public abstract IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes(); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes(); internal abstract Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor); /// <summary> /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly /// followed by types forwarded to another assembly. /// </summary> public abstract ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics); /// <summary> /// Used to distinguish which style to pick while writing native PDB information. /// </summary> /// <remarks> /// The PDB content for custom debug information is different between Visual Basic and CSharp. /// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where /// as VB only outputs namespace imports into the namespace scopes. /// C# defines forwards in that header, VB includes them into the scopes list. /// /// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module. /// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly. /// </remarks> public abstract bool GenerateVisualBasicStylePdb { get; } /// <summary> /// Linked assembly names to be stored to native PDB (VB only). /// </summary> public abstract IEnumerable<string> LinkedAssembliesDebugInfo { get; } /// <summary> /// Project level imports (VB only, TODO: C# scripts). /// </summary> public abstract ImmutableArray<Cci.UsedNamespaceOrType> GetImports(); /// <summary> /// Default namespace (VB only). /// </summary> public abstract string DefaultNamespace { get; } protected abstract Cci.IAssemblyReference GetCorLibraryReferenceToEmit(EmitContext context); protected abstract IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics); protected abstract void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics); public abstract Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context); public abstract bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType); public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context); public IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitionsCore(EmitContext context) { foreach (var typeDef in GetAdditionalTopLevelTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetEmbeddedTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetTopLevelSourceTypeDefinitions(context)) { yield return typeDef; } } /// <summary> /// Additional top-level types injected by the Expression Evaluators. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context); /// <summary> /// Anonymous types defined in the compilation. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context); /// <summary> /// Top-level embedded types (e.g. attribute types that are not present in referenced assemblies). /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context); /// <summary> /// Top-level named types defined in source. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context); /// <summary> /// A list of the files that constitute the assembly. Empty for netmodule. These are not the source language files that may have been /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well /// as any external resources. It corresponds to the File table of the .NET assembly file format. /// </summary> public abstract IEnumerable<Cci.IFileReference> GetFiles(EmitContext context); /// <summary> /// Builds symbol definition to location map used for emitting token -> location info /// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj) /// </summary> public abstract MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap(); /// <summary> /// Number of debug documents in the module. /// Used to determine capacities of lists and indices when emitting debug info. /// </summary> public int DebugDocumentCount => DebugDocumentsBuilder.DebugDocumentCount; public void Dispatch(Cci.MetadataVisitor visitor) => visitor.Visit(this); IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { Debug.Assert(ReferenceEquals(context.Module, this)); return this; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public abstract ISourceAssemblySymbolInternal SourceAssemblyOpt { get; } /// <summary> /// An approximate number of method definitions that can /// provide a basis for approximating the capacities of /// various databases used during Emit. /// </summary> public int HintNumberOfMethodDefinitions // Try to guess at the size of tables to prevent re-allocation. The method body // map is pretty close, but unfortunately it tends to undercount. x1.5 seems like // a healthy amount of room based on compiling Roslyn. => (int)(_methodBodyMap.Count * 1.5); internal Cci.IMethodBody GetMethodBody(IMethodSymbolInternal methodSymbol) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Cci.IMethodBody body; if (_methodBodyMap.TryGetValue(methodSymbol, out body)) { return body; } return null; } public void SetMethodBody(IMethodSymbolInternal methodSymbol, Cci.IMethodBody body) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Debug.Assert(body == null || (object)methodSymbol == body.MethodDefinition.GetInternalSymbol()); _methodBodyMap.Add(methodSymbol, body); } internal void SetPEEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); Debug.Assert(OutputKind.IsApplication()); PEEntryPoint = Translate(method, diagnostics, needDeclaration: true); } internal void SetDebugEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); DebugEntryPoint = Translate(method, diagnostics, needDeclaration: true); } private bool IsSourceDefinition(IMethodSymbolInternal method) { return method.ContainingModule == CommonSourceModule && method.IsDefinition; } /// <summary> /// CorLibrary assembly referenced by this module. /// </summary> public Cci.IAssemblyReference GetCorLibrary(EmitContext context) { return Translate(CommonCorLibrary, context.Diagnostics); } public Cci.IAssemblyReference GetContainingAssembly(EmitContext context) { return OutputKind == OutputKind.NetModule ? null : (Cci.IAssemblyReference)this; } /// <summary> /// Returns User Strings referenced from the IL in the module. /// </summary> public IEnumerable<string> GetStrings() { return _stringsInILMap.GetAllItems(); } public uint GetFakeSymbolTokenForIL(Cci.IReference symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitReference(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetFakeSymbolTokenForIL(Cci.ISignature symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitSignature(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetSourceDocumentIndexForIL(Cci.DebugSourceDocument document) { return _sourceDocumentsInILMap.GetOrAddTokenFor(document); } internal Cci.DebugSourceDocument GetSourceDocumentFromIndex(uint token) { return _sourceDocumentsInILMap.GetItem(token); } public object GetReferenceFromToken(uint token) { return _referencesInILMap.GetItem(token); } public uint GetFakeStringTokenForIL(string str) { return _stringsInILMap.GetOrAddTokenFor(str); } public string GetStringFromToken(uint token) { return _stringsInILMap.GetItem(token); } public ReadOnlySpan<object> ReferencesInIL() { return _referencesInILMap.GetAllItems(); } /// <summary> /// Assembly reference aliases (C# only). /// </summary> public ImmutableArray<Cci.AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context) { if (_lazyAssemblyReferenceAliases.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssemblyReferenceAliases, CalculateAssemblyReferenceAliases(context), default(ImmutableArray<Cci.AssemblyReferenceAlias>)); } return _lazyAssemblyReferenceAliases; } private ImmutableArray<Cci.AssemblyReferenceAlias> CalculateAssemblyReferenceAliases(EmitContext context) { var result = ArrayBuilder<Cci.AssemblyReferenceAlias>.GetInstance(); foreach (var assemblyAndAliases in CommonCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { var assembly = assemblyAndAliases.Item1; var aliases = assemblyAndAliases.Item2; for (int i = 0; i < aliases.Length; i++) { string alias = aliases[i]; // filter out duplicates and global aliases: if (alias != MetadataReferenceProperties.GlobalAlias && aliases.IndexOf(alias, 0, i) < 0) { result.Add(new Cci.AssemblyReferenceAlias(alias, Translate(assembly, context.Diagnostics))); } } } return result.ToImmutableAndFree(); } public IEnumerable<Cci.IAssemblyReference> GetAssemblyReferences(EmitContext context) { Cci.IAssemblyReference corLibrary = GetCorLibraryReferenceToEmit(context); // Only add Cor Library reference explicitly, PeWriter will add // other references implicitly on as needed basis. if (corLibrary != null) { yield return corLibrary; } if (OutputKind != OutputKind.NetModule) { // Explicitly add references from added modules foreach (var aRef in GetAssemblyReferencesFromAddedModules(context.Diagnostics)) { yield return aRef; } } } public ImmutableArray<Cci.ManagedResource> GetResources(EmitContext context) { if (context.IsRefAssembly) { // Manifest resources are not included in ref assemblies // Ref assemblies don't support added modules return ImmutableArray<Cci.ManagedResource>.Empty; } if (_lazyManagedResources.IsDefault) { var builder = ArrayBuilder<Cci.ManagedResource>.GetInstance(); foreach (ResourceDescription r in ManifestResources) { builder.Add(r.ToManagedResource(this)); } if (OutputKind != OutputKind.NetModule) { // Explicitly add resources from added modules AddEmbeddedResourcesFromAddedModules(builder, context.Diagnostics); } _lazyManagedResources = builder.ToImmutableAndFree(); } return _lazyManagedResources; } public IEnumerable<EmbeddedText> EmbeddedTexts { get { return _embeddedTexts; } set { Debug.Assert(value != null); _embeddedTexts = value; } } internal bool SaveTestData => TestData != null; internal void SetMethodTestData(IMethodSymbolInternal method, ILBuilder builder) { TestData.Add(method, new CompilationTestData.MethodData(builder, method)); } internal void SetMethodTestData(ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> methods) { Debug.Assert(TestData == null); TestData = methods; } public int GetTypeDefinitionGeneration(Cci.INamedTypeDefinition typeDef) { if (PreviousGeneration != null) { var symbolChanges = EncSymbolChanges!; if (symbolChanges.IsReplaced(typeDef)) { // Type emitted with Replace semantics in this delta, it's name should have the current generation ordinal suffix. return CurrentGenerationOrdinal; } var previousTypeDef = symbolChanges.DefinitionMap.MapDefinition(typeDef); if (previousTypeDef != null && PreviousGeneration.GenerationOrdinals.TryGetValue(previousTypeDef, out int lastEmittedOrdinal)) { // Type previously emitted with Replace semantics is now updated in-place. Use the ordinal used to emit the last version of the type. return lastEmittedOrdinal; } } return 0; } } /// <summary> /// Common base class for C# and VB PE module builder. /// </summary> internal abstract class PEModuleBuilder<TCompilation, TSourceModuleSymbol, TAssemblySymbol, TTypeSymbol, TNamedTypeSymbol, TMethodSymbol, TSyntaxNode, TEmbeddedTypesManager, TModuleCompilationState> : CommonPEModuleBuilder, ITokenDeferral where TCompilation : Compilation where TSourceModuleSymbol : class, IModuleSymbolInternal where TAssemblySymbol : class, IAssemblySymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TNamedTypeSymbol : class, TTypeSymbol, INamedTypeSymbolInternal where TMethodSymbol : class, IMethodSymbolInternal where TSyntaxNode : SyntaxNode where TEmbeddedTypesManager : CommonEmbeddedTypesManager where TModuleCompilationState : ModuleCompilationState<TNamedTypeSymbol, TMethodSymbol> { internal readonly TSourceModuleSymbol SourceModule; internal readonly TCompilation Compilation; private PrivateImplementationDetails _privateImplementationDetails; private ArrayMethods _lazyArrayMethods; private HashSet<string> _namesOfTopLevelTypes; internal readonly TModuleCompilationState CompilationState; private readonly Cci.RootModuleType _rootModuleType; public abstract TEmbeddedTypesManager EmbeddedTypesManagerOpt { get; } protected PEModuleBuilder( TCompilation compilation, TSourceModuleSymbol sourceModule, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, OutputKind outputKind, EmitOptions emitOptions, TModuleCompilationState compilationState) : base(manifestResources, emitOptions, outputKind, serializationProperties, compilation) { Debug.Assert(sourceModule != null); Debug.Assert(serializationProperties != null); Compilation = compilation; SourceModule = sourceModule; this.CompilationState = compilationState; _rootModuleType = new Cci.RootModuleType(this); } public Cci.RootModuleType RootModuleType => _rootModuleType; internal sealed override void CompilationFinished() { this.CompilationState.Freeze(); } internal override IAssemblySymbolInternal CommonCorLibrary => CorLibrary; internal abstract TAssemblySymbol CorLibrary { get; } internal abstract Cci.INamedTypeReference GetSpecialType(SpecialType specialType, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal sealed override Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics) { return EncTranslateLocalVariableType((TTypeSymbol)type, diagnostics); } internal virtual Cci.ITypeReference EncTranslateLocalVariableType(TTypeSymbol type, DiagnosticBag diagnostics) { return Translate(type, null, diagnostics); } protected bool HaveDeterminedTopLevelTypes { get { return _namesOfTopLevelTypes != null; } } protected bool ContainsTopLevelType(string fullEmittedName) { return _namesOfTopLevelTypes.Contains(fullEmittedName); } /// <summary> /// Returns all top-level (not nested) types defined in the module. /// </summary> public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context) { Cci.TypeReferenceIndexer typeReferenceIndexer = null; HashSet<string> names; // First time through, we need to collect emitted names of all top level types. if (_namesOfTopLevelTypes == null) { names = new HashSet<string>(); } else { names = null; } // First time through, we need to push things through TypeReferenceIndexer // to make sure we collect all to be embedded NoPia types and members. if (EmbeddedTypesManagerOpt != null && !EmbeddedTypesManagerOpt.IsFrozen) { typeReferenceIndexer = new Cci.TypeReferenceIndexer(context); Debug.Assert(names != null); // Run this reference indexer on the assembly- and module-level attributes first. // We'll run it on all other types below. // The purpose is to trigger Translate on all types. Dispatch(typeReferenceIndexer); } AddTopLevelType(names, RootModuleType); VisitTopLevelType(typeReferenceIndexer, RootModuleType); yield return RootModuleType; foreach (var typeDef in GetAnonymousTypeDefinitions(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } foreach (var typeDef in GetTopLevelTypeDefinitionsCore(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } var privateImpl = PrivateImplClass; if (privateImpl != null) { AddTopLevelType(names, privateImpl); VisitTopLevelType(typeReferenceIndexer, privateImpl); yield return privateImpl; } if (EmbeddedTypesManagerOpt != null) { foreach (var embedded in EmbeddedTypesManagerOpt.GetTypes(context.Diagnostics, names)) { AddTopLevelType(names, embedded); yield return embedded; } } if (names != null) { Debug.Assert(_namesOfTopLevelTypes == null); _namesOfTopLevelTypes = names; } static void AddTopLevelType(HashSet<string> names, Cci.INamespaceTypeDefinition type) // _namesOfTopLevelTypes are only used to generated exported types, which are not emitted in EnC deltas (hence generation 0): => names?.Add(MetadataHelpers.BuildQualifiedName(type.NamespaceName, Cci.MetadataWriter.GetMangledName(type, generation: 0))); } public virtual ImmutableArray<TNamedTypeSymbol> GetAdditionalTopLevelTypes() => ImmutableArray<TNamedTypeSymbol>.Empty; public virtual ImmutableArray<TNamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) => ImmutableArray<TNamedTypeSymbol>.Empty; internal abstract Cci.IAssemblyReference Translate(TAssemblySymbol symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(TTypeSymbol symbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(TMethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration); internal sealed override Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics) { return Translate((TAssemblySymbol)symbol, diagnostics); } internal sealed override Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate((TTypeSymbol)symbol, (TSyntaxNode)syntaxNodeOpt, diagnostics); } internal sealed override Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate((TMethodSymbol)symbol, diagnostics, needDeclaration); } internal sealed override IModuleSymbolInternal CommonSourceModule => SourceModule; internal sealed override Compilation CommonCompilation => Compilation; internal sealed override CommonModuleCompilationState CommonModuleCompilationState => CompilationState; internal sealed override CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt => EmbeddedTypesManagerOpt; internal MetadataConstant CreateConstant( TTypeSymbol type, object value, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return new MetadataConstant(Translate(type, syntaxNodeOpt, diagnostics), value); } private static void VisitTopLevelType(Cci.TypeReferenceIndexer noPiaIndexer, Cci.INamespaceTypeDefinition type) { noPiaIndexer?.Visit((Cci.ITypeDefinition)type); } internal Cci.IFieldReference GetModuleVersionId(Cci.ITypeReference mvidType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetModuleVersionId(mvidType); } internal Cci.IFieldReference GetInstrumentationPayloadRoot(int analysisKind, Cci.ITypeReference payloadType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetOrAddInstrumentationPayloadRoot(analysisKind, payloadType); } private void EnsurePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { if (details.GetMethod(WellKnownMemberNames.StaticConstructorName) == null) { details.TryAddSynthesizedMethod(CreatePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics)); } } protected abstract Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics); #region Synthesized Members /// <summary> /// Captures the set of synthesized definitions that should be added to a type /// during emit process. /// </summary> private sealed class SynthesizedDefinitions { public ConcurrentQueue<Cci.INestedTypeDefinition> NestedTypes; public ConcurrentQueue<Cci.IMethodDefinition> Methods; public ConcurrentQueue<Cci.IPropertyDefinition> Properties; public ConcurrentQueue<Cci.IFieldDefinition> Fields; public ImmutableArray<ISymbolInternal> GetAllMembers() { var builder = ArrayBuilder<ISymbolInternal>.GetInstance(); if (Fields != null) { foreach (var field in Fields) { builder.Add(field.GetInternalSymbol()); } } if (Methods != null) { foreach (var method in Methods) { builder.Add(method.GetInternalSymbol()); } } if (Properties != null) { foreach (var property in Properties) { builder.Add(property.GetInternalSymbol()); } } if (NestedTypes != null) { foreach (var type in NestedTypes) { builder.Add(type.GetInternalSymbol()); } } return builder.ToImmutableAndFree(); } } private readonly ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions> _synthesizedTypeMembers = new ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions>(ReferenceEqualityComparer.Instance); private ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>> _lazySynthesizedNamespaceMembers; internal abstract IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(TNamedTypeSymbol container); /// <summary> /// Returns null if there are no compiler generated types. /// </summary> public IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedTypes(TNamedTypeSymbol container) { IEnumerable<Cci.INestedTypeDefinition> declareTypes = GetSynthesizedNestedTypes(container); IEnumerable<Cci.INestedTypeDefinition> compileEmitTypes = null; if (_synthesizedTypeMembers.TryGetValue(container, out var defs)) { compileEmitTypes = defs.NestedTypes; } if (declareTypes == null) { return compileEmitTypes; } if (compileEmitTypes == null) { return declareTypes; } return declareTypes.Concat(compileEmitTypes); } private SynthesizedDefinitions GetOrAddSynthesizedDefinitions(TNamedTypeSymbol container) { Debug.Assert(container.IsDefinition); return _synthesizedTypeMembers.GetOrAdd(container, _ => new SynthesizedDefinitions()); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IMethodDefinition method) { Debug.Assert(method != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Methods == null) { Interlocked.CompareExchange(ref defs.Methods, new ConcurrentQueue<Cci.IMethodDefinition>(), null); } defs.Methods.Enqueue(method); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IPropertyDefinition property) { Debug.Assert(property != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Properties == null) { Interlocked.CompareExchange(ref defs.Properties, new ConcurrentQueue<Cci.IPropertyDefinition>(), null); } defs.Properties.Enqueue(property); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IFieldDefinition field) { Debug.Assert(field != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Fields == null) { Interlocked.CompareExchange(ref defs.Fields, new ConcurrentQueue<Cci.IFieldDefinition>(), null); } defs.Fields.Enqueue(field); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.INestedTypeDefinition nestedType) { Debug.Assert(nestedType != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.NestedTypes == null) { Interlocked.CompareExchange(ref defs.NestedTypes, new ConcurrentQueue<Cci.INestedTypeDefinition>(), null); } defs.NestedTypes.Enqueue(nestedType); } public void AddSynthesizedDefinition(INamespaceSymbolInternal container, INamespaceOrTypeSymbolInternal typeOrNamespace) { Debug.Assert(typeOrNamespace != null); if (_lazySynthesizedNamespaceMembers == null) { Interlocked.CompareExchange(ref _lazySynthesizedNamespaceMembers, new ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>>(), null); } _lazySynthesizedNamespaceMembers.GetOrAdd(container, _ => new ConcurrentQueue<INamespaceOrTypeSymbolInternal>()).Enqueue(typeOrNamespace); } /// <summary> /// Returns null if there are no synthesized fields. /// </summary> public IEnumerable<Cci.IFieldDefinition> GetSynthesizedFields(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Fields : null; /// <summary> /// Returns null if there are no synthesized properties. /// </summary> public IEnumerable<Cci.IPropertyDefinition> GetSynthesizedProperties(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Properties : null; /// <summary> /// Returns null if there are no synthesized methods. /// </summary> public IEnumerable<Cci.IMethodDefinition> GetSynthesizedMethods(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Methods : null; internal override ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers() { var builder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); foreach (var entry in _synthesizedTypeMembers) { builder.Add(entry.Key, entry.Value.GetAllMembers()); } var namespaceMembers = _lazySynthesizedNamespaceMembers; if (namespaceMembers != null) { foreach (var entry in namespaceMembers) { builder.Add(entry.Key, entry.Value.ToImmutableArray<ISymbolInternal>()); } } return builder.ToImmutable(); } #endregion #region Token Mapping Cci.IFieldReference ITokenDeferral.GetFieldForData(ImmutableArray<byte> data, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { Debug.Assert(this.SupportsPrivateImplClass); var privateImpl = this.GetPrivateImplClass((TSyntaxNode)syntaxNode, diagnostics); // map a field to the block (that makes it addressable via a token) return privateImpl.CreateDataField(data); } public abstract Cci.IMethodReference GetInitArrayHelper(); public ArrayMethods ArrayMethods { get { ArrayMethods result = _lazyArrayMethods; if (result == null) { result = new ArrayMethods(); if (Interlocked.CompareExchange(ref _lazyArrayMethods, result, null) != null) { result = _lazyArrayMethods; } } return result; } } #endregion #region Private Implementation Details Type internal PrivateImplementationDetails GetPrivateImplClass(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var result = _privateImplementationDetails; if ((result == null) && this.SupportsPrivateImplClass) { result = new PrivateImplementationDetails( this, this.SourceModule.Name, Compilation.GetSubmissionSlotIndex(), this.GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_ValueType, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Byte, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int16, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int32, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int64, syntaxNodeOpt, diagnostics), SynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); if (Interlocked.CompareExchange(ref _privateImplementationDetails, result, null) != null) { result = _privateImplementationDetails; } } return result; } internal PrivateImplementationDetails PrivateImplClass { get { return _privateImplementationDetails; } } internal override bool SupportsPrivateImplClass { get { return true; } } #endregion public sealed override Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context) { Debug.Assert((object)this == context.Module); switch (platformType) { case Cci.PlatformType.SystemType: throw ExceptionUtilities.UnexpectedValue(platformType); default: return GetSpecialType((SpecialType)platformType, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit.NoPia; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { internal abstract class CommonPEModuleBuilder : Cci.IUnit, Cci.IModuleReference { internal readonly DebugDocumentsBuilder DebugDocumentsBuilder; internal readonly IEnumerable<ResourceDescription> ManifestResources; internal readonly Cci.ModulePropertiesForSerialization SerializationProperties; internal readonly OutputKind OutputKind; internal Stream RawWin32Resources; internal IEnumerable<Cci.IWin32Resource> Win32Resources; internal Cci.ResourceSection Win32ResourceSection; internal Stream SourceLinkStreamOpt; internal Cci.IMethodReference PEEntryPoint; internal Cci.IMethodReference DebugEntryPoint; private readonly ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody> _methodBodyMap; private readonly TokenMap _referencesInILMap = new(); private readonly ItemTokenMap<string> _stringsInILMap = new(); private readonly ItemTokenMap<Cci.DebugSourceDocument> _sourceDocumentsInILMap = new(); private ImmutableArray<Cci.AssemblyReferenceAlias> _lazyAssemblyReferenceAliases; private ImmutableArray<Cci.ManagedResource> _lazyManagedResources; private IEnumerable<EmbeddedText> _embeddedTexts = SpecializedCollections.EmptyEnumerable<EmbeddedText>(); // Only set when running tests to allow realized IL for a given method to be looked up by method. internal ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> TestData { get; private set; } internal EmitOptions EmitOptions { get; } internal DebugInformationFormat DebugInformationFormat => EmitOptions.DebugInformationFormat; internal HashAlgorithmName PdbChecksumAlgorithm => EmitOptions.PdbChecksumAlgorithm; public CommonPEModuleBuilder( IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, OutputKind outputKind, Cci.ModulePropertiesForSerialization serializationProperties, Compilation compilation) { Debug.Assert(manifestResources != null); Debug.Assert(serializationProperties != null); Debug.Assert(compilation != null); ManifestResources = manifestResources; DebugDocumentsBuilder = new DebugDocumentsBuilder(compilation.Options.SourceReferenceResolver, compilation.IsCaseSensitive); OutputKind = outputKind; SerializationProperties = serializationProperties; _methodBodyMap = new ConcurrentDictionary<IMethodSymbolInternal, Cci.IMethodBody>(ReferenceEqualityComparer.Instance); EmitOptions = emitOptions; } #nullable enable /// <summary> /// Symbol changes when emitting EnC delta. /// </summary> public abstract SymbolChanges? EncSymbolChanges { get; } /// <summary> /// Previous EnC generation baseline, or null if this is not EnC delta. /// </summary> public abstract EmitBaseline? PreviousGeneration { get; } /// <summary> /// True if this module is an EnC update. /// </summary> public bool IsEncDelta => PreviousGeneration != null; /// <summary> /// EnC generation. 0 if the module is not an EnC delta, 1 if it is the first EnC delta, etc. /// </summary> public int CurrentGenerationOrdinal => (PreviousGeneration?.Ordinal + 1) ?? 0; #nullable disable /// <summary> /// If this module represents an assembly, name of the assembly used in AssemblyDef table. Otherwise name of the module same as <see cref="ModuleName"/>. /// </summary> public abstract string Name { get; } /// <summary> /// Name of the module. Used in ModuleDef table. /// </summary> internal abstract string ModuleName { get; } internal abstract Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration); internal abstract bool SupportsPrivateImplClass { get; } internal abstract Compilation CommonCompilation { get; } internal abstract IModuleSymbolInternal CommonSourceModule { get; } internal abstract IAssemblySymbolInternal CommonCorLibrary { get; } internal abstract CommonModuleCompilationState CommonModuleCompilationState { get; } internal abstract void CompilationFinished(); internal abstract ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers(); internal abstract CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt { get; } internal abstract Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceAssemblyAttributes(bool isRefAssembly); public abstract IEnumerable<Cci.SecurityAttribute> GetSourceAssemblySecurityAttributes(); public abstract IEnumerable<Cci.ICustomAttribute> GetSourceModuleAttributes(); internal abstract Cci.ICustomAttribute SynthesizeAttribute(WellKnownMember attributeConstructor); /// <summary> /// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly /// followed by types forwarded to another assembly. /// </summary> public abstract ImmutableArray<Cci.ExportedType> GetExportedTypes(DiagnosticBag diagnostics); /// <summary> /// Used to distinguish which style to pick while writing native PDB information. /// </summary> /// <remarks> /// The PDB content for custom debug information is different between Visual Basic and CSharp. /// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where /// as VB only outputs namespace imports into the namespace scopes. /// C# defines forwards in that header, VB includes them into the scopes list. /// /// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module. /// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly. /// </remarks> public abstract bool GenerateVisualBasicStylePdb { get; } /// <summary> /// Linked assembly names to be stored to native PDB (VB only). /// </summary> public abstract IEnumerable<string> LinkedAssembliesDebugInfo { get; } /// <summary> /// Project level imports (VB only, TODO: C# scripts). /// </summary> public abstract ImmutableArray<Cci.UsedNamespaceOrType> GetImports(); /// <summary> /// Default namespace (VB only). /// </summary> public abstract string DefaultNamespace { get; } protected abstract Cci.IAssemblyReference GetCorLibraryReferenceToEmit(EmitContext context); protected abstract IEnumerable<Cci.IAssemblyReference> GetAssemblyReferencesFromAddedModules(DiagnosticBag diagnostics); protected abstract void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics); public abstract Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context); public abstract bool IsPlatformType(Cci.ITypeReference typeRef, Cci.PlatformType platformType); public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context); public IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitionsCore(EmitContext context) { foreach (var typeDef in GetAdditionalTopLevelTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetEmbeddedTypeDefinitions(context)) { yield return typeDef; } foreach (var typeDef in GetTopLevelSourceTypeDefinitions(context)) { yield return typeDef; } } /// <summary> /// Additional top-level types injected by the Expression Evaluators. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAdditionalTopLevelTypeDefinitions(EmitContext context); /// <summary> /// Anonymous types defined in the compilation. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetAnonymousTypeDefinitions(EmitContext context); /// <summary> /// Top-level embedded types (e.g. attribute types that are not present in referenced assemblies). /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetEmbeddedTypeDefinitions(EmitContext context); /// <summary> /// Top-level named types defined in source. /// </summary> public abstract IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelSourceTypeDefinitions(EmitContext context); /// <summary> /// A list of the files that constitute the assembly. Empty for netmodule. These are not the source language files that may have been /// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well /// as any external resources. It corresponds to the File table of the .NET assembly file format. /// </summary> public abstract IEnumerable<Cci.IFileReference> GetFiles(EmitContext context); /// <summary> /// Builds symbol definition to location map used for emitting token -> location info /// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj) /// </summary> public abstract MultiDictionary<Cci.DebugSourceDocument, Cci.DefinitionWithLocation> GetSymbolToLocationMap(); /// <summary> /// Builds a list of types, and their documents, that would otherwise not be referenced by any document info /// of any methods in those types, or any nested types. This data is helpful for navigating to the source of /// types that have no methods in one or more of the source files they are contained in. /// /// For example: /// /// First.cs: /// <code> /// partial class Outer /// { /// partial class Inner /// { /// public void Method() /// { /// } /// } /// } /// </code> /// /// /// Second.cs: /// <code> /// partial class Outer /// { /// partial class Inner /// { /// } /// } /// </code> /// /// When navigating to the definition of "Outer" we know about First.cs because of the MethodDebugInfo for Outer.Inner.Method() /// but there would be no document information for Second.cs so this method would return that information. /// /// When navigating to "Inner" we likewise know about First.cs because of the MethodDebugInfo, and we know about Second.cs because /// of the document info for its containing type, so this method would not return information for Inner. In fact this method /// will never return information for any nested type. /// </summary> /// <param name="context"></param> /// <returns></returns> public abstract IEnumerable<(Cci.ITypeDefinition, ImmutableArray<Cci.DebugSourceDocument>)> GetTypeToDebugDocumentMap(EmitContext context); /// <summary> /// Number of debug documents in the module. /// Used to determine capacities of lists and indices when emitting debug info. /// </summary> public int DebugDocumentCount => DebugDocumentsBuilder.DebugDocumentCount; public void Dispatch(Cci.MetadataVisitor visitor) => visitor.Visit(this); IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) => SpecializedCollections.EmptyEnumerable<Cci.ICustomAttribute>(); Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { Debug.Assert(ReferenceEquals(context.Module, this)); return this; } Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; public abstract ISourceAssemblySymbolInternal SourceAssemblyOpt { get; } /// <summary> /// An approximate number of method definitions that can /// provide a basis for approximating the capacities of /// various databases used during Emit. /// </summary> public int HintNumberOfMethodDefinitions // Try to guess at the size of tables to prevent re-allocation. The method body // map is pretty close, but unfortunately it tends to undercount. x1.5 seems like // a healthy amount of room based on compiling Roslyn. => (int)(_methodBodyMap.Count * 1.5); internal Cci.IMethodBody GetMethodBody(IMethodSymbolInternal methodSymbol) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Cci.IMethodBody body; if (_methodBodyMap.TryGetValue(methodSymbol, out body)) { return body; } return null; } public void SetMethodBody(IMethodSymbolInternal methodSymbol, Cci.IMethodBody body) { Debug.Assert(methodSymbol.ContainingModule == CommonSourceModule); Debug.Assert(methodSymbol.IsDefinition); Debug.Assert(((IMethodSymbol)methodSymbol.GetISymbol()).PartialDefinitionPart == null); // Must be definition. Debug.Assert(body == null || (object)methodSymbol == body.MethodDefinition.GetInternalSymbol()); _methodBodyMap.Add(methodSymbol, body); } internal void SetPEEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); Debug.Assert(OutputKind.IsApplication()); PEEntryPoint = Translate(method, diagnostics, needDeclaration: true); } internal void SetDebugEntryPoint(IMethodSymbolInternal method, DiagnosticBag diagnostics) { Debug.Assert(method == null || IsSourceDefinition(method)); DebugEntryPoint = Translate(method, diagnostics, needDeclaration: true); } private bool IsSourceDefinition(IMethodSymbolInternal method) { return method.ContainingModule == CommonSourceModule && method.IsDefinition; } /// <summary> /// CorLibrary assembly referenced by this module. /// </summary> public Cci.IAssemblyReference GetCorLibrary(EmitContext context) { return Translate(CommonCorLibrary, context.Diagnostics); } public Cci.IAssemblyReference GetContainingAssembly(EmitContext context) { return OutputKind == OutputKind.NetModule ? null : (Cci.IAssemblyReference)this; } /// <summary> /// Returns User Strings referenced from the IL in the module. /// </summary> public IEnumerable<string> GetStrings() { return _stringsInILMap.GetAllItems(); } public uint GetFakeSymbolTokenForIL(Cci.IReference symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitReference(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetFakeSymbolTokenForIL(Cci.ISignature symbol, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { uint token = _referencesInILMap.GetOrAddTokenFor(symbol, out bool added); if (added) { ReferenceDependencyWalker.VisitSignature(symbol, new EmitContext(this, syntaxNode, diagnostics, metadataOnly: false, includePrivateMembers: true)); } return token; } public uint GetSourceDocumentIndexForIL(Cci.DebugSourceDocument document) { return _sourceDocumentsInILMap.GetOrAddTokenFor(document); } internal Cci.DebugSourceDocument GetSourceDocumentFromIndex(uint token) { return _sourceDocumentsInILMap.GetItem(token); } public object GetReferenceFromToken(uint token) { return _referencesInILMap.GetItem(token); } public uint GetFakeStringTokenForIL(string str) { return _stringsInILMap.GetOrAddTokenFor(str); } public string GetStringFromToken(uint token) { return _stringsInILMap.GetItem(token); } public ReadOnlySpan<object> ReferencesInIL() { return _referencesInILMap.GetAllItems(); } /// <summary> /// Assembly reference aliases (C# only). /// </summary> public ImmutableArray<Cci.AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context) { if (_lazyAssemblyReferenceAliases.IsDefault) { ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssemblyReferenceAliases, CalculateAssemblyReferenceAliases(context), default(ImmutableArray<Cci.AssemblyReferenceAlias>)); } return _lazyAssemblyReferenceAliases; } private ImmutableArray<Cci.AssemblyReferenceAlias> CalculateAssemblyReferenceAliases(EmitContext context) { var result = ArrayBuilder<Cci.AssemblyReferenceAlias>.GetInstance(); foreach (var assemblyAndAliases in CommonCompilation.GetBoundReferenceManager().GetReferencedAssemblyAliases()) { var assembly = assemblyAndAliases.Item1; var aliases = assemblyAndAliases.Item2; for (int i = 0; i < aliases.Length; i++) { string alias = aliases[i]; // filter out duplicates and global aliases: if (alias != MetadataReferenceProperties.GlobalAlias && aliases.IndexOf(alias, 0, i) < 0) { result.Add(new Cci.AssemblyReferenceAlias(alias, Translate(assembly, context.Diagnostics))); } } } return result.ToImmutableAndFree(); } public IEnumerable<Cci.IAssemblyReference> GetAssemblyReferences(EmitContext context) { Cci.IAssemblyReference corLibrary = GetCorLibraryReferenceToEmit(context); // Only add Cor Library reference explicitly, PeWriter will add // other references implicitly on as needed basis. if (corLibrary != null) { yield return corLibrary; } if (OutputKind != OutputKind.NetModule) { // Explicitly add references from added modules foreach (var aRef in GetAssemblyReferencesFromAddedModules(context.Diagnostics)) { yield return aRef; } } } public ImmutableArray<Cci.ManagedResource> GetResources(EmitContext context) { if (context.IsRefAssembly) { // Manifest resources are not included in ref assemblies // Ref assemblies don't support added modules return ImmutableArray<Cci.ManagedResource>.Empty; } if (_lazyManagedResources.IsDefault) { var builder = ArrayBuilder<Cci.ManagedResource>.GetInstance(); foreach (ResourceDescription r in ManifestResources) { builder.Add(r.ToManagedResource(this)); } if (OutputKind != OutputKind.NetModule) { // Explicitly add resources from added modules AddEmbeddedResourcesFromAddedModules(builder, context.Diagnostics); } _lazyManagedResources = builder.ToImmutableAndFree(); } return _lazyManagedResources; } public IEnumerable<EmbeddedText> EmbeddedTexts { get { return _embeddedTexts; } set { Debug.Assert(value != null); _embeddedTexts = value; } } internal bool SaveTestData => TestData != null; internal void SetMethodTestData(IMethodSymbolInternal method, ILBuilder builder) { TestData.Add(method, new CompilationTestData.MethodData(builder, method)); } internal void SetMethodTestData(ConcurrentDictionary<IMethodSymbolInternal, CompilationTestData.MethodData> methods) { Debug.Assert(TestData == null); TestData = methods; } public int GetTypeDefinitionGeneration(Cci.INamedTypeDefinition typeDef) { if (PreviousGeneration != null) { var symbolChanges = EncSymbolChanges!; if (symbolChanges.IsReplaced(typeDef)) { // Type emitted with Replace semantics in this delta, it's name should have the current generation ordinal suffix. return CurrentGenerationOrdinal; } var previousTypeDef = symbolChanges.DefinitionMap.MapDefinition(typeDef); if (previousTypeDef != null && PreviousGeneration.GenerationOrdinals.TryGetValue(previousTypeDef, out int lastEmittedOrdinal)) { // Type previously emitted with Replace semantics is now updated in-place. Use the ordinal used to emit the last version of the type. return lastEmittedOrdinal; } } return 0; } } /// <summary> /// Common base class for C# and VB PE module builder. /// </summary> internal abstract class PEModuleBuilder<TCompilation, TSourceModuleSymbol, TAssemblySymbol, TTypeSymbol, TNamedTypeSymbol, TMethodSymbol, TSyntaxNode, TEmbeddedTypesManager, TModuleCompilationState> : CommonPEModuleBuilder, ITokenDeferral where TCompilation : Compilation where TSourceModuleSymbol : class, IModuleSymbolInternal where TAssemblySymbol : class, IAssemblySymbolInternal where TTypeSymbol : class, ITypeSymbolInternal where TNamedTypeSymbol : class, TTypeSymbol, INamedTypeSymbolInternal where TMethodSymbol : class, IMethodSymbolInternal where TSyntaxNode : SyntaxNode where TEmbeddedTypesManager : CommonEmbeddedTypesManager where TModuleCompilationState : ModuleCompilationState<TNamedTypeSymbol, TMethodSymbol> { internal readonly TSourceModuleSymbol SourceModule; internal readonly TCompilation Compilation; private PrivateImplementationDetails _privateImplementationDetails; private ArrayMethods _lazyArrayMethods; private HashSet<string> _namesOfTopLevelTypes; internal readonly TModuleCompilationState CompilationState; private readonly Cci.RootModuleType _rootModuleType; public abstract TEmbeddedTypesManager EmbeddedTypesManagerOpt { get; } protected PEModuleBuilder( TCompilation compilation, TSourceModuleSymbol sourceModule, Cci.ModulePropertiesForSerialization serializationProperties, IEnumerable<ResourceDescription> manifestResources, OutputKind outputKind, EmitOptions emitOptions, TModuleCompilationState compilationState) : base(manifestResources, emitOptions, outputKind, serializationProperties, compilation) { Debug.Assert(sourceModule != null); Debug.Assert(serializationProperties != null); Compilation = compilation; SourceModule = sourceModule; this.CompilationState = compilationState; _rootModuleType = new Cci.RootModuleType(this); } public Cci.RootModuleType RootModuleType => _rootModuleType; internal sealed override void CompilationFinished() { this.CompilationState.Freeze(); } internal override IAssemblySymbolInternal CommonCorLibrary => CorLibrary; internal abstract TAssemblySymbol CorLibrary { get; } internal abstract Cci.INamedTypeReference GetSpecialType(SpecialType specialType, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal sealed override Cci.ITypeReference EncTranslateType(ITypeSymbolInternal type, DiagnosticBag diagnostics) { return EncTranslateLocalVariableType((TTypeSymbol)type, diagnostics); } internal virtual Cci.ITypeReference EncTranslateLocalVariableType(TTypeSymbol type, DiagnosticBag diagnostics) { return Translate(type, null, diagnostics); } protected bool HaveDeterminedTopLevelTypes { get { return _namesOfTopLevelTypes != null; } } protected bool ContainsTopLevelType(string fullEmittedName) { return _namesOfTopLevelTypes.Contains(fullEmittedName); } /// <summary> /// Returns all top-level (not nested) types defined in the module. /// </summary> public override IEnumerable<Cci.INamespaceTypeDefinition> GetTopLevelTypeDefinitions(EmitContext context) { Cci.TypeReferenceIndexer typeReferenceIndexer = null; HashSet<string> names; // First time through, we need to collect emitted names of all top level types. if (_namesOfTopLevelTypes == null) { names = new HashSet<string>(); } else { names = null; } // First time through, we need to push things through TypeReferenceIndexer // to make sure we collect all to be embedded NoPia types and members. if (EmbeddedTypesManagerOpt != null && !EmbeddedTypesManagerOpt.IsFrozen) { typeReferenceIndexer = new Cci.TypeReferenceIndexer(context); Debug.Assert(names != null); // Run this reference indexer on the assembly- and module-level attributes first. // We'll run it on all other types below. // The purpose is to trigger Translate on all types. Dispatch(typeReferenceIndexer); } AddTopLevelType(names, RootModuleType); VisitTopLevelType(typeReferenceIndexer, RootModuleType); yield return RootModuleType; foreach (var typeDef in GetAnonymousTypeDefinitions(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } foreach (var typeDef in GetTopLevelTypeDefinitionsCore(context)) { AddTopLevelType(names, typeDef); VisitTopLevelType(typeReferenceIndexer, typeDef); yield return typeDef; } var privateImpl = PrivateImplClass; if (privateImpl != null) { AddTopLevelType(names, privateImpl); VisitTopLevelType(typeReferenceIndexer, privateImpl); yield return privateImpl; } if (EmbeddedTypesManagerOpt != null) { foreach (var embedded in EmbeddedTypesManagerOpt.GetTypes(context.Diagnostics, names)) { AddTopLevelType(names, embedded); yield return embedded; } } if (names != null) { Debug.Assert(_namesOfTopLevelTypes == null); _namesOfTopLevelTypes = names; } static void AddTopLevelType(HashSet<string> names, Cci.INamespaceTypeDefinition type) // _namesOfTopLevelTypes are only used to generated exported types, which are not emitted in EnC deltas (hence generation 0): => names?.Add(MetadataHelpers.BuildQualifiedName(type.NamespaceName, Cci.MetadataWriter.GetMangledName(type, generation: 0))); } public virtual ImmutableArray<TNamedTypeSymbol> GetAdditionalTopLevelTypes() => ImmutableArray<TNamedTypeSymbol>.Empty; public virtual ImmutableArray<TNamedTypeSymbol> GetEmbeddedTypes(DiagnosticBag diagnostics) => ImmutableArray<TNamedTypeSymbol>.Empty; internal abstract Cci.IAssemblyReference Translate(TAssemblySymbol symbol, DiagnosticBag diagnostics); internal abstract Cci.ITypeReference Translate(TTypeSymbol symbol, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics); internal abstract Cci.IMethodReference Translate(TMethodSymbol symbol, DiagnosticBag diagnostics, bool needDeclaration); internal sealed override Cci.IAssemblyReference Translate(IAssemblySymbolInternal symbol, DiagnosticBag diagnostics) { return Translate((TAssemblySymbol)symbol, diagnostics); } internal sealed override Cci.ITypeReference Translate(ITypeSymbolInternal symbol, SyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return Translate((TTypeSymbol)symbol, (TSyntaxNode)syntaxNodeOpt, diagnostics); } internal sealed override Cci.IMethodReference Translate(IMethodSymbolInternal symbol, DiagnosticBag diagnostics, bool needDeclaration) { return Translate((TMethodSymbol)symbol, diagnostics, needDeclaration); } internal sealed override IModuleSymbolInternal CommonSourceModule => SourceModule; internal sealed override Compilation CommonCompilation => Compilation; internal sealed override CommonModuleCompilationState CommonModuleCompilationState => CompilationState; internal sealed override CommonEmbeddedTypesManager CommonEmbeddedTypesManagerOpt => EmbeddedTypesManagerOpt; internal MetadataConstant CreateConstant( TTypeSymbol type, object value, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { return new MetadataConstant(Translate(type, syntaxNodeOpt, diagnostics), value); } private static void VisitTopLevelType(Cci.TypeReferenceIndexer noPiaIndexer, Cci.INamespaceTypeDefinition type) { noPiaIndexer?.Visit((Cci.ITypeDefinition)type); } internal Cci.IFieldReference GetModuleVersionId(Cci.ITypeReference mvidType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetModuleVersionId(mvidType); } internal Cci.IFieldReference GetInstrumentationPayloadRoot(int analysisKind, Cci.ITypeReference payloadType, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { PrivateImplementationDetails details = GetPrivateImplClass(syntaxOpt, diagnostics); EnsurePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics); return details.GetOrAddInstrumentationPayloadRoot(analysisKind, payloadType); } private void EnsurePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics) { if (details.GetMethod(WellKnownMemberNames.StaticConstructorName) == null) { details.TryAddSynthesizedMethod(CreatePrivateImplementationDetailsStaticConstructor(details, syntaxOpt, diagnostics)); } } protected abstract Cci.IMethodDefinition CreatePrivateImplementationDetailsStaticConstructor(PrivateImplementationDetails details, TSyntaxNode syntaxOpt, DiagnosticBag diagnostics); #region Synthesized Members /// <summary> /// Captures the set of synthesized definitions that should be added to a type /// during emit process. /// </summary> private sealed class SynthesizedDefinitions { public ConcurrentQueue<Cci.INestedTypeDefinition> NestedTypes; public ConcurrentQueue<Cci.IMethodDefinition> Methods; public ConcurrentQueue<Cci.IPropertyDefinition> Properties; public ConcurrentQueue<Cci.IFieldDefinition> Fields; public ImmutableArray<ISymbolInternal> GetAllMembers() { var builder = ArrayBuilder<ISymbolInternal>.GetInstance(); if (Fields != null) { foreach (var field in Fields) { builder.Add(field.GetInternalSymbol()); } } if (Methods != null) { foreach (var method in Methods) { builder.Add(method.GetInternalSymbol()); } } if (Properties != null) { foreach (var property in Properties) { builder.Add(property.GetInternalSymbol()); } } if (NestedTypes != null) { foreach (var type in NestedTypes) { builder.Add(type.GetInternalSymbol()); } } return builder.ToImmutableAndFree(); } } private readonly ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions> _synthesizedTypeMembers = new ConcurrentDictionary<TNamedTypeSymbol, SynthesizedDefinitions>(ReferenceEqualityComparer.Instance); private ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>> _lazySynthesizedNamespaceMembers; internal abstract IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedNestedTypes(TNamedTypeSymbol container); /// <summary> /// Returns null if there are no compiler generated types. /// </summary> public IEnumerable<Cci.INestedTypeDefinition> GetSynthesizedTypes(TNamedTypeSymbol container) { IEnumerable<Cci.INestedTypeDefinition> declareTypes = GetSynthesizedNestedTypes(container); IEnumerable<Cci.INestedTypeDefinition> compileEmitTypes = null; if (_synthesizedTypeMembers.TryGetValue(container, out var defs)) { compileEmitTypes = defs.NestedTypes; } if (declareTypes == null) { return compileEmitTypes; } if (compileEmitTypes == null) { return declareTypes; } return declareTypes.Concat(compileEmitTypes); } private SynthesizedDefinitions GetOrAddSynthesizedDefinitions(TNamedTypeSymbol container) { Debug.Assert(container.IsDefinition); return _synthesizedTypeMembers.GetOrAdd(container, _ => new SynthesizedDefinitions()); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IMethodDefinition method) { Debug.Assert(method != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Methods == null) { Interlocked.CompareExchange(ref defs.Methods, new ConcurrentQueue<Cci.IMethodDefinition>(), null); } defs.Methods.Enqueue(method); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IPropertyDefinition property) { Debug.Assert(property != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Properties == null) { Interlocked.CompareExchange(ref defs.Properties, new ConcurrentQueue<Cci.IPropertyDefinition>(), null); } defs.Properties.Enqueue(property); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.IFieldDefinition field) { Debug.Assert(field != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.Fields == null) { Interlocked.CompareExchange(ref defs.Fields, new ConcurrentQueue<Cci.IFieldDefinition>(), null); } defs.Fields.Enqueue(field); } public void AddSynthesizedDefinition(TNamedTypeSymbol container, Cci.INestedTypeDefinition nestedType) { Debug.Assert(nestedType != null); SynthesizedDefinitions defs = GetOrAddSynthesizedDefinitions(container); if (defs.NestedTypes == null) { Interlocked.CompareExchange(ref defs.NestedTypes, new ConcurrentQueue<Cci.INestedTypeDefinition>(), null); } defs.NestedTypes.Enqueue(nestedType); } public void AddSynthesizedDefinition(INamespaceSymbolInternal container, INamespaceOrTypeSymbolInternal typeOrNamespace) { Debug.Assert(typeOrNamespace != null); if (_lazySynthesizedNamespaceMembers == null) { Interlocked.CompareExchange(ref _lazySynthesizedNamespaceMembers, new ConcurrentDictionary<INamespaceSymbolInternal, ConcurrentQueue<INamespaceOrTypeSymbolInternal>>(), null); } _lazySynthesizedNamespaceMembers.GetOrAdd(container, _ => new ConcurrentQueue<INamespaceOrTypeSymbolInternal>()).Enqueue(typeOrNamespace); } /// <summary> /// Returns null if there are no synthesized fields. /// </summary> public IEnumerable<Cci.IFieldDefinition> GetSynthesizedFields(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Fields : null; /// <summary> /// Returns null if there are no synthesized properties. /// </summary> public IEnumerable<Cci.IPropertyDefinition> GetSynthesizedProperties(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Properties : null; /// <summary> /// Returns null if there are no synthesized methods. /// </summary> public IEnumerable<Cci.IMethodDefinition> GetSynthesizedMethods(TNamedTypeSymbol container) => _synthesizedTypeMembers.TryGetValue(container, out var defs) ? defs.Methods : null; internal override ImmutableDictionary<ISymbolInternal, ImmutableArray<ISymbolInternal>> GetAllSynthesizedMembers() { var builder = ImmutableDictionary.CreateBuilder<ISymbolInternal, ImmutableArray<ISymbolInternal>>(); foreach (var entry in _synthesizedTypeMembers) { builder.Add(entry.Key, entry.Value.GetAllMembers()); } var namespaceMembers = _lazySynthesizedNamespaceMembers; if (namespaceMembers != null) { foreach (var entry in namespaceMembers) { builder.Add(entry.Key, entry.Value.ToImmutableArray<ISymbolInternal>()); } } return builder.ToImmutable(); } #endregion #region Token Mapping Cci.IFieldReference ITokenDeferral.GetFieldForData(ImmutableArray<byte> data, SyntaxNode syntaxNode, DiagnosticBag diagnostics) { Debug.Assert(this.SupportsPrivateImplClass); var privateImpl = this.GetPrivateImplClass((TSyntaxNode)syntaxNode, diagnostics); // map a field to the block (that makes it addressable via a token) return privateImpl.CreateDataField(data); } public abstract Cci.IMethodReference GetInitArrayHelper(); public ArrayMethods ArrayMethods { get { ArrayMethods result = _lazyArrayMethods; if (result == null) { result = new ArrayMethods(); if (Interlocked.CompareExchange(ref _lazyArrayMethods, result, null) != null) { result = _lazyArrayMethods; } } return result; } } #endregion #region Private Implementation Details Type internal PrivateImplementationDetails GetPrivateImplClass(TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var result = _privateImplementationDetails; if ((result == null) && this.SupportsPrivateImplClass) { result = new PrivateImplementationDetails( this, this.SourceModule.Name, Compilation.GetSubmissionSlotIndex(), this.GetSpecialType(SpecialType.System_Object, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_ValueType, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Byte, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int16, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int32, syntaxNodeOpt, diagnostics), this.GetSpecialType(SpecialType.System_Int64, syntaxNodeOpt, diagnostics), SynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); if (Interlocked.CompareExchange(ref _privateImplementationDetails, result, null) != null) { result = _privateImplementationDetails; } } return result; } internal PrivateImplementationDetails PrivateImplClass { get { return _privateImplementationDetails; } } internal override bool SupportsPrivateImplClass { get { return true; } } #endregion public sealed override Cci.ITypeReference GetPlatformType(Cci.PlatformType platformType, EmitContext context) { Debug.Assert((object)this == context.Module); switch (platformType) { case Cci.PlatformType.SystemType: throw ExceptionUtilities.UnexpectedValue(platformType); default: return GetSpecialType((SpecialType)platformType, (TSyntaxNode)context.SyntaxNode, context.Diagnostics); } } } }
1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/PEWriter/MetadataWriter.PortablePdb.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.Cci { internal partial class MetadataWriter { /// <summary> /// Import scopes are associated with binders (in C#) and thus multiple instances might be created for a single set of imports. /// We consider scopes with the same parent and the same imports the same. /// Internal for testing. /// </summary> internal sealed class ImportScopeEqualityComparer : IEqualityComparer<IImportScope> { public static readonly ImportScopeEqualityComparer Instance = new ImportScopeEqualityComparer(); public bool Equals(IImportScope x, IImportScope y) { return (object)x == y || x != null && y != null && Equals(x.Parent, y.Parent) && x.GetUsedNamespaces().SequenceEqual(y.GetUsedNamespaces()); } public int GetHashCode(IImportScope obj) { return Hash.Combine(Hash.CombineValues(obj.GetUsedNamespaces()), obj.Parent != null ? GetHashCode(obj.Parent) : 0); } } private readonly Dictionary<DebugSourceDocument, DocumentHandle> _documentIndex = new Dictionary<DebugSourceDocument, DocumentHandle>(); private readonly Dictionary<IImportScope, ImportScopeHandle> _scopeIndex = new Dictionary<IImportScope, ImportScopeHandle>(ImportScopeEqualityComparer.Instance); private void SerializeMethodDebugInfo(IMethodBody bodyOpt, int methodRid, int aggregateMethodRid, StandaloneSignatureHandle localSignatureHandleOpt, ref LocalVariableHandle lastLocalVariableHandle, ref LocalConstantHandle lastLocalConstantHandle) { if (bodyOpt == null) { _debugMetadataOpt.AddMethodDebugInformation(document: default, sequencePoints: default); return; } bool isKickoffMethod = bodyOpt.StateMachineTypeName != null; bool emitAllDebugInfo = isKickoffMethod || !bodyOpt.SequencePoints.IsEmpty; var methodHandle = MetadataTokens.MethodDefinitionHandle(methodRid); // documents & sequence points: BlobHandle sequencePointsBlob = SerializeSequencePoints(localSignatureHandleOpt, bodyOpt.SequencePoints, _documentIndex, out var singleDocumentHandle); _debugMetadataOpt.AddMethodDebugInformation(document: singleDocumentHandle, sequencePoints: sequencePointsBlob); if (emitAllDebugInfo) { var bodyImportScope = bodyOpt.ImportScope; var importScopeHandle = (bodyImportScope != null) ? GetImportScopeIndex(bodyImportScope, _scopeIndex) : default; // Unlike native PDB we don't emit an empty root scope. // scopes are already ordered by StartOffset ascending then by EndOffset descending (the longest scope first). if (bodyOpt.LocalScopes.Length == 0) { // TODO: the compiler should produce a scope for each debuggable method rather then adding one here _debugMetadataOpt.AddLocalScope( method: methodHandle, importScope: importScopeHandle, variableList: NextHandle(lastLocalVariableHandle), constantList: NextHandle(lastLocalConstantHandle), startOffset: 0, length: bodyOpt.IL.Length); } else { foreach (LocalScope scope in bodyOpt.LocalScopes) { _debugMetadataOpt.AddLocalScope( method: methodHandle, importScope: importScopeHandle, variableList: NextHandle(lastLocalVariableHandle), constantList: NextHandle(lastLocalConstantHandle), startOffset: scope.StartOffset, length: scope.Length); foreach (ILocalDefinition local in scope.Variables) { Debug.Assert(local.SlotIndex >= 0); lastLocalVariableHandle = _debugMetadataOpt.AddLocalVariable( attributes: local.PdbAttributes, index: local.SlotIndex, name: _debugMetadataOpt.GetOrAddString(local.Name)); SerializeLocalInfo(local, lastLocalVariableHandle); } foreach (ILocalDefinition constant in scope.Constants) { var mdConstant = constant.CompileTimeValue; Debug.Assert(mdConstant != null); lastLocalConstantHandle = _debugMetadataOpt.AddLocalConstant( name: _debugMetadataOpt.GetOrAddString(constant.Name), signature: SerializeLocalConstantSignature(constant)); SerializeLocalInfo(constant, lastLocalConstantHandle); } } } var moveNextBodyInfo = bodyOpt.MoveNextBodyInfo; if (moveNextBodyInfo != null) { _debugMetadataOpt.AddStateMachineMethod( moveNextMethod: methodHandle, kickoffMethod: GetMethodDefinitionHandle(moveNextBodyInfo.KickoffMethod)); if (moveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncInfo) { SerializeAsyncMethodSteppingInfo(asyncInfo, methodHandle, aggregateMethodRid); } } SerializeStateMachineLocalScopes(bodyOpt, methodHandle); } // Emit EnC info for all methods even if they do not have sequence points. // The information facilitates reusing lambdas and closures. The reuse is important for runtimes that can't add new members (e.g. Mono). // EnC delta doesn't need this information - we use information recorded by previous generation emit. if (Context.Module.CommonCompilation.Options.EnableEditAndContinue && IsFullMetadata) { SerializeEncMethodDebugInformation(bodyOpt, methodHandle); } } private static LocalVariableHandle NextHandle(LocalVariableHandle handle) => MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(handle) + 1); private static LocalConstantHandle NextHandle(LocalConstantHandle handle) => MetadataTokens.LocalConstantHandle(MetadataTokens.GetRowNumber(handle) + 1); private BlobHandle SerializeLocalConstantSignature(ILocalDefinition localConstant) { var builder = new BlobBuilder(); // TODO: BlobEncoder.LocalConstantSignature // CustomMod* var encoder = new CustomModifiersEncoder(builder); SerializeCustomModifiers(encoder, localConstant.CustomModifiers); var type = localConstant.Type; var typeCode = type.TypeCode; object value = localConstant.CompileTimeValue.Value; // PrimitiveConstant or EnumConstant if (value is decimal) { builder.WriteByte((byte)SignatureTypeKind.ValueType); builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); builder.WriteDecimal((decimal)value); } else if (value is DateTime) { builder.WriteByte((byte)SignatureTypeKind.ValueType); builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); builder.WriteDateTime((DateTime)value); } else if (typeCode == PrimitiveTypeCode.String) { builder.WriteByte((byte)ConstantTypeCode.String); if (value == null) { builder.WriteByte(0xff); } else { builder.WriteUTF16((string)value); } } else if (value != null) { // TypeCode builder.WriteByte((byte)GetConstantTypeCode(value)); // Value builder.WriteConstant(value); // EnumType if (type.IsEnum) { builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); } } else if (this.module.IsPlatformType(type, PlatformType.SystemObject)) { builder.WriteByte((byte)SignatureTypeCode.Object); } else { builder.WriteByte((byte)(type.IsValueType ? SignatureTypeKind.ValueType : SignatureTypeKind.Class)); builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); } return _debugMetadataOpt.GetOrAddBlob(builder); } private static SignatureTypeCode GetConstantTypeCode(object value) { if (value == null) { // The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a zero. return (SignatureTypeCode)SignatureTypeKind.Class; } Debug.Assert(!value.GetType().GetTypeInfo().IsEnum); // Perf: Note that JIT optimizes each expression val.GetType() == typeof(T) to a single register comparison. // Also the checks are sorted by commonality of the checked types. if (value.GetType() == typeof(int)) { return SignatureTypeCode.Int32; } if (value.GetType() == typeof(string)) { return SignatureTypeCode.String; } if (value.GetType() == typeof(bool)) { return SignatureTypeCode.Boolean; } if (value.GetType() == typeof(char)) { return SignatureTypeCode.Char; } if (value.GetType() == typeof(byte)) { return SignatureTypeCode.Byte; } if (value.GetType() == typeof(long)) { return SignatureTypeCode.Int64; } if (value.GetType() == typeof(double)) { return SignatureTypeCode.Double; } if (value.GetType() == typeof(short)) { return SignatureTypeCode.Int16; } if (value.GetType() == typeof(ushort)) { return SignatureTypeCode.UInt16; } if (value.GetType() == typeof(uint)) { return SignatureTypeCode.UInt32; } if (value.GetType() == typeof(sbyte)) { return SignatureTypeCode.SByte; } if (value.GetType() == typeof(ulong)) { return SignatureTypeCode.UInt64; } if (value.GetType() == typeof(float)) { return SignatureTypeCode.Single; } throw ExceptionUtilities.Unreachable; } #region ImportScope private static readonly ImportScopeHandle ModuleImportScopeHandle = MetadataTokens.ImportScopeHandle(1); private void SerializeImport(BlobBuilder writer, AssemblyReferenceAlias alias) { // <import> ::= AliasAssemblyReference <alias> <target-assembly> writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyReference); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(alias.Name))); writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetOrAddAssemblyReferenceHandle(alias.Assembly))); } private void SerializeImport(BlobBuilder writer, UsedNamespaceOrType import) { if (import.TargetXmlNamespaceOpt != null) { Debug.Assert(import.TargetNamespaceOpt == null); Debug.Assert(import.TargetAssemblyOpt == null); Debug.Assert(import.TargetTypeOpt == null); // <import> ::= ImportXmlNamespace <alias> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.ImportXmlNamespace); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.TargetXmlNamespaceOpt))); } else if (import.TargetTypeOpt != null) { Debug.Assert(import.TargetNamespaceOpt == null); Debug.Assert(import.TargetAssemblyOpt == null); if (import.AliasOpt != null) { // <import> ::= AliasType <alias> <target-type> writer.WriteByte((byte)ImportDefinitionKind.AliasType); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } else { // <import> ::= ImportType <target-type> writer.WriteByte((byte)ImportDefinitionKind.ImportType); } writer.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(import.TargetTypeOpt))); // TODO: index in release build } else if (import.TargetNamespaceOpt != null) { if (import.TargetAssemblyOpt != null) { if (import.AliasOpt != null) { // <import> ::= AliasAssemblyNamespace <alias> <target-assembly> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyNamespace); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } else { // <import> ::= ImportAssemblyNamespace <target-assembly> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyNamespace); } writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetAssemblyReferenceHandle(import.TargetAssemblyOpt))); } else { if (import.AliasOpt != null) { // <import> ::= AliasNamespace <alias> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.AliasNamespace); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } else { // <import> ::= ImportNamespace <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.ImportNamespace); } } // TODO: cache? string namespaceName = TypeNameSerializer.BuildQualifiedNamespaceName(import.TargetNamespaceOpt); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(namespaceName))); } else { // <import> ::= ImportReferenceAlias <alias> Debug.Assert(import.AliasOpt != null); Debug.Assert(import.TargetAssemblyOpt == null); writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyReferenceAlias); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } } private void DefineModuleImportScope() { // module-level import scope: var writer = new BlobBuilder(); SerializeModuleDefaultNamespace(); foreach (AssemblyReferenceAlias alias in module.GetAssemblyReferenceAliases(Context)) { SerializeImport(writer, alias); } foreach (UsedNamespaceOrType import in module.GetImports()) { SerializeImport(writer, import); } var rid = _debugMetadataOpt.AddImportScope( parentScope: default(ImportScopeHandle), imports: _debugMetadataOpt.GetOrAddBlob(writer)); Debug.Assert(rid == ModuleImportScopeHandle); } private ImportScopeHandle GetImportScopeIndex(IImportScope scope, Dictionary<IImportScope, ImportScopeHandle> scopeIndex) { ImportScopeHandle scopeHandle; if (scopeIndex.TryGetValue(scope, out scopeHandle)) { // scope is already indexed: return scopeHandle; } var parent = scope.Parent; var parentScopeHandle = (parent != null) ? GetImportScopeIndex(scope.Parent, scopeIndex) : ModuleImportScopeHandle; var result = _debugMetadataOpt.AddImportScope( parentScope: parentScopeHandle, imports: SerializeImportsBlob(scope)); scopeIndex.Add(scope, result); return result; } private BlobHandle SerializeImportsBlob(IImportScope scope) { var writer = new BlobBuilder(); foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces()) { SerializeImport(writer, import); } return _debugMetadataOpt.GetOrAddBlob(writer); } private void SerializeModuleDefaultNamespace() { // C#: DefaultNamespace is null. // VB: DefaultNamespace is non-null. if (module.DefaultNamespace == null) { return; } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DefaultNamespace), value: _debugMetadataOpt.GetOrAddBlobUTF8(module.DefaultNamespace)); } #endregion #region Locals private void SerializeLocalInfo(ILocalDefinition local, EntityHandle parent) { var dynamicFlags = local.DynamicTransformFlags; if (!dynamicFlags.IsEmpty) { var value = SerializeBitVector(dynamicFlags); _debugMetadataOpt.AddCustomDebugInformation( parent: parent, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DynamicLocalVariables), value: _debugMetadataOpt.GetOrAddBlob(value)); } var tupleElementNames = local.TupleElementNames; if (!tupleElementNames.IsEmpty) { var builder = new BlobBuilder(); SerializeTupleElementNames(builder, tupleElementNames); _debugMetadataOpt.AddCustomDebugInformation( parent: parent, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.TupleElementNames), value: _debugMetadataOpt.GetOrAddBlob(builder)); } } private static ImmutableArray<byte> SerializeBitVector(ImmutableArray<bool> vector) { var builder = ArrayBuilder<byte>.GetInstance(); int b = 0; int shift = 0; for (int i = 0; i < vector.Length; i++) { if (vector[i]) { b |= 1 << shift; } if (shift == 7) { builder.Add((byte)b); b = 0; shift = 0; } else { shift++; } } if (b != 0) { builder.Add((byte)b); } else { // trim trailing zeros: int lastNonZero = builder.Count - 1; while (builder[lastNonZero] == 0) { lastNonZero--; } builder.Clip(lastNonZero + 1); } return builder.ToImmutableAndFree(); } private static void SerializeTupleElementNames(BlobBuilder builder, ImmutableArray<string> names) { foreach (var name in names) { WriteUtf8String(builder, name ?? string.Empty); } } /// <summary> /// Write string as UTF8 with null terminator. /// </summary> private static void WriteUtf8String(BlobBuilder builder, string str) { builder.WriteUTF8(str); builder.WriteByte(0); } #endregion #region State Machines private void SerializeAsyncMethodSteppingInfo(AsyncMoveNextBodyDebugInfo asyncInfo, MethodDefinitionHandle moveNextMethod, int aggregateMethodDefRid) { Debug.Assert(asyncInfo.ResumeOffsets.Length == asyncInfo.YieldOffsets.Length); Debug.Assert(asyncInfo.CatchHandlerOffset >= -1); var writer = new BlobBuilder(); writer.WriteUInt32((uint)((long)asyncInfo.CatchHandlerOffset + 1)); for (int i = 0; i < asyncInfo.ResumeOffsets.Length; i++) { writer.WriteUInt32((uint)asyncInfo.YieldOffsets[i]); writer.WriteUInt32((uint)asyncInfo.ResumeOffsets[i]); writer.WriteCompressedInteger(aggregateMethodDefRid); } _debugMetadataOpt.AddCustomDebugInformation( parent: moveNextMethod, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.AsyncMethodSteppingInformationBlob), value: _debugMetadataOpt.GetOrAddBlob(writer)); } private void SerializeStateMachineLocalScopes(IMethodBody methodBody, MethodDefinitionHandle method) { var scopes = methodBody.StateMachineHoistedLocalScopes; if (scopes.IsDefaultOrEmpty) { return; } var writer = new BlobBuilder(); foreach (var scope in scopes) { writer.WriteUInt32((uint)scope.StartOffset); writer.WriteUInt32((uint)scope.Length); } _debugMetadataOpt.AddCustomDebugInformation( parent: method, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes), value: _debugMetadataOpt.GetOrAddBlob(writer)); } #endregion #region Sequence Points private BlobHandle SerializeSequencePoints( StandaloneSignatureHandle localSignatureHandleOpt, ImmutableArray<SequencePoint> sequencePoints, Dictionary<DebugSourceDocument, DocumentHandle> documentIndex, out DocumentHandle singleDocumentHandle) { if (sequencePoints.Length == 0) { singleDocumentHandle = default(DocumentHandle); return default(BlobHandle); } var writer = new BlobBuilder(); int previousNonHiddenStartLine = -1; int previousNonHiddenStartColumn = -1; // header: writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(localSignatureHandleOpt)); var previousDocument = TryGetSingleDocument(sequencePoints); singleDocumentHandle = (previousDocument != null) ? GetOrAddDocument(previousDocument, documentIndex) : default(DocumentHandle); for (int i = 0; i < sequencePoints.Length; i++) { var currentDocument = sequencePoints[i].Document; if (previousDocument != currentDocument) { var documentHandle = GetOrAddDocument(currentDocument, documentIndex); // optional document in header or document record: if (previousDocument != null) { writer.WriteCompressedInteger(0); } writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(documentHandle)); previousDocument = currentDocument; } // delta IL offset: if (i > 0) { writer.WriteCompressedInteger(sequencePoints[i].Offset - sequencePoints[i - 1].Offset); } else { writer.WriteCompressedInteger(sequencePoints[i].Offset); } if (sequencePoints[i].IsHidden) { writer.WriteInt16(0); continue; } // Delta Lines & Columns: SerializeDeltaLinesAndColumns(writer, sequencePoints[i]); // delta Start Lines & Columns: if (previousNonHiddenStartLine < 0) { Debug.Assert(previousNonHiddenStartColumn < 0); writer.WriteCompressedInteger(sequencePoints[i].StartLine); writer.WriteCompressedInteger(sequencePoints[i].StartColumn); } else { writer.WriteCompressedSignedInteger(sequencePoints[i].StartLine - previousNonHiddenStartLine); writer.WriteCompressedSignedInteger(sequencePoints[i].StartColumn - previousNonHiddenStartColumn); } previousNonHiddenStartLine = sequencePoints[i].StartLine; previousNonHiddenStartColumn = sequencePoints[i].StartColumn; } return _debugMetadataOpt.GetOrAddBlob(writer); } private static DebugSourceDocument TryGetSingleDocument(ImmutableArray<SequencePoint> sequencePoints) { DebugSourceDocument singleDocument = sequencePoints[0].Document; for (int i = 1; i < sequencePoints.Length; i++) { if (sequencePoints[i].Document != singleDocument) { return null; } } return singleDocument; } private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SequencePoint sequencePoint) { int deltaLines = sequencePoint.EndLine - sequencePoint.StartLine; int deltaColumns = sequencePoint.EndColumn - sequencePoint.StartColumn; // only hidden sequence points have zero width Debug.Assert(deltaLines != 0 || deltaColumns != 0 || sequencePoint.IsHidden); writer.WriteCompressedInteger(deltaLines); if (deltaLines == 0) { writer.WriteCompressedInteger(deltaColumns); } else { writer.WriteCompressedSignedInteger(deltaColumns); } } #endregion #region Documents private DocumentHandle GetOrAddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index) { if (index.TryGetValue(document, out var documentHandle)) { return documentHandle; } return AddDocument(document, index); } private DocumentHandle AddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index) { DocumentHandle documentHandle; DebugSourceInfo info = document.GetSourceInfo(); var name = document.Location; if (_usingNonSourceDocumentNameEnumerator) { var result = _nonSourceDocumentNameEnumerator.MoveNext(); Debug.Assert(result); name = _nonSourceDocumentNameEnumerator.Current; } documentHandle = _debugMetadataOpt.AddDocument( name: _debugMetadataOpt.GetOrAddDocumentName(name), hashAlgorithm: info.Checksum.IsDefault ? default(GuidHandle) : _debugMetadataOpt.GetOrAddGuid(info.ChecksumAlgorithmId), hash: info.Checksum.IsDefault ? default(BlobHandle) : _debugMetadataOpt.GetOrAddBlob(info.Checksum), language: _debugMetadataOpt.GetOrAddGuid(document.Language)); index.Add(document, documentHandle); if (info.EmbeddedTextBlob != null) { _debugMetadataOpt.AddCustomDebugInformation( parent: documentHandle, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EmbeddedSource), value: _debugMetadataOpt.GetOrAddBlob(info.EmbeddedTextBlob)); } return documentHandle; } /// <summary> /// Add document entries for all debug documents that do not yet have an entry. /// </summary> /// <remarks> /// This is done after serializing method debug info to ensure that we embed all requested /// text even if there are no corresponding sequence points. /// </remarks> public void AddRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents) { foreach (var kvp in documents .Where(kvp => !_documentIndex.ContainsKey(kvp.Value)) .OrderBy(kvp => kvp.Key)) { AddDocument(kvp.Value, _documentIndex); } } #endregion #region Edit and Continue private void SerializeEncMethodDebugInformation(IMethodBody methodBody, MethodDefinitionHandle method) { var encInfo = GetEncMethodDebugInfo(methodBody); if (!encInfo.LocalSlots.IsDefaultOrEmpty) { var writer = new BlobBuilder(); encInfo.SerializeLocalSlots(writer); _debugMetadataOpt.AddCustomDebugInformation( parent: method, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLocalSlotMap), value: _debugMetadataOpt.GetOrAddBlob(writer)); } if (!encInfo.Lambdas.IsDefaultOrEmpty) { var writer = new BlobBuilder(); encInfo.SerializeLambdaMap(writer); _debugMetadataOpt.AddCustomDebugInformation( parent: method, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap), value: _debugMetadataOpt.GetOrAddBlob(writer)); } } #endregion private void EmbedSourceLink(Stream stream) { byte[] bytes; try { bytes = stream.ReadAllBytes(); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new SymUnmanagedWriterException(e.Message, e); } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.SourceLink), value: _debugMetadataOpt.GetOrAddBlob(bytes)); } ///<summary>The version of the compilation options schema to be written to the PDB.</summary> private const int CompilationOptionsSchemaVersion = 2; /// <summary> /// Capture the set of compilation options to allow a compilation /// to be reconstructed from the pdb /// </summary> private void EmbedCompilationOptions(CommonPEModuleBuilder module) { var builder = new BlobBuilder(); if (this.Context.RebuildData is { } rebuildData) { var reader = rebuildData.OptionsBlobReader; builder.WriteBytes(reader.ReadBytes(reader.RemainingBytes)); } else { var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; WriteValue(CompilationOptionNames.CompilationOptionsVersion, CompilationOptionsSchemaVersion.ToString()); WriteValue(CompilationOptionNames.CompilerVersion, compilerVersion); WriteValue(CompilationOptionNames.Language, module.CommonCompilation.Options.Language); WriteValue(CompilationOptionNames.SourceFileCount, module.CommonCompilation.SyntaxTrees.Count().ToString()); WriteValue(CompilationOptionNames.OutputKind, module.OutputKind.ToString()); if (module.EmitOptions.FallbackSourceFileEncoding != null) { WriteValue(CompilationOptionNames.FallbackEncoding, module.EmitOptions.FallbackSourceFileEncoding.WebName); } if (module.EmitOptions.DefaultSourceFileEncoding != null) { WriteValue(CompilationOptionNames.DefaultEncoding, module.EmitOptions.DefaultSourceFileEncoding.WebName); } int portabilityPolicy = 0; if (module.CommonCompilation.Options.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer) { portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0; portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0; } if (portabilityPolicy != 0) { WriteValue(CompilationOptionNames.PortabilityPolicy, portabilityPolicy.ToString()); } var optimizationLevel = module.CommonCompilation.Options.OptimizationLevel; var debugPlusMode = module.CommonCompilation.Options.DebugPlusMode; if ((optimizationLevel, debugPlusMode) != OptimizationLevelFacts.DefaultValues) { WriteValue(CompilationOptionNames.Optimization, optimizationLevel.ToPdbSerializedString(debugPlusMode)); } var platform = module.CommonCompilation.Options.Platform; WriteValue(CompilationOptionNames.Platform, platform.ToString()); var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; WriteValue(CompilationOptionNames.RuntimeVersion, runtimeVersion); module.CommonCompilation.SerializePdbEmbeddedCompilationOptions(builder); } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationOptions), value: _debugMetadataOpt.GetOrAddBlob(builder)); void WriteValue(string key, string value) { builder.WriteUTF8(key); builder.WriteByte(0); builder.WriteUTF8(value); builder.WriteByte(0); } } /// <summary> /// Writes information about metadata references to the pdb so the same /// reference can be found on sourcelink to create the compilation again /// </summary> private void EmbedMetadataReferenceInformation(CommonPEModuleBuilder module) { var builder = new BlobBuilder(); // Order of information // File name (null terminated string): A.exe // Extern Alias (null terminated string): a1,a2,a3 // MetadataImageKind (byte) // EmbedInteropTypes (boolean) // COFF header Timestamp field (4 byte int) // COFF header SizeOfImage field (4 byte int) // MVID (Guid, 24 bytes) var referenceManager = module.CommonCompilation.GetBoundReferenceManager(); foreach (var pair in referenceManager.GetReferencedAssemblyAliases()) { if (referenceManager.GetMetadataReference(pair.AssemblySymbol) is PortableExecutableReference { FilePath: { } } portableReference) { var fileName = PathUtilities.GetFileName(portableReference.FilePath); var peReader = pair.AssemblySymbol.GetISymbol() is IAssemblySymbol assemblySymbol ? assemblySymbol.GetMetadata().GetAssembly().ManifestModule.PEReaderOpt : null; // Don't write before checking that we can get a peReader for the metadata reference if (peReader is null) continue; // Write file name first builder.WriteUTF8(fileName); // Make sure to add null terminator builder.WriteByte(0); // Extern alias if (pair.Aliases.Length > 0) builder.WriteUTF8(string.Join(",", pair.Aliases.OrderBy(StringComparer.Ordinal))); // Always null terminate the extern alias list builder.WriteByte(0); byte kindAndEmbedInteropTypes = (byte)(portableReference.Properties.EmbedInteropTypes ? 0b10 : 0b0); kindAndEmbedInteropTypes |= portableReference.Properties.Kind switch { MetadataImageKind.Assembly => 1, MetadataImageKind.Module => 0, _ => throw ExceptionUtilities.UnexpectedValue(portableReference.Properties.Kind) }; builder.WriteByte(kindAndEmbedInteropTypes); builder.WriteInt32(peReader.PEHeaders.CoffHeader.TimeDateStamp); builder.WriteInt32(peReader.PEHeaders.PEHeader.SizeOfImage); var metadataReader = peReader.GetMetadataReader(); var moduleDefinition = metadataReader.GetModuleDefinition(); builder.WriteGuid(metadataReader.GetGuid(moduleDefinition.Mvid)); } } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationMetadataReferences), value: _debugMetadataOpt.GetOrAddBlob(builder)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.Cci { internal partial class MetadataWriter { /// <summary> /// Import scopes are associated with binders (in C#) and thus multiple instances might be created for a single set of imports. /// We consider scopes with the same parent and the same imports the same. /// Internal for testing. /// </summary> internal sealed class ImportScopeEqualityComparer : IEqualityComparer<IImportScope> { public static readonly ImportScopeEqualityComparer Instance = new ImportScopeEqualityComparer(); public bool Equals(IImportScope x, IImportScope y) { return (object)x == y || x != null && y != null && Equals(x.Parent, y.Parent) && x.GetUsedNamespaces().SequenceEqual(y.GetUsedNamespaces()); } public int GetHashCode(IImportScope obj) { return Hash.Combine(Hash.CombineValues(obj.GetUsedNamespaces()), obj.Parent != null ? GetHashCode(obj.Parent) : 0); } } private readonly Dictionary<DebugSourceDocument, DocumentHandle> _documentIndex = new Dictionary<DebugSourceDocument, DocumentHandle>(); private readonly Dictionary<IImportScope, ImportScopeHandle> _scopeIndex = new Dictionary<IImportScope, ImportScopeHandle>(ImportScopeEqualityComparer.Instance); private void SerializeMethodDebugInfo(IMethodBody bodyOpt, int methodRid, int aggregateMethodRid, StandaloneSignatureHandle localSignatureHandleOpt, ref LocalVariableHandle lastLocalVariableHandle, ref LocalConstantHandle lastLocalConstantHandle) { if (bodyOpt == null) { _debugMetadataOpt.AddMethodDebugInformation(document: default, sequencePoints: default); return; } bool isKickoffMethod = bodyOpt.StateMachineTypeName != null; bool emitAllDebugInfo = isKickoffMethod || !bodyOpt.SequencePoints.IsEmpty; var methodHandle = MetadataTokens.MethodDefinitionHandle(methodRid); // documents & sequence points: BlobHandle sequencePointsBlob = SerializeSequencePoints(localSignatureHandleOpt, bodyOpt.SequencePoints, _documentIndex, out var singleDocumentHandle); _debugMetadataOpt.AddMethodDebugInformation(document: singleDocumentHandle, sequencePoints: sequencePointsBlob); if (emitAllDebugInfo) { var bodyImportScope = bodyOpt.ImportScope; var importScopeHandle = (bodyImportScope != null) ? GetImportScopeIndex(bodyImportScope, _scopeIndex) : default; // Unlike native PDB we don't emit an empty root scope. // scopes are already ordered by StartOffset ascending then by EndOffset descending (the longest scope first). if (bodyOpt.LocalScopes.Length == 0) { // TODO: the compiler should produce a scope for each debuggable method rather then adding one here _debugMetadataOpt.AddLocalScope( method: methodHandle, importScope: importScopeHandle, variableList: NextHandle(lastLocalVariableHandle), constantList: NextHandle(lastLocalConstantHandle), startOffset: 0, length: bodyOpt.IL.Length); } else { foreach (LocalScope scope in bodyOpt.LocalScopes) { _debugMetadataOpt.AddLocalScope( method: methodHandle, importScope: importScopeHandle, variableList: NextHandle(lastLocalVariableHandle), constantList: NextHandle(lastLocalConstantHandle), startOffset: scope.StartOffset, length: scope.Length); foreach (ILocalDefinition local in scope.Variables) { Debug.Assert(local.SlotIndex >= 0); lastLocalVariableHandle = _debugMetadataOpt.AddLocalVariable( attributes: local.PdbAttributes, index: local.SlotIndex, name: _debugMetadataOpt.GetOrAddString(local.Name)); SerializeLocalInfo(local, lastLocalVariableHandle); } foreach (ILocalDefinition constant in scope.Constants) { var mdConstant = constant.CompileTimeValue; Debug.Assert(mdConstant != null); lastLocalConstantHandle = _debugMetadataOpt.AddLocalConstant( name: _debugMetadataOpt.GetOrAddString(constant.Name), signature: SerializeLocalConstantSignature(constant)); SerializeLocalInfo(constant, lastLocalConstantHandle); } } } var moveNextBodyInfo = bodyOpt.MoveNextBodyInfo; if (moveNextBodyInfo != null) { _debugMetadataOpt.AddStateMachineMethod( moveNextMethod: methodHandle, kickoffMethod: GetMethodDefinitionHandle(moveNextBodyInfo.KickoffMethod)); if (moveNextBodyInfo is AsyncMoveNextBodyDebugInfo asyncInfo) { SerializeAsyncMethodSteppingInfo(asyncInfo, methodHandle, aggregateMethodRid); } } SerializeStateMachineLocalScopes(bodyOpt, methodHandle); } // Emit EnC info for all methods even if they do not have sequence points. // The information facilitates reusing lambdas and closures. The reuse is important for runtimes that can't add new members (e.g. Mono). // EnC delta doesn't need this information - we use information recorded by previous generation emit. if (Context.Module.CommonCompilation.Options.EnableEditAndContinue && IsFullMetadata) { SerializeEncMethodDebugInformation(bodyOpt, methodHandle); } } private static LocalVariableHandle NextHandle(LocalVariableHandle handle) => MetadataTokens.LocalVariableHandle(MetadataTokens.GetRowNumber(handle) + 1); private static LocalConstantHandle NextHandle(LocalConstantHandle handle) => MetadataTokens.LocalConstantHandle(MetadataTokens.GetRowNumber(handle) + 1); private BlobHandle SerializeLocalConstantSignature(ILocalDefinition localConstant) { var builder = new BlobBuilder(); // TODO: BlobEncoder.LocalConstantSignature // CustomMod* var encoder = new CustomModifiersEncoder(builder); SerializeCustomModifiers(encoder, localConstant.CustomModifiers); var type = localConstant.Type; var typeCode = type.TypeCode; object value = localConstant.CompileTimeValue.Value; // PrimitiveConstant or EnumConstant if (value is decimal) { builder.WriteByte((byte)SignatureTypeKind.ValueType); builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); builder.WriteDecimal((decimal)value); } else if (value is DateTime) { builder.WriteByte((byte)SignatureTypeKind.ValueType); builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); builder.WriteDateTime((DateTime)value); } else if (typeCode == PrimitiveTypeCode.String) { builder.WriteByte((byte)ConstantTypeCode.String); if (value == null) { builder.WriteByte(0xff); } else { builder.WriteUTF16((string)value); } } else if (value != null) { // TypeCode builder.WriteByte((byte)GetConstantTypeCode(value)); // Value builder.WriteConstant(value); // EnumType if (type.IsEnum) { builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); } } else if (this.module.IsPlatformType(type, PlatformType.SystemObject)) { builder.WriteByte((byte)SignatureTypeCode.Object); } else { builder.WriteByte((byte)(type.IsValueType ? SignatureTypeKind.ValueType : SignatureTypeKind.Class)); builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(type))); } return _debugMetadataOpt.GetOrAddBlob(builder); } private static SignatureTypeCode GetConstantTypeCode(object value) { if (value == null) { // The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a zero. return (SignatureTypeCode)SignatureTypeKind.Class; } Debug.Assert(!value.GetType().GetTypeInfo().IsEnum); // Perf: Note that JIT optimizes each expression val.GetType() == typeof(T) to a single register comparison. // Also the checks are sorted by commonality of the checked types. if (value.GetType() == typeof(int)) { return SignatureTypeCode.Int32; } if (value.GetType() == typeof(string)) { return SignatureTypeCode.String; } if (value.GetType() == typeof(bool)) { return SignatureTypeCode.Boolean; } if (value.GetType() == typeof(char)) { return SignatureTypeCode.Char; } if (value.GetType() == typeof(byte)) { return SignatureTypeCode.Byte; } if (value.GetType() == typeof(long)) { return SignatureTypeCode.Int64; } if (value.GetType() == typeof(double)) { return SignatureTypeCode.Double; } if (value.GetType() == typeof(short)) { return SignatureTypeCode.Int16; } if (value.GetType() == typeof(ushort)) { return SignatureTypeCode.UInt16; } if (value.GetType() == typeof(uint)) { return SignatureTypeCode.UInt32; } if (value.GetType() == typeof(sbyte)) { return SignatureTypeCode.SByte; } if (value.GetType() == typeof(ulong)) { return SignatureTypeCode.UInt64; } if (value.GetType() == typeof(float)) { return SignatureTypeCode.Single; } throw ExceptionUtilities.Unreachable; } #region ImportScope private static readonly ImportScopeHandle ModuleImportScopeHandle = MetadataTokens.ImportScopeHandle(1); private void SerializeImport(BlobBuilder writer, AssemblyReferenceAlias alias) { // <import> ::= AliasAssemblyReference <alias> <target-assembly> writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyReference); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(alias.Name))); writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetOrAddAssemblyReferenceHandle(alias.Assembly))); } private void SerializeImport(BlobBuilder writer, UsedNamespaceOrType import) { if (import.TargetXmlNamespaceOpt != null) { Debug.Assert(import.TargetNamespaceOpt == null); Debug.Assert(import.TargetAssemblyOpt == null); Debug.Assert(import.TargetTypeOpt == null); // <import> ::= ImportXmlNamespace <alias> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.ImportXmlNamespace); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.TargetXmlNamespaceOpt))); } else if (import.TargetTypeOpt != null) { Debug.Assert(import.TargetNamespaceOpt == null); Debug.Assert(import.TargetAssemblyOpt == null); if (import.AliasOpt != null) { // <import> ::= AliasType <alias> <target-type> writer.WriteByte((byte)ImportDefinitionKind.AliasType); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } else { // <import> ::= ImportType <target-type> writer.WriteByte((byte)ImportDefinitionKind.ImportType); } writer.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(GetTypeHandle(import.TargetTypeOpt))); // TODO: index in release build } else if (import.TargetNamespaceOpt != null) { if (import.TargetAssemblyOpt != null) { if (import.AliasOpt != null) { // <import> ::= AliasAssemblyNamespace <alias> <target-assembly> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.AliasAssemblyNamespace); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } else { // <import> ::= ImportAssemblyNamespace <target-assembly> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyNamespace); } writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(GetAssemblyReferenceHandle(import.TargetAssemblyOpt))); } else { if (import.AliasOpt != null) { // <import> ::= AliasNamespace <alias> <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.AliasNamespace); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } else { // <import> ::= ImportNamespace <target-namespace> writer.WriteByte((byte)ImportDefinitionKind.ImportNamespace); } } // TODO: cache? string namespaceName = TypeNameSerializer.BuildQualifiedNamespaceName(import.TargetNamespaceOpt); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(namespaceName))); } else { // <import> ::= ImportReferenceAlias <alias> Debug.Assert(import.AliasOpt != null); Debug.Assert(import.TargetAssemblyOpt == null); writer.WriteByte((byte)ImportDefinitionKind.ImportAssemblyReferenceAlias); writer.WriteCompressedInteger(MetadataTokens.GetHeapOffset(_debugMetadataOpt.GetOrAddBlobUTF8(import.AliasOpt))); } } private void DefineModuleImportScope() { // module-level import scope: var writer = new BlobBuilder(); SerializeModuleDefaultNamespace(); foreach (AssemblyReferenceAlias alias in module.GetAssemblyReferenceAliases(Context)) { SerializeImport(writer, alias); } foreach (UsedNamespaceOrType import in module.GetImports()) { SerializeImport(writer, import); } var rid = _debugMetadataOpt.AddImportScope( parentScope: default(ImportScopeHandle), imports: _debugMetadataOpt.GetOrAddBlob(writer)); Debug.Assert(rid == ModuleImportScopeHandle); } private ImportScopeHandle GetImportScopeIndex(IImportScope scope, Dictionary<IImportScope, ImportScopeHandle> scopeIndex) { ImportScopeHandle scopeHandle; if (scopeIndex.TryGetValue(scope, out scopeHandle)) { // scope is already indexed: return scopeHandle; } var parent = scope.Parent; var parentScopeHandle = (parent != null) ? GetImportScopeIndex(scope.Parent, scopeIndex) : ModuleImportScopeHandle; var result = _debugMetadataOpt.AddImportScope( parentScope: parentScopeHandle, imports: SerializeImportsBlob(scope)); scopeIndex.Add(scope, result); return result; } private BlobHandle SerializeImportsBlob(IImportScope scope) { var writer = new BlobBuilder(); foreach (UsedNamespaceOrType import in scope.GetUsedNamespaces()) { SerializeImport(writer, import); } return _debugMetadataOpt.GetOrAddBlob(writer); } private void SerializeModuleDefaultNamespace() { // C#: DefaultNamespace is null. // VB: DefaultNamespace is non-null. if (module.DefaultNamespace == null) { return; } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DefaultNamespace), value: _debugMetadataOpt.GetOrAddBlobUTF8(module.DefaultNamespace)); } #endregion #region Locals private void SerializeLocalInfo(ILocalDefinition local, EntityHandle parent) { var dynamicFlags = local.DynamicTransformFlags; if (!dynamicFlags.IsEmpty) { var value = SerializeBitVector(dynamicFlags); _debugMetadataOpt.AddCustomDebugInformation( parent: parent, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.DynamicLocalVariables), value: _debugMetadataOpt.GetOrAddBlob(value)); } var tupleElementNames = local.TupleElementNames; if (!tupleElementNames.IsEmpty) { var builder = new BlobBuilder(); SerializeTupleElementNames(builder, tupleElementNames); _debugMetadataOpt.AddCustomDebugInformation( parent: parent, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.TupleElementNames), value: _debugMetadataOpt.GetOrAddBlob(builder)); } } private static ImmutableArray<byte> SerializeBitVector(ImmutableArray<bool> vector) { var builder = ArrayBuilder<byte>.GetInstance(); int b = 0; int shift = 0; for (int i = 0; i < vector.Length; i++) { if (vector[i]) { b |= 1 << shift; } if (shift == 7) { builder.Add((byte)b); b = 0; shift = 0; } else { shift++; } } if (b != 0) { builder.Add((byte)b); } else { // trim trailing zeros: int lastNonZero = builder.Count - 1; while (builder[lastNonZero] == 0) { lastNonZero--; } builder.Clip(lastNonZero + 1); } return builder.ToImmutableAndFree(); } private static void SerializeTupleElementNames(BlobBuilder builder, ImmutableArray<string> names) { foreach (var name in names) { WriteUtf8String(builder, name ?? string.Empty); } } /// <summary> /// Write string as UTF8 with null terminator. /// </summary> private static void WriteUtf8String(BlobBuilder builder, string str) { builder.WriteUTF8(str); builder.WriteByte(0); } #endregion #region State Machines private void SerializeAsyncMethodSteppingInfo(AsyncMoveNextBodyDebugInfo asyncInfo, MethodDefinitionHandle moveNextMethod, int aggregateMethodDefRid) { Debug.Assert(asyncInfo.ResumeOffsets.Length == asyncInfo.YieldOffsets.Length); Debug.Assert(asyncInfo.CatchHandlerOffset >= -1); var writer = new BlobBuilder(); writer.WriteUInt32((uint)((long)asyncInfo.CatchHandlerOffset + 1)); for (int i = 0; i < asyncInfo.ResumeOffsets.Length; i++) { writer.WriteUInt32((uint)asyncInfo.YieldOffsets[i]); writer.WriteUInt32((uint)asyncInfo.ResumeOffsets[i]); writer.WriteCompressedInteger(aggregateMethodDefRid); } _debugMetadataOpt.AddCustomDebugInformation( parent: moveNextMethod, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.AsyncMethodSteppingInformationBlob), value: _debugMetadataOpt.GetOrAddBlob(writer)); } private void SerializeStateMachineLocalScopes(IMethodBody methodBody, MethodDefinitionHandle method) { var scopes = methodBody.StateMachineHoistedLocalScopes; if (scopes.IsDefaultOrEmpty) { return; } var writer = new BlobBuilder(); foreach (var scope in scopes) { writer.WriteUInt32((uint)scope.StartOffset); writer.WriteUInt32((uint)scope.Length); } _debugMetadataOpt.AddCustomDebugInformation( parent: method, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes), value: _debugMetadataOpt.GetOrAddBlob(writer)); } #endregion #region Sequence Points private BlobHandle SerializeSequencePoints( StandaloneSignatureHandle localSignatureHandleOpt, ImmutableArray<SequencePoint> sequencePoints, Dictionary<DebugSourceDocument, DocumentHandle> documentIndex, out DocumentHandle singleDocumentHandle) { if (sequencePoints.Length == 0) { singleDocumentHandle = default(DocumentHandle); return default(BlobHandle); } var writer = new BlobBuilder(); int previousNonHiddenStartLine = -1; int previousNonHiddenStartColumn = -1; // header: writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(localSignatureHandleOpt)); var previousDocument = TryGetSingleDocument(sequencePoints); singleDocumentHandle = (previousDocument != null) ? GetOrAddDocument(previousDocument, documentIndex) : default(DocumentHandle); for (int i = 0; i < sequencePoints.Length; i++) { var currentDocument = sequencePoints[i].Document; if (previousDocument != currentDocument) { var documentHandle = GetOrAddDocument(currentDocument, documentIndex); // optional document in header or document record: if (previousDocument != null) { writer.WriteCompressedInteger(0); } writer.WriteCompressedInteger(MetadataTokens.GetRowNumber(documentHandle)); previousDocument = currentDocument; } // delta IL offset: if (i > 0) { writer.WriteCompressedInteger(sequencePoints[i].Offset - sequencePoints[i - 1].Offset); } else { writer.WriteCompressedInteger(sequencePoints[i].Offset); } if (sequencePoints[i].IsHidden) { writer.WriteInt16(0); continue; } // Delta Lines & Columns: SerializeDeltaLinesAndColumns(writer, sequencePoints[i]); // delta Start Lines & Columns: if (previousNonHiddenStartLine < 0) { Debug.Assert(previousNonHiddenStartColumn < 0); writer.WriteCompressedInteger(sequencePoints[i].StartLine); writer.WriteCompressedInteger(sequencePoints[i].StartColumn); } else { writer.WriteCompressedSignedInteger(sequencePoints[i].StartLine - previousNonHiddenStartLine); writer.WriteCompressedSignedInteger(sequencePoints[i].StartColumn - previousNonHiddenStartColumn); } previousNonHiddenStartLine = sequencePoints[i].StartLine; previousNonHiddenStartColumn = sequencePoints[i].StartColumn; } return _debugMetadataOpt.GetOrAddBlob(writer); } private static DebugSourceDocument TryGetSingleDocument(ImmutableArray<SequencePoint> sequencePoints) { DebugSourceDocument singleDocument = sequencePoints[0].Document; for (int i = 1; i < sequencePoints.Length; i++) { if (sequencePoints[i].Document != singleDocument) { return null; } } return singleDocument; } private void SerializeDeltaLinesAndColumns(BlobBuilder writer, SequencePoint sequencePoint) { int deltaLines = sequencePoint.EndLine - sequencePoint.StartLine; int deltaColumns = sequencePoint.EndColumn - sequencePoint.StartColumn; // only hidden sequence points have zero width Debug.Assert(deltaLines != 0 || deltaColumns != 0 || sequencePoint.IsHidden); writer.WriteCompressedInteger(deltaLines); if (deltaLines == 0) { writer.WriteCompressedInteger(deltaColumns); } else { writer.WriteCompressedSignedInteger(deltaColumns); } } #endregion #region Documents private DocumentHandle GetOrAddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index) { if (index.TryGetValue(document, out var documentHandle)) { return documentHandle; } return AddDocument(document, index); } private DocumentHandle AddDocument(DebugSourceDocument document, Dictionary<DebugSourceDocument, DocumentHandle> index) { DocumentHandle documentHandle; DebugSourceInfo info = document.GetSourceInfo(); var name = document.Location; if (_usingNonSourceDocumentNameEnumerator) { var result = _nonSourceDocumentNameEnumerator.MoveNext(); Debug.Assert(result); name = _nonSourceDocumentNameEnumerator.Current; } documentHandle = _debugMetadataOpt.AddDocument( name: _debugMetadataOpt.GetOrAddDocumentName(name), hashAlgorithm: info.Checksum.IsDefault ? default(GuidHandle) : _debugMetadataOpt.GetOrAddGuid(info.ChecksumAlgorithmId), hash: info.Checksum.IsDefault ? default(BlobHandle) : _debugMetadataOpt.GetOrAddBlob(info.Checksum), language: _debugMetadataOpt.GetOrAddGuid(document.Language)); index.Add(document, documentHandle); if (info.EmbeddedTextBlob != null) { _debugMetadataOpt.AddCustomDebugInformation( parent: documentHandle, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EmbeddedSource), value: _debugMetadataOpt.GetOrAddBlob(info.EmbeddedTextBlob)); } return documentHandle; } /// <summary> /// Add document entries for all debug documents that do not yet have an entry. /// </summary> /// <remarks> /// This is done after serializing method debug info to ensure that we embed all requested /// text even if there are no corresponding sequence points. /// </remarks> public void AddRemainingDebugDocuments(IReadOnlyDictionary<string, DebugSourceDocument> documents) { foreach (var kvp in documents .Where(kvp => !_documentIndex.ContainsKey(kvp.Value)) .OrderBy(kvp => kvp.Key)) { AddDocument(kvp.Value, _documentIndex); } } #endregion #region Edit and Continue private void SerializeEncMethodDebugInformation(IMethodBody methodBody, MethodDefinitionHandle method) { var encInfo = GetEncMethodDebugInfo(methodBody); if (!encInfo.LocalSlots.IsDefaultOrEmpty) { var writer = new BlobBuilder(); encInfo.SerializeLocalSlots(writer); _debugMetadataOpt.AddCustomDebugInformation( parent: method, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLocalSlotMap), value: _debugMetadataOpt.GetOrAddBlob(writer)); } if (!encInfo.Lambdas.IsDefaultOrEmpty) { var writer = new BlobBuilder(); encInfo.SerializeLambdaMap(writer); _debugMetadataOpt.AddCustomDebugInformation( parent: method, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.EncLambdaAndClosureMap), value: _debugMetadataOpt.GetOrAddBlob(writer)); } } #endregion private void EmbedSourceLink(Stream stream) { byte[] bytes; try { bytes = stream.ReadAllBytes(); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new SymUnmanagedWriterException(e.Message, e); } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.SourceLink), value: _debugMetadataOpt.GetOrAddBlob(bytes)); } ///<summary>The version of the compilation options schema to be written to the PDB.</summary> private const int CompilationOptionsSchemaVersion = 2; /// <summary> /// Capture the set of compilation options to allow a compilation /// to be reconstructed from the pdb /// </summary> private void EmbedCompilationOptions(CommonPEModuleBuilder module) { var builder = new BlobBuilder(); if (this.Context.RebuildData is { } rebuildData) { var reader = rebuildData.OptionsBlobReader; builder.WriteBytes(reader.ReadBytes(reader.RemainingBytes)); } else { var compilerVersion = typeof(Compilation).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion; WriteValue(CompilationOptionNames.CompilationOptionsVersion, CompilationOptionsSchemaVersion.ToString()); WriteValue(CompilationOptionNames.CompilerVersion, compilerVersion); WriteValue(CompilationOptionNames.Language, module.CommonCompilation.Options.Language); WriteValue(CompilationOptionNames.SourceFileCount, module.CommonCompilation.SyntaxTrees.Count().ToString()); WriteValue(CompilationOptionNames.OutputKind, module.OutputKind.ToString()); if (module.EmitOptions.FallbackSourceFileEncoding != null) { WriteValue(CompilationOptionNames.FallbackEncoding, module.EmitOptions.FallbackSourceFileEncoding.WebName); } if (module.EmitOptions.DefaultSourceFileEncoding != null) { WriteValue(CompilationOptionNames.DefaultEncoding, module.EmitOptions.DefaultSourceFileEncoding.WebName); } int portabilityPolicy = 0; if (module.CommonCompilation.Options.AssemblyIdentityComparer is DesktopAssemblyIdentityComparer identityComparer) { portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightLibraryAssembliesPortability ? 0b1 : 0; portabilityPolicy |= identityComparer.PortabilityPolicy.SuppressSilverlightPlatformAssembliesPortability ? 0b10 : 0; } if (portabilityPolicy != 0) { WriteValue(CompilationOptionNames.PortabilityPolicy, portabilityPolicy.ToString()); } var optimizationLevel = module.CommonCompilation.Options.OptimizationLevel; var debugPlusMode = module.CommonCompilation.Options.DebugPlusMode; if ((optimizationLevel, debugPlusMode) != OptimizationLevelFacts.DefaultValues) { WriteValue(CompilationOptionNames.Optimization, optimizationLevel.ToPdbSerializedString(debugPlusMode)); } var platform = module.CommonCompilation.Options.Platform; WriteValue(CompilationOptionNames.Platform, platform.ToString()); var runtimeVersion = typeof(object).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion; WriteValue(CompilationOptionNames.RuntimeVersion, runtimeVersion); module.CommonCompilation.SerializePdbEmbeddedCompilationOptions(builder); } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationOptions), value: _debugMetadataOpt.GetOrAddBlob(builder)); void WriteValue(string key, string value) { builder.WriteUTF8(key); builder.WriteByte(0); builder.WriteUTF8(value); builder.WriteByte(0); } } /// <summary> /// Writes information about metadata references to the pdb so the same /// reference can be found on sourcelink to create the compilation again /// </summary> private void EmbedMetadataReferenceInformation(CommonPEModuleBuilder module) { var builder = new BlobBuilder(); // Order of information // File name (null terminated string): A.exe // Extern Alias (null terminated string): a1,a2,a3 // MetadataImageKind (byte) // EmbedInteropTypes (boolean) // COFF header Timestamp field (4 byte int) // COFF header SizeOfImage field (4 byte int) // MVID (Guid, 24 bytes) var referenceManager = module.CommonCompilation.GetBoundReferenceManager(); foreach (var pair in referenceManager.GetReferencedAssemblyAliases()) { if (referenceManager.GetMetadataReference(pair.AssemblySymbol) is PortableExecutableReference { FilePath: { } } portableReference) { var fileName = PathUtilities.GetFileName(portableReference.FilePath); var peReader = pair.AssemblySymbol.GetISymbol() is IAssemblySymbol assemblySymbol ? assemblySymbol.GetMetadata().GetAssembly().ManifestModule.PEReaderOpt : null; // Don't write before checking that we can get a peReader for the metadata reference if (peReader is null) continue; // Write file name first builder.WriteUTF8(fileName); // Make sure to add null terminator builder.WriteByte(0); // Extern alias if (pair.Aliases.Length > 0) builder.WriteUTF8(string.Join(",", pair.Aliases.OrderBy(StringComparer.Ordinal))); // Always null terminate the extern alias list builder.WriteByte(0); byte kindAndEmbedInteropTypes = (byte)(portableReference.Properties.EmbedInteropTypes ? 0b10 : 0b0); kindAndEmbedInteropTypes |= portableReference.Properties.Kind switch { MetadataImageKind.Assembly => 1, MetadataImageKind.Module => 0, _ => throw ExceptionUtilities.UnexpectedValue(portableReference.Properties.Kind) }; builder.WriteByte(kindAndEmbedInteropTypes); builder.WriteInt32(peReader.PEHeaders.CoffHeader.TimeDateStamp); builder.WriteInt32(peReader.PEHeaders.PEHeader.SizeOfImage); var metadataReader = peReader.GetMetadataReader(); var moduleDefinition = metadataReader.GetModuleDefinition(); builder.WriteGuid(metadataReader.GetGuid(moduleDefinition.Mvid)); } } _debugMetadataOpt.AddCustomDebugInformation( parent: EntityHandle.ModuleDefinition, kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.CompilationMetadataReferences), value: _debugMetadataOpt.GetOrAddBlob(builder)); } private void EmbedTypeDefinitionDocumentInformation(CommonPEModuleBuilder module) { var builder = new BlobBuilder(); foreach (var (definition, documents) in module.GetTypeToDebugDocumentMap(Context)) { foreach (var document in documents) { var handle = GetOrAddDocument(document, _documentIndex); builder.WriteCompressedInteger(MetadataTokens.GetRowNumber(handle)); } _debugMetadataOpt.AddCustomDebugInformation( parent: GetTypeDefinitionHandle(definition), kind: _debugMetadataOpt.GetOrAddGuid(PortableCustomDebugInfoKinds.TypeDefinitionDocuments), value: _debugMetadataOpt.GetOrAddBlob(builder)); builder.Clear(); } } } }
1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/PEWriter/MetadataWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.Cci { internal abstract partial class MetadataWriter { internal static readonly Encoding s_utf8Encoding = Encoding.UTF8; /// <summary> /// This is the maximum length of a type or member name in metadata, assuming /// the name is in UTF-8 format and not (yet) null-terminated. /// </summary> /// <remarks> /// Source names may have to be shorter still to accommodate mangling. /// Used for event names, field names, property names, field names, method def names, /// member ref names, type def (full) names, type ref (full) names, exported type /// (full) names, parameter names, manifest resource names, and unmanaged method names /// (ImplMap table). /// /// See CLI Part II, section 22. /// </remarks> internal const int NameLengthLimit = 1024 - 1; //MAX_CLASS_NAME = 1024 in dev11 /// <summary> /// This is the maximum length of a path in metadata, assuming the path is in UTF-8 /// format and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for file names, module names, and module ref names. /// /// See CLI Part II, section 22. /// </remarks> internal const int PathLengthLimit = 260 - 1; //MAX_PATH = 1024 in dev11 /// <summary> /// This is the maximum length of a string in the PDB, assuming it is in UTF-8 format /// and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for import strings, locals, and local constants. /// </remarks> internal const int PdbLengthLimit = 2046; // Empirical, based on when ISymUnmanagedWriter2 methods start throwing. private readonly int _numTypeDefsEstimate; private readonly bool _deterministic; internal readonly bool MetadataOnly; internal readonly bool EmitTestCoverageData; // A map of method body before token translation to RVA. Used for deduplication of small bodies. private readonly Dictionary<(ImmutableArray<byte>, bool), int> _smallMethodBodies; private const byte TinyFormat = 2; private const int ThrowNullCodeSize = 2; private static readonly ImmutableArray<byte> ThrowNullEncodedBody = ImmutableArray.Create( (byte)((ThrowNullCodeSize << 2) | TinyFormat), (byte)ILOpCode.Ldnull, (byte)ILOpCode.Throw); protected MetadataWriter( MetadataBuilder metadata, MetadataBuilder debugMetadataOpt, DynamicAnalysisDataWriter dynamicAnalysisDataWriterOpt, EmitContext context, CommonMessageProvider messageProvider, bool metadataOnly, bool deterministic, bool emitTestCoverageData, CancellationToken cancellationToken) { Debug.Assert(metadata != debugMetadataOpt); this.module = context.Module; _deterministic = deterministic; this.MetadataOnly = metadataOnly; this.EmitTestCoverageData = emitTestCoverageData; // EDMAURER provide some reasonable size estimates for these that will avoid // much of the reallocation that would occur when growing these from empty. _signatureIndex = new Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>>(module.HintNumberOfMethodDefinitions, ReferenceEqualityComparer.Instance); //ignores field signatures _numTypeDefsEstimate = module.HintNumberOfMethodDefinitions / 6; this.Context = context; this.messageProvider = messageProvider; _cancellationToken = cancellationToken; this.metadata = metadata; _debugMetadataOpt = debugMetadataOpt; _dynamicAnalysisDataWriterOpt = dynamicAnalysisDataWriterOpt; _smallMethodBodies = new Dictionary<(ImmutableArray<byte>, bool), int>(ByteSequenceBoolTupleComparer.Instance); } private int NumberOfTypeDefsEstimate { get { return _numTypeDefsEstimate; } } /// <summary> /// Returns true if writing full metadata, false if writing delta. /// </summary> internal bool IsFullMetadata { get { return this.Generation == 0; } } /// <summary> /// True if writing delta metadata in a minimal format. /// </summary> private bool IsMinimalDelta { get { return !IsFullMetadata; } } /// <summary> /// NetModules and EnC deltas don't have AssemblyDef record. /// We don't emit it for EnC deltas since assembly identity has to be preserved across generations (CLR/debugger get confused otherwise). /// </summary> private bool EmitAssemblyDefinition => module.OutputKind != OutputKind.NetModule && !IsMinimalDelta; /// <summary> /// Returns metadata generation ordinal. Zero for /// full metadata and non-zero for delta. /// </summary> protected abstract ushort Generation { get; } /// <summary> /// Returns unique Guid for this delta, or default(Guid) /// if full metadata. /// </summary> protected abstract Guid EncId { get; } /// <summary> /// Returns Guid of previous delta, or default(Guid) /// if full metadata or generation 1 delta. /// </summary> protected abstract Guid EncBaseId { get; } /// <summary> /// Returns true and full metadata handle of the type definition /// if the type definition is recognized. Otherwise returns false. /// </summary> protected abstract bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle); /// <summary> /// Get full metadata handle of the type definition. /// </summary> protected abstract TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def); /// <summary> /// The type definition corresponding to full metadata type handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract ITypeDefinition GetTypeDef(TypeDefinitionHandle handle); /// <summary> /// The type definitions to be emitted, in row order. These /// are just the type definitions from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeDefinition> GetTypeDefs(); /// <summary> /// Get full metadata handle of the event definition. /// </summary> protected abstract EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def); /// <summary> /// The event definitions to be emitted, in row order. These /// are just the event definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IEventDefinition> GetEventDefs(); /// <summary> /// Get full metadata handle of the field definition. /// </summary> protected abstract FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def); /// <summary> /// The field definitions to be emitted, in row order. These /// are just the field definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IFieldDefinition> GetFieldDefs(); /// <summary> /// Returns true and handle of the method definition /// if the method definition is recognized. Otherwise returns false. /// The index is into the full metadata. /// </summary> protected abstract bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle); /// <summary> /// Get full metadata handle of the method definition. /// </summary> protected abstract MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def); /// <summary> /// The method definition corresponding to full metadata method handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract IMethodDefinition GetMethodDef(MethodDefinitionHandle handle); /// <summary> /// The method definitions to be emitted, in row order. These /// are just the method definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IMethodDefinition> GetMethodDefs(); /// <summary> /// Get full metadata handle of the property definition. /// </summary> protected abstract PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def); /// <summary> /// The property definitions to be emitted, in row order. These /// are just the property definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IPropertyDefinition> GetPropertyDefs(); /// <summary> /// The full metadata handle of the parameter definition. /// </summary> protected abstract ParameterHandle GetParameterHandle(IParameterDefinition def); /// <summary> /// The parameter definitions to be emitted, in row order. These /// are just the parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IParameterDefinition> GetParameterDefs(); /// <summary> /// The generic parameter definitions to be emitted, in row order. These /// are just the generic parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericParameter> GetGenericParameters(); /// <summary> /// The handle of the first field of the type. /// </summary> protected abstract FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first method of the type. /// </summary> protected abstract MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first parameter of the method. /// </summary> protected abstract ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef); /// <summary> /// Return full metadata handle of the assembly reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference); /// <summary> /// The assembly references to be emitted, in row order. These /// are just the assembly references from the current generation. /// </summary> protected abstract IReadOnlyList<AssemblyIdentity> GetAssemblyRefs(); // ModuleRef table contains module names for TypeRefs that target types in netmodules (represented by IModuleReference), // and module names specified by P/Invokes (plain strings). Names in the table must be unique and are case sensitive. // // Spec 22.31 (ModuleRef : 0x1A) // "Name should match an entry in the Name column of the File table. Moreover, that entry shall enable the // CLI to locate the target module (typically it might name the file used to hold the module)" // // This is not how the Dev10 compilers and ILASM work. An entry is added to File table only for resources and netmodules. // Entries aren't added for P/Invoked modules. /// <summary> /// Return full metadata handle of the module reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference); /// <summary> /// The module references to be emitted, in row order. These /// are just the module references from the current generation. /// </summary> protected abstract IReadOnlyList<string> GetModuleRefs(); /// <summary> /// Return full metadata handle of the member reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference); /// <summary> /// The member references to be emitted, in row order. These /// are just the member references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeMemberReference> GetMemberRefs(); /// <summary> /// Return full metadata handle of the method spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference); /// <summary> /// The method specs to be emitted, in row order. These /// are just the method specs from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs(); /// <summary> /// The greatest index given to any method definition. /// </summary> protected abstract int GreatestMethodDefIndex { get; } /// <summary> /// Return true and full metadata handle of the type reference /// if the reference is available in the current generation. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle); /// <summary> /// Return full metadata handle of the type reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference); /// <summary> /// The type references to be emitted, in row order. These /// are just the type references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeRefs(); /// <summary> /// Returns full metadata handle of the type spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference); /// <summary> /// The type specs to be emitted, in row order. These /// are just the type specs from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeSpecs(); /// <summary> /// Returns full metadata handle the standalone signature, adding /// the signature to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle handle); /// <summary> /// The signature blob handles to be emitted, in row order. These /// are just the signature indices from the current generation. /// </summary> protected abstract IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles(); protected abstract void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef); /// <summary> /// Return a visitor for traversing all references to be emitted. /// </summary> protected abstract ReferenceIndexer CreateReferenceVisitor(); /// <summary> /// Populate EventMap table. /// </summary> protected abstract void PopulateEventMapTableRows(); /// <summary> /// Populate PropertyMap table. /// </summary> protected abstract void PopulatePropertyMapTableRows(); protected abstract void ReportReferencesToAddedSymbols(); // If true, it is allowed to have methods not have bodies (for emitting metadata-only // assembly) private readonly CancellationToken _cancellationToken; protected readonly CommonPEModuleBuilder module; public readonly EmitContext Context; protected readonly CommonMessageProvider messageProvider; // progress: private bool _tableIndicesAreComplete; private bool _usingNonSourceDocumentNameEnumerator; private ImmutableArray<string>.Enumerator _nonSourceDocumentNameEnumerator; private EntityHandle[] _pseudoSymbolTokenToTokenMap; private object[] _pseudoSymbolTokenToReferenceMap; private UserStringHandle[] _pseudoStringTokenToTokenMap; private bool _userStringTokenOverflow; private List<string> _pseudoStringTokenToStringMap; private ReferenceIndexer _referenceVisitor; protected readonly MetadataBuilder metadata; // A builder for Portable or Embedded PDB metadata, or null if we are not emitting Portable/Embedded PDB. protected readonly MetadataBuilder _debugMetadataOpt; internal bool EmitPortableDebugMetadata => _debugMetadataOpt != null; private readonly DynamicAnalysisDataWriter _dynamicAnalysisDataWriterOpt; private readonly Dictionary<ICustomAttribute, BlobHandle> _customAttributeSignatureIndex = new Dictionary<ICustomAttribute, BlobHandle>(); private readonly Dictionary<ITypeReference, BlobHandle> _typeSpecSignatureIndex = new Dictionary<ITypeReference, BlobHandle>(ReferenceEqualityComparer.Instance); private readonly Dictionary<string, int> _fileRefIndex = new Dictionary<string, int>(32); // more than enough in most cases, value is a RowId private readonly List<IFileReference> _fileRefList = new List<IFileReference>(32); private readonly Dictionary<IFieldReference, BlobHandle> _fieldSignatureIndex = new Dictionary<IFieldReference, BlobHandle>(ReferenceEqualityComparer.Instance); // We need to keep track of both the index of the signature and the actual blob to support VB static local naming scheme. private readonly Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>> _signatureIndex; private readonly Dictionary<IMarshallingInformation, BlobHandle> _marshallingDescriptorIndex = new Dictionary<IMarshallingInformation, BlobHandle>(); protected readonly List<MethodImplementation> methodImplList = new List<MethodImplementation>(); private readonly Dictionary<IGenericMethodInstanceReference, BlobHandle> _methodInstanceSignatureIndex = new Dictionary<IGenericMethodInstanceReference, BlobHandle>(ReferenceEqualityComparer.Instance); // Well known dummy cor library types whose refs are used for attaching assembly attributes off within net modules // There is no guarantee the types actually exist in a cor library internal const string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices"; internal const string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere"; internal static readonly string[,] dummyAssemblyAttributeParentQualifier = { { "", "M" }, { "S", "SM" } }; private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = { { default(TypeReferenceHandle), default(TypeReferenceHandle) }, { default(TypeReferenceHandle), default(TypeReferenceHandle) } }; internal CommonPEModuleBuilder Module => module; private void CreateMethodBodyReferenceIndex() { var referencesInIL = module.ReferencesInIL(); _pseudoSymbolTokenToTokenMap = new EntityHandle[referencesInIL.Length]; _pseudoSymbolTokenToReferenceMap = referencesInIL.ToArray(); } private void CreateIndices() { _cancellationToken.ThrowIfCancellationRequested(); this.CreateUserStringIndices(); this.CreateInitialAssemblyRefIndex(); this.CreateInitialFileRefIndex(); this.CreateIndicesForModule(); // Find all references and assign tokens. _referenceVisitor = this.CreateReferenceVisitor(); _referenceVisitor.Visit(module); this.CreateMethodBodyReferenceIndex(); this.OnIndicesCreated(); } private void CreateUserStringIndices() { _pseudoStringTokenToStringMap = new List<string>(); foreach (string str in this.module.GetStrings()) { _pseudoStringTokenToStringMap.Add(str); } _pseudoStringTokenToTokenMap = new UserStringHandle[_pseudoStringTokenToStringMap.Count]; } private void CreateIndicesForModule() { var nestedTypes = new Queue<INestedTypeDefinition>(); foreach (INamespaceTypeDefinition typeDef in module.GetTopLevelTypeDefinitions(Context)) { this.CreateIndicesFor(typeDef, nestedTypes); } while (nestedTypes.Count > 0) { var nestedType = nestedTypes.Dequeue(); this.CreateIndicesFor(nestedType, nestedTypes); } } protected virtual void OnIndicesCreated() { } private void CreateIndicesFor(ITypeDefinition typeDef, Queue<INestedTypeDefinition> nestedTypes) { _cancellationToken.ThrowIfCancellationRequested(); this.CreateIndicesForNonTypeMembers(typeDef); // Metadata spec: // The TypeDef table has a special ordering constraint: // the definition of an enclosing class shall precede the definition of all classes it encloses. foreach (var nestedType in typeDef.GetNestedTypes(Context)) { nestedTypes.Enqueue(nestedType); } } protected IEnumerable<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { if (typeDef.IsGeneric) { return typeDef.GenericParameters; } return null; } return this.GetConsolidatedTypeParameters(typeDef, typeDef); } private List<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef, ITypeDefinition owner) { List<IGenericTypeParameter> result = null; INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef != null) { result = this.GetConsolidatedTypeParameters(nestedTypeDef.ContainingTypeDefinition, owner); } if (typeDef.GenericParameterCount > 0) { ushort index = 0; if (result == null) { result = new List<IGenericTypeParameter>(); } else { index = (ushort)result.Count; } if (typeDef == owner && index == 0) { result.AddRange(typeDef.GenericParameters); } else { foreach (IGenericTypeParameter genericParameter in typeDef.GenericParameters) { result.Add(new InheritedTypeParameter(index++, owner, genericParameter)); } } } return result; } protected ImmutableArray<IParameterDefinition> GetParametersToEmit(IMethodDefinition methodDef) { if (methodDef.ParameterCount == 0 && !(methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context)))) { return ImmutableArray<IParameterDefinition>.Empty; } return GetParametersToEmitCore(methodDef); } private ImmutableArray<IParameterDefinition> GetParametersToEmitCore(IMethodDefinition methodDef) { ArrayBuilder<IParameterDefinition> builder = null; var parameters = methodDef.Parameters; if (methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context))) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length + 1); builder.Add(new ReturnValueParameter(methodDef)); } for (int i = 0; i < parameters.Length; i++) { IParameterDefinition parDef = parameters[i]; // No explicit param row is needed if param has no flags (other than optionally IN), // no name and no references to the param row, such as CustomAttribute, Constant, or FieldMarshal if (parDef.Name != String.Empty || parDef.HasDefaultValue || parDef.IsOptional || parDef.IsOut || parDef.IsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(parDef.GetAttributes(Context))) { if (builder != null) { builder.Add(parDef); } } else { // we have a parameter that does not need to be emitted (not common) if (builder == null) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length); builder.AddRange(parameters, i); } } } return builder?.ToImmutableAndFree() ?? parameters; } /// <summary> /// Returns a reference to the unit that defines the given referenced type. If the referenced type is a structural type, such as a pointer or a generic type instance, /// then the result is null. /// </summary> public static IUnitReference GetDefiningUnitReference(ITypeReference typeReference, EmitContext context) { INestedTypeReference nestedTypeReference = typeReference.AsNestedTypeReference; while (nestedTypeReference != null) { if (nestedTypeReference.AsGenericTypeInstanceReference != null) { return null; } typeReference = nestedTypeReference.GetContainingType(context); nestedTypeReference = typeReference.AsNestedTypeReference; } INamespaceTypeReference namespaceTypeReference = typeReference.AsNamespaceTypeReference; if (namespaceTypeReference == null) { return null; } Debug.Assert(namespaceTypeReference.AsGenericTypeInstanceReference == null); return namespaceTypeReference.GetUnit(context); } private void CreateInitialAssemblyRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IAssemblyReference assemblyRef in this.module.GetAssemblyReferences(Context)) { this.GetOrAddAssemblyReferenceHandle(assemblyRef); } } private void CreateInitialFileRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IFileReference fileRef in module.GetFiles(Context)) { string key = fileRef.FileName; if (!_fileRefIndex.ContainsKey(key)) { _fileRefList.Add(fileRef); _fileRefIndex.Add(key, _fileRefList.Count); } } } internal AssemblyReferenceHandle GetAssemblyReferenceHandle(IAssemblyReference assemblyReference) { var containingAssembly = this.module.GetContainingAssembly(Context); if (containingAssembly != null && ReferenceEquals(assemblyReference, containingAssembly)) { return default(AssemblyReferenceHandle); } return this.GetOrAddAssemblyReferenceHandle(assemblyReference); } internal ModuleReferenceHandle GetModuleReferenceHandle(string moduleName) { return this.GetOrAddModuleReferenceHandle(moduleName); } private BlobHandle GetCustomAttributeSignatureIndex(ICustomAttribute customAttribute) { BlobHandle result; if (_customAttributeSignatureIndex.TryGetValue(customAttribute, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeCustomAttributeSignature(customAttribute, writer); result = metadata.GetOrAddBlob(writer); _customAttributeSignatureIndex.Add(customAttribute, result); writer.Free(); return result; } private EntityHandle GetCustomAttributeTypeCodedIndex(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static EventAttributes GetEventAttributes(IEventDefinition eventDef) { EventAttributes result = 0; if (eventDef.IsSpecialName) { result |= EventAttributes.SpecialName; } if (eventDef.IsRuntimeSpecial) { result |= EventAttributes.RTSpecialName; } return result; } public static FieldAttributes GetFieldAttributes(IFieldDefinition fieldDef) { var result = (FieldAttributes)fieldDef.Visibility; if (fieldDef.IsStatic) { result |= FieldAttributes.Static; } if (fieldDef.IsReadOnly) { result |= FieldAttributes.InitOnly; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.Literal; } if (fieldDef.IsNotSerialized) { result |= FieldAttributes.NotSerialized; } if (!fieldDef.MappedData.IsDefault) { result |= FieldAttributes.HasFieldRVA; } if (fieldDef.IsSpecialName) { result |= FieldAttributes.SpecialName; } if (fieldDef.IsRuntimeSpecial) { result |= FieldAttributes.RTSpecialName; } if (fieldDef.IsMarshalledExplicitly) { result |= FieldAttributes.HasFieldMarshal; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.HasDefault; } return result; } internal BlobHandle GetFieldSignatureIndex(IFieldReference fieldReference) { BlobHandle result; ISpecializedFieldReference specializedFieldReference = fieldReference.AsSpecializedFieldReference; if (specializedFieldReference != null) { fieldReference = specializedFieldReference.UnspecializedVersion; } if (_fieldSignatureIndex.TryGetValue(fieldReference, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeFieldSignature(fieldReference, writer); result = metadata.GetOrAddBlob(writer); _fieldSignatureIndex.Add(fieldReference, result); writer.Free(); return result; } internal EntityHandle GetFieldHandle(IFieldReference fieldReference) { IFieldDefinition fieldDef = null; IUnitReference definingUnit = GetDefiningUnitReference(fieldReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { fieldDef = fieldReference.GetResolvedField(Context); } return fieldDef != null ? (EntityHandle)GetFieldDefinitionHandle(fieldDef) : GetMemberReferenceHandle(fieldReference); } internal AssemblyFileHandle GetAssemblyFileHandle(IFileReference fileReference) { string key = fileReference.FileName; int index; if (!_fileRefIndex.TryGetValue(key, out index)) { Debug.Assert(!_tableIndicesAreComplete); _fileRefList.Add(fileReference); _fileRefIndex.Add(key, index = _fileRefList.Count); } return MetadataTokens.AssemblyFileHandle(index); } private AssemblyFileHandle GetAssemblyFileHandle(IModuleReference mref) { return MetadataTokens.AssemblyFileHandle(_fileRefIndex[mref.Name]); } private static GenericParameterAttributes GetGenericParameterAttributes(IGenericParameter genPar) { GenericParameterAttributes result = 0; switch (genPar.Variance) { case TypeParameterVariance.Covariant: result |= GenericParameterAttributes.Covariant; break; case TypeParameterVariance.Contravariant: result |= GenericParameterAttributes.Contravariant; break; } if (genPar.MustBeReferenceType) { result |= GenericParameterAttributes.ReferenceTypeConstraint; } if (genPar.MustBeValueType) { result |= GenericParameterAttributes.NotNullableValueTypeConstraint; } if (genPar.MustHaveDefaultConstructor) { result |= GenericParameterAttributes.DefaultConstructorConstraint; } return result; } private EntityHandle GetExportedTypeImplementation(INamespaceTypeReference namespaceRef) { IUnitReference uref = namespaceRef.GetUnit(Context); if (uref is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } var mref = (IModuleReference)uref; aref = mref.GetContainingAssembly(Context); return aref == null || ReferenceEquals(aref, this.module.GetContainingAssembly(Context)) ? (EntityHandle)GetAssemblyFileHandle(mref) : GetAssemblyReferenceHandle(aref); } private static uint GetManagedResourceOffset(ManagedResource resource, BlobBuilder resourceWriter) { if (resource.ExternalFile != null) { return resource.Offset; } int result = resourceWriter.Count; resource.WriteData(resourceWriter); return (uint)result; } private static uint GetManagedResourceOffset(BlobBuilder resource, BlobBuilder resourceWriter) { int result = resourceWriter.Count; resourceWriter.WriteInt32(resource.Count); resource.WriteContentTo(resourceWriter); resourceWriter.Align(8); return (uint)result; } public static string GetMangledName(INamedTypeReference namedType, int generation) { string unmangledName = (generation == 0) ? namedType.Name : namedType.Name + "#" + generation; return namedType.MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(unmangledName, namedType.GenericParameterCount) : unmangledName; } internal MemberReferenceHandle GetMemberReferenceHandle(ITypeMemberReference memberRef) { return this.GetOrAddMemberReferenceHandle(memberRef); } internal EntityHandle GetMemberReferenceParent(ITypeMemberReference memberRef) { ITypeDefinition parentTypeDef = memberRef.GetContainingType(Context).AsTypeDefinition(Context); if (parentTypeDef != null) { TypeDefinitionHandle parentTypeDefHandle; TryGetTypeDefinitionHandle(parentTypeDef, out parentTypeDefHandle); if (!parentTypeDefHandle.IsNil) { if (memberRef is IFieldReference) { return parentTypeDefHandle; } if (memberRef is IMethodReference methodRef) { if (methodRef.AcceptsExtraArguments) { MethodDefinitionHandle methodHandle; if (this.TryGetMethodDefinitionHandle(methodRef.GetResolvedMethod(Context), out methodHandle)) { return methodHandle; } } return parentTypeDefHandle; } // TODO: error } } // TODO: special treatment for global fields and methods. Object model support would be nice. var containingType = memberRef.GetContainingType(Context); return containingType.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(containingType) : GetTypeReferenceHandle(containingType); } internal EntityHandle GetMethodDefinitionOrReferenceHandle(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static MethodAttributes GetMethodAttributes(IMethodDefinition methodDef) { var result = (MethodAttributes)methodDef.Visibility; if (methodDef.IsStatic) { result |= MethodAttributes.Static; } if (methodDef.IsSealed) { result |= MethodAttributes.Final; } if (methodDef.IsVirtual) { result |= MethodAttributes.Virtual; } if (methodDef.IsHiddenBySignature) { result |= MethodAttributes.HideBySig; } if (methodDef.IsNewSlot) { result |= MethodAttributes.NewSlot; } if (methodDef.IsAccessCheckedOnOverride) { result |= MethodAttributes.CheckAccessOnOverride; } if (methodDef.IsAbstract) { result |= MethodAttributes.Abstract; } if (methodDef.IsSpecialName) { result |= MethodAttributes.SpecialName; } if (methodDef.IsRuntimeSpecial) { result |= MethodAttributes.RTSpecialName; } if (methodDef.IsPlatformInvoke) { result |= MethodAttributes.PinvokeImpl; } if (methodDef.HasDeclarativeSecurity) { result |= MethodAttributes.HasSecurity; } if (methodDef.RequiresSecurityObject) { result |= MethodAttributes.RequireSecObject; } return result; } internal BlobHandle GetMethodSpecificationSignatureHandle(IGenericMethodInstanceReference methodInstanceReference) { BlobHandle result; if (_methodInstanceSignatureIndex.TryGetValue(methodInstanceReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSpecificationSignature(methodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference typeReference in methodInstanceReference.GetGenericArguments(Context)) { var typeRef = typeReference; SerializeTypeReference(encoder.AddArgument(), typeRef); } result = metadata.GetOrAddBlob(builder); _methodInstanceSignatureIndex.Add(methodInstanceReference, result); builder.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(IMarshallingInformation marshallingInformation) { BlobHandle result; if (_marshallingDescriptorIndex.TryGetValue(marshallingInformation, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeMarshallingDescriptor(marshallingInformation, writer); result = metadata.GetOrAddBlob(writer); _marshallingDescriptorIndex.Add(marshallingInformation, result); writer.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(ImmutableArray<byte> descriptor) { return metadata.GetOrAddBlob(descriptor); } private BlobHandle GetMemberReferenceSignatureHandle(ITypeMemberReference memberRef) { return memberRef switch { IFieldReference fieldReference => this.GetFieldSignatureIndex(fieldReference), IMethodReference methodReference => this.GetMethodSignatureHandle(methodReference), _ => throw ExceptionUtilities.Unreachable }; } internal BlobHandle GetMethodSignatureHandle(IMethodReference methodReference) { return GetMethodSignatureHandleAndBlob(methodReference, out _); } internal byte[] GetMethodSignature(IMethodReference methodReference) { ImmutableArray<byte> signatureBlob; GetMethodSignatureHandleAndBlob(methodReference, out signatureBlob); return signatureBlob.ToArray(); } private BlobHandle GetMethodSignatureHandleAndBlob(IMethodReference methodReference, out ImmutableArray<byte> signatureBlob) { BlobHandle result; ISpecializedMethodReference specializedMethodReference = methodReference.AsSpecializedMethodReference; if (specializedMethodReference != null) { methodReference = specializedMethodReference.UnspecializedVersion; } KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(methodReference, out existing)) { signatureBlob = existing.Value; return existing.Key; } Debug.Assert((methodReference.CallingConvention & CallingConvention.Generic) != 0 == (methodReference.GenericParameterCount > 0)); var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSignature( new SignatureHeader((byte)methodReference.CallingConvention).CallingConvention, methodReference.GenericParameterCount, isInstanceMethod: (methodReference.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, methodReference, methodReference.ExtraParameters); signatureBlob = builder.ToImmutableArray(); result = metadata.GetOrAddBlob(signatureBlob); _signatureIndex.Add(methodReference, KeyValuePairUtil.Create(result, signatureBlob)); builder.Free(); return result; } private BlobHandle GetMethodSpecificationBlobHandle(IGenericMethodInstanceReference genericMethodInstanceReference) { var writer = PooledBlobBuilder.GetInstance(); SerializeMethodSpecificationSignature(writer, genericMethodInstanceReference); BlobHandle result = metadata.GetOrAddBlob(writer); writer.Free(); return result; } private MethodSpecificationHandle GetMethodSpecificationHandle(IGenericMethodInstanceReference methodSpec) { return this.GetOrAddMethodSpecificationHandle(methodSpec); } internal EntityHandle GetMethodHandle(IMethodReference methodReference) { MethodDefinitionHandle methodDefHandle; IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } if (methodDef != null && (methodReference == methodDef || !methodReference.AcceptsExtraArguments) && this.TryGetMethodDefinitionHandle(methodDef, out methodDefHandle)) { return methodDefHandle; } IGenericMethodInstanceReference methodSpec = methodReference.AsGenericMethodInstanceReference; return methodSpec != null ? (EntityHandle)GetMethodSpecificationHandle(methodSpec) : GetMemberReferenceHandle(methodReference); } internal EntityHandle GetStandaloneSignatureHandle(ISignature signature) { Debug.Assert(!(signature is IMethodReference)); var builder = PooledBlobBuilder.GetInstance(); var signatureEncoder = new BlobEncoder(builder).MethodSignature(convention: signature.CallingConvention.ToSignatureConvention(), genericParameterCount: 0, isInstanceMethod: false); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); StandaloneSignatureHandle handle = GetOrAddStandaloneSignatureHandle(blobIndex); return handle; } public static ParameterAttributes GetParameterAttributes(IParameterDefinition parDef) { ParameterAttributes result = 0; if (parDef.IsIn) { result |= ParameterAttributes.In; } if (parDef.IsOut) { result |= ParameterAttributes.Out; } if (parDef.IsOptional) { result |= ParameterAttributes.Optional; } if (parDef.HasDefaultValue) { result |= ParameterAttributes.HasDefault; } if (parDef.IsMarshalledExplicitly) { result |= ParameterAttributes.HasFieldMarshal; } return result; } private BlobHandle GetPermissionSetBlobHandle(ImmutableArray<ICustomAttribute> permissionSet) { var writer = PooledBlobBuilder.GetInstance(); BlobHandle result; try { writer.WriteByte((byte)'.'); writer.WriteCompressedInteger(permissionSet.Length); this.SerializePermissionSet(permissionSet, writer); result = metadata.GetOrAddBlob(writer); } finally { writer.Free(); } return result; } public static PropertyAttributes GetPropertyAttributes(IPropertyDefinition propertyDef) { PropertyAttributes result = 0; if (propertyDef.IsSpecialName) { result |= PropertyAttributes.SpecialName; } if (propertyDef.IsRuntimeSpecial) { result |= PropertyAttributes.RTSpecialName; } if (propertyDef.HasDefaultValue) { result |= PropertyAttributes.HasDefault; } return result; } private BlobHandle GetPropertySignatureHandle(IPropertyDefinition propertyDef) { KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(propertyDef, out existing)) { return existing.Key; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).PropertySignature( isInstanceProperty: (propertyDef.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, propertyDef, ImmutableArray<IParameterTypeInformation>.Empty); var blob = builder.ToImmutableArray(); var result = metadata.GetOrAddBlob(blob); _signatureIndex.Add(propertyDef, KeyValuePairUtil.Create(result, blob)); builder.Free(); return result; } private EntityHandle GetResolutionScopeHandle(IUnitReference unitReference) { if (unitReference is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } // If this is a module from a referenced multi-module assembly, // the assembly should be used as the resolution scope. var mref = (IModuleReference)unitReference; aref = mref.GetContainingAssembly(Context); if (aref != null && aref != module.GetContainingAssembly(Context)) { return GetAssemblyReferenceHandle(aref); } return GetModuleReferenceHandle(mref.Name); } private StringHandle GetStringHandleForPathAndCheckLength(string path, INamedEntity errorEntity = null) { CheckPathLength(path, errorEntity); return metadata.GetOrAddString(path); } private StringHandle GetStringHandleForNameAndCheckLength(string name, INamedEntity errorEntity = null) { CheckNameLength(name, errorEntity); return metadata.GetOrAddString(name); } /// <summary> /// The Microsoft CLR requires that {namespace} + "." + {name} fit in MAX_CLASS_NAME /// (even though the name and namespace are stored separately in the Microsoft /// implementation). Note that the namespace name of a nested type is always blank /// (since comes from the container). /// </summary> /// <param name="namespaceType">We're trying to add the containing namespace of this type to the string heap.</param> /// <param name="mangledTypeName">Namespace names are never used on their own - this is the type that is adding the namespace name. /// Used only for length checking.</param> private StringHandle GetStringHandleForNamespaceAndCheckLength(INamespaceTypeReference namespaceType, string mangledTypeName) { string namespaceName = namespaceType.NamespaceName; if (namespaceName.Length == 0) // Optimization: CheckNamespaceLength is relatively expensive. { return default(StringHandle); } CheckNamespaceLength(namespaceName, mangledTypeName, namespaceType); return metadata.GetOrAddString(namespaceName); } private void CheckNameLength(string name, INamedEntity errorEntity) { // NOTE: ildasm shows quotes around some names (e.g. explicit implementations of members of generic interfaces) // but that seems to be tool-specific - they don't seem to and up in the string heap (so they don't count against // the length limit). if (IsTooLongInternal(name, NameLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, name)); } } private void CheckPathLength(string path, INamedEntity errorEntity = null) { if (IsTooLongInternal(path, PathLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, path)); } } private void CheckNamespaceLength(string namespaceName, string mangledTypeName, INamespaceTypeReference errorEntity) { // It's never useful to report that the namespace name is too long. // If it's too long, then the full name is too long and that string is // more helpful. // PERF: We expect to check this A LOT, so we'll aggressively inline some // of the helpers (esp IsTooLongInternal) in a way that allows us to forego // string concatenation (unless a diagnostic is actually reported). if (namespaceName.Length + 1 + mangledTypeName.Length > NameLengthLimit / 3) { int utf8Length = s_utf8Encoding.GetByteCount(namespaceName) + 1 + // dot s_utf8Encoding.GetByteCount(mangledTypeName); if (utf8Length > NameLengthLimit) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, namespaceName + "." + mangledTypeName)); } } } internal bool IsUsingStringTooLong(string usingString, INamedEntity errorEntity = null) { if (IsTooLongInternal(usingString, PdbLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbUsingNameTooLong, location, usingString)); return true; } return false; } internal bool IsLocalNameTooLong(ILocalDefinition localDefinition) { string name = localDefinition.Name; if (IsTooLongInternal(name, PdbLengthLimit)) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbLocalNameTooLong, localDefinition.Location, name)); return true; } return false; } /// <summary> /// Test the given name to see if it fits in metadata. /// </summary> /// <param name="str">String to test (non-null).</param> /// <param name="maxLength">Max length for name. (Expected to be at least 5.)</param> /// <returns>True if the name is too long.</returns> /// <remarks>Internal for test purposes.</remarks> internal static bool IsTooLongInternal(string str, int maxLength) { Debug.Assert(str != null); // No need to handle in an internal utility. if (str.Length < maxLength / 3) //UTF-8 uses at most 3 bytes per char { return false; } int utf8Length = s_utf8Encoding.GetByteCount(str); return utf8Length > maxLength; } private static Location GetNamedEntityLocation(INamedEntity errorEntity) { ISymbolInternal symbol; if (errorEntity is Cci.INamespace ns) { symbol = ns.GetInternalSymbol(); } else { symbol = (errorEntity as Cci.IReference)?.GetInternalSymbol(); } return GetSymbolLocation(symbol); } protected static Location GetSymbolLocation(ISymbolInternal symbolOpt) { return symbolOpt != null && !symbolOpt.Locations.IsDefaultOrEmpty ? symbolOpt.Locations[0] : Location.None; } internal TypeAttributes GetTypeAttributes(ITypeDefinition typeDef) { return GetTypeAttributes(typeDef, Context); } public static TypeAttributes GetTypeAttributes(ITypeDefinition typeDef, EmitContext context) { TypeAttributes result = 0; switch (typeDef.Layout) { case LayoutKind.Sequential: result |= TypeAttributes.SequentialLayout; break; case LayoutKind.Explicit: result |= TypeAttributes.ExplicitLayout; break; } if (typeDef.IsInterface) { result |= TypeAttributes.Interface; } if (typeDef.IsAbstract) { result |= TypeAttributes.Abstract; } if (typeDef.IsSealed) { result |= TypeAttributes.Sealed; } if (typeDef.IsSpecialName) { result |= TypeAttributes.SpecialName; } if (typeDef.IsRuntimeSpecial) { result |= TypeAttributes.RTSpecialName; } if (typeDef.IsComObject) { result |= TypeAttributes.Import; } if (typeDef.IsSerializable) { result |= TypeAttributes.Serializable; } if (typeDef.IsWindowsRuntimeImport) { result |= TypeAttributes.WindowsRuntime; } switch (typeDef.StringFormat) { case CharSet.Unicode: result |= TypeAttributes.UnicodeClass; break; case Constants.CharSet_Auto: result |= TypeAttributes.AutoClass; break; } if (typeDef.HasDeclarativeSecurity) { result |= TypeAttributes.HasSecurity; } if (typeDef.IsBeforeFieldInit) { result |= TypeAttributes.BeforeFieldInit; } INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(context); if (nestedTypeDef != null) { switch (((ITypeDefinitionMember)typeDef).Visibility) { case TypeMemberVisibility.Public: result |= TypeAttributes.NestedPublic; break; case TypeMemberVisibility.Private: result |= TypeAttributes.NestedPrivate; break; case TypeMemberVisibility.Family: result |= TypeAttributes.NestedFamily; break; case TypeMemberVisibility.Assembly: result |= TypeAttributes.NestedAssembly; break; case TypeMemberVisibility.FamilyAndAssembly: result |= TypeAttributes.NestedFamANDAssem; break; case TypeMemberVisibility.FamilyOrAssembly: result |= TypeAttributes.NestedFamORAssem; break; } return result; } INamespaceTypeDefinition namespaceTypeDef = typeDef.AsNamespaceTypeDefinition(context); if (namespaceTypeDef != null && namespaceTypeDef.IsPublic) { result |= TypeAttributes.Public; } return result; } private EntityHandle GetDeclaringTypeOrMethodHandle(IGenericParameter genPar) { IGenericTypeParameter genTypePar = genPar.AsGenericTypeParameter; if (genTypePar != null) { return GetTypeDefinitionHandle(genTypePar.DefiningType); } IGenericMethodParameter genMethPar = genPar.AsGenericMethodParameter; if (genMethPar != null) { return GetMethodDefinitionHandle(genMethPar.DefiningMethod); } throw ExceptionUtilities.Unreachable; } private TypeReferenceHandle GetTypeReferenceHandle(ITypeReference typeReference) { TypeReferenceHandle result; if (this.TryGetTypeReferenceHandle(typeReference, out result)) { return result; } // NOTE: Even though CLR documentation does not explicitly specify any requirements // NOTE: to the order of records in TypeRef table, some tools and/or APIs (e.g. // NOTE: IMetaDataEmit::MergeEnd) assume that the containing type referenced as // NOTE: ResolutionScope for its nested types should appear in TypeRef table // NOTE: *before* any of its nested types. // SEE ALSO: bug#570975 and test Bug570975() INestedTypeReference nestedTypeRef = typeReference.AsNestedTypeReference; if (nestedTypeRef != null) { GetTypeReferenceHandle(nestedTypeRef.GetContainingType(this.Context)); } return this.GetOrAddTypeReferenceHandle(typeReference); } private TypeSpecificationHandle GetTypeSpecificationHandle(ITypeReference typeReference) { return this.GetOrAddTypeSpecificationHandle(typeReference); } internal ITypeDefinition GetTypeDefinition(int token) { // The token must refer to a TypeDef row since we are // only handling indexes into the full metadata (in EnC) // for def tables. Other tables contain deltas only. return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)); } internal IMethodDefinition GetMethodDefinition(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetMethodDef(MetadataTokens.MethodDefinitionHandle(token)); } internal INestedTypeReference GetNestedTypeReference(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)).AsNestedTypeReference; } internal BlobHandle GetTypeSpecSignatureIndex(ITypeReference typeReference) { BlobHandle result; if (_typeSpecSignatureIndex.TryGetValue(typeReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); this.SerializeTypeReference(new BlobEncoder(builder).TypeSpecificationSignature(), typeReference); result = metadata.GetOrAddBlob(builder); _typeSpecSignatureIndex.Add(typeReference, result); builder.Free(); return result; } internal EntityHandle GetTypeHandle(ITypeReference typeReference, bool treatRefAsPotentialTypeSpec = true) { TypeDefinitionHandle handle; var typeDefinition = typeReference.AsTypeDefinition(this.Context); if (typeDefinition != null && this.TryGetTypeDefinitionHandle(typeDefinition, out handle)) { return handle; } return treatRefAsPotentialTypeSpec && typeReference.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(typeReference) : GetTypeReferenceHandle(typeReference); } internal EntityHandle GetDefinitionHandle(IDefinition definition) { return definition switch { ITypeDefinition typeDef => (EntityHandle)GetTypeDefinitionHandle(typeDef), IMethodDefinition methodDef => GetMethodDefinitionHandle(methodDef), IFieldDefinition fieldDef => GetFieldDefinitionHandle(fieldDef), IEventDefinition eventDef => GetEventDefinitionHandle(eventDef), IPropertyDefinition propertyDef => GetPropertyDefIndex(propertyDef), _ => throw ExceptionUtilities.Unreachable }; } public void WriteMetadataAndIL(PdbWriter nativePdbWriterOpt, Stream metadataStream, Stream ilStream, Stream portablePdbStreamOpt, out MetadataSizes metadataSizes) { Debug.Assert(nativePdbWriterOpt == null ^ portablePdbStreamOpt == null); nativePdbWriterOpt?.SetMetadataEmitter(this); // TODO: we can precalculate the exact size of IL stream var ilBuilder = new BlobBuilder(1024); var metadataBuilder = new BlobBuilder(4 * 1024); var mappedFieldDataBuilder = new BlobBuilder(0); var managedResourceDataBuilder = new BlobBuilder(0); // Add 4B of padding to the start of the separated IL stream, // so that method RVAs, which are offsets to this stream, are never 0. ilBuilder.WriteUInt32(0); // this is used to handle edit-and-continue emit, so we should have a module // version ID that is imposed by the caller (the same as the previous module version ID). // Therefore we do not have to fill in a new module version ID in the generated metadata // stream. Debug.Assert(module.SerializationProperties.PersistentIdentifier != default(Guid)); BuildMetadataAndIL( nativePdbWriterOpt, ilBuilder, mappedFieldDataBuilder, managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup); var typeSystemRowCounts = metadata.GetRowCounts(); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0); PopulateEncTables(typeSystemRowCounts); Debug.Assert(mappedFieldDataBuilder.Count == 0); Debug.Assert(managedResourceDataBuilder.Count == 0); Debug.Assert(mvidFixup.IsDefault); Debug.Assert(mvidStringFixup.IsDefault); // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. var rootBuilder = new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); rootBuilder.Serialize(metadataBuilder, methodBodyStreamRva: 0, mappedFieldDataStreamRva: 0); metadataSizes = rootBuilder.Sizes; try { ilBuilder.WriteContentTo(ilStream); metadataBuilder.WriteContentTo(metadataStream); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new PeWritingException(e); } if (portablePdbStreamOpt != null) { var portablePdbBuilder = GetPortablePdbBuilder( typeSystemRowCounts, debugEntryPoint: default(MethodDefinitionHandle), deterministicIdProviderOpt: null); var portablePdbBlob = new BlobBuilder(); portablePdbBuilder.Serialize(portablePdbBlob); try { portablePdbBlob.WriteContentTo(portablePdbStreamOpt); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new SymUnmanagedWriterException(e.Message, e); } } } public void BuildMetadataAndIL( PdbWriter nativePdbWriterOpt, BlobBuilder ilBuilder, BlobBuilder mappedFieldDataBuilder, BlobBuilder managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup) { // Extract information from object model into tables, indices and streams CreateIndices(); if (_debugMetadataOpt != null) { // Ensure document table lists files in command line order // This is key for us to be able to accurately rebuild a binary from a PDB. var documentsBuilder = Module.DebugDocumentsBuilder; foreach (var tree in Module.CommonCompilation.SyntaxTrees) { if (documentsBuilder.TryGetDebugDocument(tree.FilePath, basePath: null) is { } doc && !_documentIndex.ContainsKey(doc)) { AddDocument(doc, _documentIndex); } } if (Context.RebuildData is { } rebuildData) { _usingNonSourceDocumentNameEnumerator = true; _nonSourceDocumentNameEnumerator = rebuildData.NonSourceFileDocumentNames.GetEnumerator(); } DefineModuleImportScope(); if (module.SourceLinkStreamOpt != null) { EmbedSourceLink(module.SourceLinkStreamOpt); } EmbedCompilationOptions(module); EmbedMetadataReferenceInformation(module); } int[] methodBodyOffsets; if (MetadataOnly) { methodBodyOffsets = SerializeThrowNullMethodBodies(ilBuilder); mvidStringFixup = default(Blob); } else { methodBodyOffsets = SerializeMethodBodies(ilBuilder, nativePdbWriterOpt, out mvidStringFixup); } _cancellationToken.ThrowIfCancellationRequested(); // method body serialization adds Stand Alone Signatures _tableIndicesAreComplete = true; ReportReferencesToAddedSymbols(); BlobBuilder dynamicAnalysisDataOpt = null; if (_dynamicAnalysisDataWriterOpt != null) { dynamicAnalysisDataOpt = new BlobBuilder(); _dynamicAnalysisDataWriterOpt.SerializeMetadataTables(dynamicAnalysisDataOpt); } PopulateTypeSystemTables(methodBodyOffsets, mappedFieldDataBuilder, managedResourceDataBuilder, dynamicAnalysisDataOpt, out mvidFixup); } public virtual void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts) { } public MetadataRootBuilder GetRootBuilder() { // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. return new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); } public PortablePdbBuilder GetPortablePdbBuilder(ImmutableArray<int> typeSystemRowCounts, MethodDefinitionHandle debugEntryPoint, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProviderOpt) { return new PortablePdbBuilder(_debugMetadataOpt, typeSystemRowCounts, debugEntryPoint, deterministicIdProviderOpt); } internal void GetEntryPoints(out MethodDefinitionHandle entryPointHandle, out MethodDefinitionHandle debugEntryPointHandle) { if (IsFullMetadata && !MetadataOnly) { // PE entry point is set for executable programs IMethodReference entryPoint = module.PEEntryPoint; entryPointHandle = entryPoint != null ? (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)entryPoint.AsDefinition(Context)) : default(MethodDefinitionHandle); // debug entry point may be different from PE entry point, it may also be set for libraries IMethodReference debugEntryPoint = module.DebugEntryPoint; if (debugEntryPoint != null && debugEntryPoint != entryPoint) { debugEntryPointHandle = (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)debugEntryPoint.AsDefinition(Context)); } else { debugEntryPointHandle = entryPointHandle; } } else { entryPointHandle = debugEntryPointHandle = default(MethodDefinitionHandle); } } private ImmutableArray<IGenericParameter> GetSortedGenericParameters() { return GetGenericParameters().OrderBy((x, y) => { // Spec: GenericParam table is sorted by Owner and then by Number. int result = CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(x)) - CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(y)); if (result != 0) { return result; } return x.Index - y.Index; }).ToImmutableArray(); } private void PopulateTypeSystemTables(int[] methodBodyOffsets, BlobBuilder mappedFieldDataWriter, BlobBuilder resourceWriter, BlobBuilder dynamicAnalysisDataOpt, out Blob mvidFixup) { var sortedGenericParameters = GetSortedGenericParameters(); this.PopulateAssemblyRefTableRows(); this.PopulateAssemblyTableRows(); this.PopulateClassLayoutTableRows(); this.PopulateConstantTableRows(); this.PopulateDeclSecurityTableRows(); this.PopulateEventMapTableRows(); this.PopulateEventTableRows(); this.PopulateExportedTypeTableRows(); this.PopulateFieldLayoutTableRows(); this.PopulateFieldMarshalTableRows(); this.PopulateFieldRvaTableRows(mappedFieldDataWriter); this.PopulateFieldTableRows(); this.PopulateFileTableRows(); this.PopulateGenericParameters(sortedGenericParameters); this.PopulateImplMapTableRows(); this.PopulateInterfaceImplTableRows(); this.PopulateManifestResourceTableRows(resourceWriter, dynamicAnalysisDataOpt); this.PopulateMemberRefTableRows(); this.PopulateMethodImplTableRows(); this.PopulateMethodTableRows(methodBodyOffsets); this.PopulateMethodSemanticsTableRows(); this.PopulateMethodSpecTableRows(); this.PopulateModuleRefTableRows(); this.PopulateModuleTableRow(out mvidFixup); this.PopulateNestedClassTableRows(); this.PopulateParamTableRows(); this.PopulatePropertyMapTableRows(); this.PopulatePropertyTableRows(); this.PopulateTypeDefTableRows(); this.PopulateTypeRefTableRows(); this.PopulateTypeSpecTableRows(); this.PopulateStandaloneSignatures(); // This table is populated after the others because it depends on the order of the entries of the generic parameter table. this.PopulateCustomAttributeTableRows(sortedGenericParameters); } private void PopulateAssemblyRefTableRows() { var assemblyRefs = this.GetAssemblyRefs(); metadata.SetCapacity(TableIndex.AssemblyRef, assemblyRefs.Count); foreach (var identity in assemblyRefs) { // reference has token, not full public key metadata.AddAssemblyReference( name: GetStringHandleForPathAndCheckLength(identity.Name), version: identity.Version, culture: metadata.GetOrAddString(identity.CultureName), publicKeyOrToken: metadata.GetOrAddBlob(identity.PublicKeyToken), flags: (AssemblyFlags)((int)identity.ContentType << 9) | (identity.IsRetargetable ? AssemblyFlags.Retargetable : 0), hashValue: default(BlobHandle)); } } private void PopulateAssemblyTableRows() { if (!EmitAssemblyDefinition) { return; } var sourceAssembly = module.SourceAssemblyOpt; Debug.Assert(sourceAssembly != null); var flags = sourceAssembly.AssemblyFlags & ~AssemblyFlags.PublicKey; if (!sourceAssembly.Identity.PublicKey.IsDefaultOrEmpty) { flags |= AssemblyFlags.PublicKey; } metadata.AddAssembly( flags: flags, hashAlgorithm: sourceAssembly.HashAlgorithm, version: sourceAssembly.Identity.Version, publicKey: metadata.GetOrAddBlob(sourceAssembly.Identity.PublicKey), name: GetStringHandleForPathAndCheckLength(module.Name, module), culture: metadata.GetOrAddString(sourceAssembly.Identity.CultureName)); } private void PopulateCustomAttributeTableRows(ImmutableArray<IGenericParameter> sortedGenericParameters) { if (this.IsFullMetadata) { this.AddAssemblyAttributesToTable(); } this.AddCustomAttributesToTable(GetMethodDefs(), def => GetMethodDefinitionHandle(def)); this.AddCustomAttributesToTable(GetFieldDefs(), def => GetFieldDefinitionHandle(def)); // this.AddCustomAttributesToTable(this.typeRefList, 2); var typeDefs = GetTypeDefs(); this.AddCustomAttributesToTable(typeDefs, def => GetTypeDefinitionHandle(def)); this.AddCustomAttributesToTable(GetParameterDefs(), def => GetParameterHandle(def)); // TODO: attributes on member reference entries 6 if (this.IsFullMetadata) { this.AddModuleAttributesToTable(module); } // TODO: declarative security entries 8 this.AddCustomAttributesToTable(GetPropertyDefs(), def => GetPropertyDefIndex(def)); this.AddCustomAttributesToTable(GetEventDefs(), def => GetEventDefinitionHandle(def)); // TODO: standalone signature entries 11 // TODO: type spec entries 13 // this.AddCustomAttributesToTable(this.module.AssemblyReferences, 15); // TODO: this.AddCustomAttributesToTable(assembly.Files, 16); // TODO: exported types 17 // TODO: this.AddCustomAttributesToTable(assembly.Resources, 18); this.AddCustomAttributesToTable(sortedGenericParameters, TableIndex.GenericParam); } private void AddAssemblyAttributesToTable() { bool writingNetModule = module.OutputKind == OutputKind.NetModule; if (writingNetModule) { // When writing netmodules, assembly security attributes are not emitted by PopulateDeclSecurityTableRows(). // Instead, here we make sure they are emitted as regular attributes, attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. AddAssemblyAttributesToTable( this.module.GetSourceAssemblySecurityAttributes().Select(sa => sa.Attribute), needsDummyParent: true, isSecurity: true); } AddAssemblyAttributesToTable( this.module.GetSourceAssemblyAttributes(Context.IsRefAssembly), needsDummyParent: writingNetModule, isSecurity: false); } private void AddAssemblyAttributesToTable(IEnumerable<ICustomAttribute> assemblyAttributes, bool needsDummyParent, bool isSecurity) { Debug.Assert(this.IsFullMetadata); // parentToken is not relative EntityHandle parentHandle = Handle.AssemblyDefinition; foreach (ICustomAttribute customAttribute in assemblyAttributes) { if (needsDummyParent) { // When writing netmodules, assembly attributes are attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. parentHandle = GetDummyAssemblyAttributeParent(isSecurity, customAttribute.AllowMultiple); } AddCustomAttributeToTable(parentHandle, customAttribute); } } private TypeReferenceHandle GetDummyAssemblyAttributeParent(bool isSecurity, bool allowMultiple) { // Lazily get or create placeholder assembly attribute parent type ref for the given combination of // whether isSecurity and allowMultiple. Convert type ref row id to corresponding attribute parent tag. // Note that according to the defacto contract, although the placeholder type refs have CorLibrary as their // resolution scope, the types backing the placeholder type refs need not actually exist. int iS = isSecurity ? 1 : 0; int iM = allowMultiple ? 1 : 0; if (_dummyAssemblyAttributeParent[iS, iM].IsNil) { _dummyAssemblyAttributeParent[iS, iM] = metadata.AddTypeReference( resolutionScope: GetResolutionScopeHandle(module.GetCorLibrary(Context)), @namespace: metadata.GetOrAddString(dummyAssemblyAttributeParentNamespace), name: metadata.GetOrAddString(dummyAssemblyAttributeParentName + dummyAssemblyAttributeParentQualifier[iS, iM])); } return _dummyAssemblyAttributeParent[iS, iM]; } private void AddModuleAttributesToTable(CommonPEModuleBuilder module) { Debug.Assert(this.IsFullMetadata); AddCustomAttributesToTable(EntityHandle.ModuleDefinition, module.GetSourceModuleAttributes()); } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, TableIndex tableIndex) where T : IReference { int parentRowId = 1; foreach (var parent in parentList) { var parentHandle = MetadataTokens.Handle(tableIndex, parentRowId++); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, Func<T, EntityHandle> getDefinitionHandle) where T : IReference { foreach (var parent in parentList) { EntityHandle parentHandle = getDefinitionHandle(parent); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } protected virtual int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes) { int count = 0; foreach (var attr in attributes) { count++; AddCustomAttributeToTable(parentHandle, attr); } return count; } private void AddCustomAttributeToTable(EntityHandle parentHandle, ICustomAttribute customAttribute) { IMethodReference constructor = customAttribute.Constructor(Context, reportDiagnostics: true); if (constructor != null) { metadata.AddCustomAttribute( parent: parentHandle, constructor: GetCustomAttributeTypeCodedIndex(constructor), value: GetCustomAttributeSignatureIndex(customAttribute)); } } private void PopulateDeclSecurityTableRows() { if (module.OutputKind != OutputKind.NetModule) { this.PopulateDeclSecurityTableRowsFor(EntityHandle.AssemblyDefinition, module.GetSourceAssemblySecurityAttributes()); } foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (!typeDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetTypeDefinitionHandle(typeDef), typeDef.SecurityAttributes); } foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetMethodDefinitionHandle(methodDef), methodDef.SecurityAttributes); } } private void PopulateDeclSecurityTableRowsFor(EntityHandle parentHandle, IEnumerable<SecurityAttribute> attributes) { OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute> groupedSecurityAttributes = null; foreach (SecurityAttribute securityAttribute in attributes) { groupedSecurityAttributes = groupedSecurityAttributes ?? OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute>.GetInstance(); groupedSecurityAttributes.Add(securityAttribute.Action, securityAttribute.Attribute); } if (groupedSecurityAttributes == null) { return; } foreach (DeclarativeSecurityAction securityAction in groupedSecurityAttributes.Keys) { metadata.AddDeclarativeSecurityAttribute( parent: parentHandle, action: securityAction, permissionSet: GetPermissionSetBlobHandle(groupedSecurityAttributes[securityAction])); } groupedSecurityAttributes.Free(); } private void PopulateEventTableRows() { var eventDefs = this.GetEventDefs(); metadata.SetCapacity(TableIndex.Event, eventDefs.Count); foreach (IEventDefinition eventDef in eventDefs) { metadata.AddEvent( attributes: GetEventAttributes(eventDef), name: GetStringHandleForNameAndCheckLength(eventDef.Name, eventDef), type: GetTypeHandle(eventDef.GetType(Context))); } } private void PopulateExportedTypeTableRows() { if (!IsFullMetadata) { return; } var exportedTypes = module.GetExportedTypes(Context.Diagnostics); if (exportedTypes.Length == 0) { return; } metadata.SetCapacity(TableIndex.ExportedType, exportedTypes.Length); foreach (var exportedType in exportedTypes) { INestedTypeReference nestedRef; INamespaceTypeReference namespaceTypeRef; TypeAttributes attributes; StringHandle typeName; StringHandle typeNamespace; EntityHandle implementation; if ((namespaceTypeRef = exportedType.Type.AsNamespaceTypeReference) != null) { // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); typeNamespace = GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); implementation = GetExportedTypeImplementation(namespaceTypeRef); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic | Constants.TypeAttributes_TypeForwarder : TypeAttributes.Public; } else if ((nestedRef = exportedType.Type.AsNestedTypeReference) != null) { Debug.Assert(exportedType.ParentIndex != -1); // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(nestedRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, nestedRef); typeNamespace = default(StringHandle); implementation = MetadataTokens.ExportedTypeHandle(exportedType.ParentIndex + 1); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic : TypeAttributes.NestedPublic; } else { throw ExceptionUtilities.UnexpectedValue(exportedType); } metadata.AddExportedType( attributes: attributes, @namespace: typeNamespace, name: typeName, implementation: implementation, typeDefinitionId: exportedType.IsForwarder ? 0 : MetadataTokens.GetToken(exportedType.Type.TypeDef)); } } private void PopulateFieldLayoutTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.ContainingTypeDefinition.Layout != LayoutKind.Explicit || fieldDef.IsStatic) { continue; } metadata.AddFieldLayout( field: GetFieldDefinitionHandle(fieldDef), offset: fieldDef.Offset); } } private void PopulateFieldMarshalTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (!fieldDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = fieldDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(fieldDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetFieldDefinitionHandle(fieldDef), descriptor: descriptor); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { if (!parDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = parDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(parDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetParameterHandle(parDef), descriptor: descriptor); } } private void PopulateFieldRvaTableRows(BlobBuilder mappedFieldDataWriter) { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.MappedData.IsDefault) { continue; } int offset = mappedFieldDataWriter.Count; mappedFieldDataWriter.WriteBytes(fieldDef.MappedData); mappedFieldDataWriter.Align(ManagedPEBuilder.MappedFieldDataAlignment); metadata.AddFieldRelativeVirtualAddress( field: GetFieldDefinitionHandle(fieldDef), offset: offset); } } private void PopulateFieldTableRows() { var fieldDefs = this.GetFieldDefs(); metadata.SetCapacity(TableIndex.Field, fieldDefs.Count); foreach (IFieldDefinition fieldDef in fieldDefs) { if (fieldDef.IsContextualNamedEntity) { ((IContextualNamedEntity)fieldDef).AssociateWithMetadataWriter(this); } metadata.AddFieldDefinition( attributes: GetFieldAttributes(fieldDef), name: GetStringHandleForNameAndCheckLength(fieldDef.Name, fieldDef), signature: GetFieldSignatureIndex(fieldDef)); } } private void PopulateConstantTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { var constant = fieldDef.GetCompileTimeValue(Context); if (constant == null) { continue; } metadata.AddConstant( parent: GetFieldDefinitionHandle(fieldDef), value: constant.Value); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { var defaultValue = parDef.GetDefaultValue(Context); if (defaultValue == null) { continue; } metadata.AddConstant( parent: GetParameterHandle(parDef), value: defaultValue.Value); } foreach (IPropertyDefinition propDef in this.GetPropertyDefs()) { if (!propDef.HasDefaultValue) { continue; } metadata.AddConstant( parent: GetPropertyDefIndex(propDef), value: propDef.DefaultValue.Value); } } private void PopulateFileTableRows() { ISourceAssemblySymbolInternal assembly = module.SourceAssemblyOpt; if (assembly == null) { return; } var hashAlgorithm = assembly.HashAlgorithm; metadata.SetCapacity(TableIndex.File, _fileRefList.Count); foreach (IFileReference fileReference in _fileRefList) { metadata.AddAssemblyFile( name: GetStringHandleForPathAndCheckLength(fileReference.FileName), hashValue: metadata.GetOrAddBlob(fileReference.GetHashValue(hashAlgorithm)), containsMetadata: fileReference.HasMetadata); } } private void PopulateGenericParameters( ImmutableArray<IGenericParameter> sortedGenericParameters) { foreach (IGenericParameter genericParameter in sortedGenericParameters) { // CONSIDER: The CLI spec doesn't mention a restriction on the Name column of the GenericParam table, // but they go in the same string heap as all the other declaration names, so it stands to reason that // they should be restricted in the same way. var genericParameterHandle = metadata.AddGenericParameter( parent: GetDeclaringTypeOrMethodHandle(genericParameter), attributes: GetGenericParameterAttributes(genericParameter), name: GetStringHandleForNameAndCheckLength(genericParameter.Name, genericParameter), index: genericParameter.Index); foreach (var refWithAttributes in genericParameter.GetConstraints(Context)) { var genericConstraintHandle = metadata.AddGenericParameterConstraint( genericParameter: genericParameterHandle, constraint: GetTypeHandle(refWithAttributes.TypeRef)); AddCustomAttributesToTable(genericConstraintHandle, refWithAttributes.Attributes); } } } private void PopulateImplMapTableRows() { foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.IsPlatformInvoke) { continue; } var data = methodDef.PlatformInvokeData; string entryPointName = data.EntryPointName; StringHandle importName = entryPointName != null && entryPointName != methodDef.Name ? GetStringHandleForNameAndCheckLength(entryPointName, methodDef) : metadata.GetOrAddString(methodDef.Name); // Length checked while populating the method def table. metadata.AddMethodImport( method: GetMethodDefinitionHandle(methodDef), attributes: data.Flags, name: importName, module: GetModuleReferenceHandle(data.ModuleName)); } } private void PopulateInterfaceImplTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { var typeDefHandle = GetTypeDefinitionHandle(typeDef); foreach (var interfaceImpl in typeDef.Interfaces(Context)) { var handle = metadata.AddInterfaceImplementation( type: typeDefHandle, implementedInterface: GetTypeHandle(interfaceImpl.TypeRef)); AddCustomAttributesToTable(handle, interfaceImpl.Attributes); } } } private void PopulateManifestResourceTableRows(BlobBuilder resourceDataWriter, BlobBuilder dynamicAnalysisDataOpt) { if (dynamicAnalysisDataOpt != null) { metadata.AddManifestResource( attributes: ManifestResourceAttributes.Private, name: metadata.GetOrAddString("<DynamicAnalysisData>"), implementation: default(EntityHandle), offset: GetManagedResourceOffset(dynamicAnalysisDataOpt, resourceDataWriter) ); } foreach (var resource in this.module.GetResources(Context)) { EntityHandle implementation; if (resource.ExternalFile != null) { // Length checked on insertion into the file table. implementation = GetAssemblyFileHandle(resource.ExternalFile); } else { // This is an embedded resource, we don't support references to resources from referenced assemblies. implementation = default(EntityHandle); } metadata.AddManifestResource( attributes: resource.IsPublic ? ManifestResourceAttributes.Public : ManifestResourceAttributes.Private, name: GetStringHandleForNameAndCheckLength(resource.Name), implementation: implementation, offset: GetManagedResourceOffset(resource, resourceDataWriter)); } // the stream should be aligned: Debug.Assert((resourceDataWriter.Count % ManagedPEBuilder.ManagedResourcesDataAlignment) == 0); } private void PopulateMemberRefTableRows() { var memberRefs = this.GetMemberRefs(); metadata.SetCapacity(TableIndex.MemberRef, memberRefs.Count); foreach (ITypeMemberReference memberRef in memberRefs) { metadata.AddMemberReference( parent: GetMemberReferenceParent(memberRef), name: GetStringHandleForNameAndCheckLength(memberRef.Name, memberRef), signature: GetMemberReferenceSignatureHandle(memberRef)); } } private void PopulateMethodImplTableRows() { metadata.SetCapacity(TableIndex.MethodImpl, methodImplList.Count); foreach (MethodImplementation methodImplementation in this.methodImplList) { metadata.AddMethodImplementation( type: GetTypeDefinitionHandle(methodImplementation.ContainingType), methodBody: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementingMethod), methodDeclaration: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementedMethod)); } } private void PopulateMethodSpecTableRows() { var methodSpecs = this.GetMethodSpecs(); metadata.SetCapacity(TableIndex.MethodSpec, methodSpecs.Count); foreach (IGenericMethodInstanceReference genericMethodInstanceReference in methodSpecs) { metadata.AddMethodSpecification( method: GetMethodDefinitionOrReferenceHandle(genericMethodInstanceReference.GetGenericMethod(Context)), instantiation: GetMethodSpecificationBlobHandle(genericMethodInstanceReference)); } } private void PopulateMethodTableRows(int[] methodBodyOffsets) { var methodDefs = this.GetMethodDefs(); metadata.SetCapacity(TableIndex.MethodDef, methodDefs.Count); int i = 0; foreach (IMethodDefinition methodDef in methodDefs) { metadata.AddMethodDefinition( attributes: GetMethodAttributes(methodDef), implAttributes: methodDef.GetImplementationAttributes(Context), name: GetStringHandleForNameAndCheckLength(methodDef.Name, methodDef), signature: GetMethodSignatureHandle(methodDef), bodyOffset: methodBodyOffsets[i], parameterList: GetFirstParameterHandle(methodDef)); i++; } } private void PopulateMethodSemanticsTableRows() { var propertyDefs = this.GetPropertyDefs(); var eventDefs = this.GetEventDefs(); // an estimate, not necessarily accurate. metadata.SetCapacity(TableIndex.MethodSemantics, propertyDefs.Count * 2 + eventDefs.Count * 2); foreach (IPropertyDefinition propertyDef in this.GetPropertyDefs()) { var association = GetPropertyDefIndex(propertyDef); foreach (IMethodReference accessorMethod in propertyDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == propertyDef.Setter) { semantics = MethodSemanticsAttributes.Setter; } else if (accessorMethod == propertyDef.Getter) { semantics = MethodSemanticsAttributes.Getter; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } foreach (IEventDefinition eventDef in this.GetEventDefs()) { var association = GetEventDefinitionHandle(eventDef); foreach (IMethodReference accessorMethod in eventDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == eventDef.Adder) { semantics = MethodSemanticsAttributes.Adder; } else if (accessorMethod == eventDef.Remover) { semantics = MethodSemanticsAttributes.Remover; } else if (accessorMethod == eventDef.Caller) { semantics = MethodSemanticsAttributes.Raiser; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } } private void PopulateModuleRefTableRows() { var moduleRefs = this.GetModuleRefs(); metadata.SetCapacity(TableIndex.ModuleRef, moduleRefs.Count); foreach (string moduleName in moduleRefs) { metadata.AddModuleReference(GetStringHandleForPathAndCheckLength(moduleName)); } } private void PopulateModuleTableRow(out Blob mvidFixup) { CheckPathLength(this.module.ModuleName); GuidHandle mvidHandle; Guid mvid = this.module.SerializationProperties.PersistentIdentifier; if (mvid != default(Guid)) { // MVID is specified upfront when emitting EnC delta: mvidHandle = metadata.GetOrAddGuid(mvid); mvidFixup = default(Blob); } else { // The guid will be filled in later: var reservedGuid = metadata.ReserveGuid(); mvidFixup = reservedGuid.Content; mvidHandle = reservedGuid.Handle; reservedGuid.CreateWriter().WriteBytes(0, mvidFixup.Length); } metadata.AddModule( generation: this.Generation, moduleName: metadata.GetOrAddString(this.module.ModuleName), mvid: mvidHandle, encId: metadata.GetOrAddGuid(EncId), encBaseId: metadata.GetOrAddGuid(EncBaseId)); } private void PopulateParamTableRows() { var parameterDefs = this.GetParameterDefs(); metadata.SetCapacity(TableIndex.Param, parameterDefs.Count); foreach (IParameterDefinition parDef in parameterDefs) { metadata.AddParameter( attributes: GetParameterAttributes(parDef), sequenceNumber: (parDef is ReturnValueParameter) ? 0 : parDef.Index + 1, name: GetStringHandleForNameAndCheckLength(parDef.Name, parDef)); } } private void PopulatePropertyTableRows() { var propertyDefs = this.GetPropertyDefs(); metadata.SetCapacity(TableIndex.Property, propertyDefs.Count); foreach (IPropertyDefinition propertyDef in propertyDefs) { metadata.AddProperty( attributes: GetPropertyAttributes(propertyDef), name: GetStringHandleForNameAndCheckLength(propertyDef.Name, propertyDef), signature: GetPropertySignatureHandle(propertyDef)); } } private void PopulateTypeDefTableRows() { var typeDefs = this.GetTypeDefs(); metadata.SetCapacity(TableIndex.TypeDef, typeDefs.Count); foreach (INamedTypeDefinition typeDef in typeDefs) { INamespaceTypeDefinition namespaceType = typeDef.AsNamespaceTypeDefinition(Context); var moduleBuilder = Context.Module; int generation = moduleBuilder.GetTypeDefinitionGeneration(typeDef); string mangledTypeName = GetMangledName(typeDef, generation); ITypeReference baseType = typeDef.GetBaseClass(Context); metadata.AddTypeDefinition( attributes: GetTypeAttributes(typeDef), @namespace: (namespaceType != null) ? GetStringHandleForNamespaceAndCheckLength(namespaceType, mangledTypeName) : default(StringHandle), name: GetStringHandleForNameAndCheckLength(mangledTypeName, typeDef), baseType: (baseType != null) ? GetTypeHandle(baseType) : default(EntityHandle), fieldList: GetFirstFieldDefinitionHandle(typeDef), methodList: GetFirstMethodDefinitionHandle(typeDef)); } } private void PopulateNestedClassTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { continue; } metadata.AddNestedType( type: GetTypeDefinitionHandle(typeDef), enclosingType: GetTypeDefinitionHandle(nestedTypeDef.ContainingTypeDefinition)); } } private void PopulateClassLayoutTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (typeDef.Alignment == 0 && typeDef.SizeOf == 0) { continue; } metadata.AddTypeLayout( type: GetTypeDefinitionHandle(typeDef), packingSize: typeDef.Alignment, size: typeDef.SizeOf); } } private void PopulateTypeRefTableRows() { var typeRefs = this.GetTypeRefs(); metadata.SetCapacity(TableIndex.TypeRef, typeRefs.Count); foreach (ITypeReference typeRef in typeRefs) { EntityHandle resolutionScope; StringHandle name; StringHandle @namespace; INestedTypeReference nestedTypeRef = typeRef.AsNestedTypeReference; if (nestedTypeRef != null) { ITypeReference scopeTypeRef; ISpecializedNestedTypeReference sneTypeRef = nestedTypeRef.AsSpecializedNestedTypeReference; if (sneTypeRef != null) { scopeTypeRef = sneTypeRef.GetUnspecializedVersion(Context).GetContainingType(Context); } else { scopeTypeRef = nestedTypeRef.GetContainingType(Context); } resolutionScope = GetTypeReferenceHandle(scopeTypeRef); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(nestedTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, nestedTypeRef); @namespace = default(StringHandle); } else { INamespaceTypeReference namespaceTypeRef = typeRef.AsNamespaceTypeReference; if (namespaceTypeRef == null) { throw ExceptionUtilities.UnexpectedValue(typeRef); } resolutionScope = this.GetResolutionScopeHandle(namespaceTypeRef.GetUnit(Context)); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); @namespace = this.GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); } metadata.AddTypeReference( resolutionScope: resolutionScope, @namespace: @namespace, name: name); } } private void PopulateTypeSpecTableRows() { var typeSpecs = this.GetTypeSpecs(); metadata.SetCapacity(TableIndex.TypeSpec, typeSpecs.Count); foreach (ITypeReference typeSpec in typeSpecs) { metadata.AddTypeSpecification(GetTypeSpecSignatureIndex(typeSpec)); } } private void PopulateStandaloneSignatures() { var signatures = GetStandaloneSignatureBlobHandles(); foreach (BlobHandle signature in signatures) { metadata.AddStandaloneSignature(signature); } } private int[] SerializeThrowNullMethodBodies(BlobBuilder ilBuilder) { Debug.Assert(MetadataOnly); var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; int bodyOffsetCache = -1; int methodRid = 0; foreach (IMethodDefinition method in methods) { if (method.HasBody()) { if (bodyOffsetCache == -1) { bodyOffsetCache = ilBuilder.Count; ilBuilder.WriteBytes(ThrowNullEncodedBody); } bodyOffsets[methodRid] = bodyOffsetCache; } else { bodyOffsets[methodRid] = -1; } methodRid++; } return bodyOffsets; } private int[] SerializeMethodBodies(BlobBuilder ilBuilder, PdbWriter nativePdbWriterOpt, out Blob mvidStringFixup) { CustomDebugInfoWriter customDebugInfoWriter = (nativePdbWriterOpt != null) ? new CustomDebugInfoWriter(nativePdbWriterOpt) : null; var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; var lastLocalVariableHandle = default(LocalVariableHandle); var lastLocalConstantHandle = default(LocalConstantHandle); var encoder = new MethodBodyStreamEncoder(ilBuilder); var mvidStringHandle = default(UserStringHandle); mvidStringFixup = default(Blob); int methodRid = 1; foreach (IMethodDefinition method in methods) { _cancellationToken.ThrowIfCancellationRequested(); int bodyOffset; IMethodBody body; StandaloneSignatureHandle localSignatureHandleOpt; if (method.HasBody()) { body = method.GetBody(Context); if (body != null) { localSignatureHandleOpt = this.SerializeLocalVariablesSignature(body); // TODO: consider parallelizing these (local signature tokens can be piped into IL serialization & debug info generation) bodyOffset = SerializeMethodBody(encoder, body, localSignatureHandleOpt, ref mvidStringHandle, ref mvidStringFixup); nativePdbWriterOpt?.SerializeDebugInfo(body, localSignatureHandleOpt, customDebugInfoWriter); } else { bodyOffset = 0; localSignatureHandleOpt = default(StandaloneSignatureHandle); } } else { // 0 is actually written to metadata when the row is serialized bodyOffset = -1; body = null; localSignatureHandleOpt = default(StandaloneSignatureHandle); } if (_debugMetadataOpt != null) { // methodRid is based on this delta but for async state machine debug info we need the "real" row number // of the method aggregated across generations var aggregateMethodRid = MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(method)); SerializeMethodDebugInfo(body, methodRid, aggregateMethodRid, localSignatureHandleOpt, ref lastLocalVariableHandle, ref lastLocalConstantHandle); } _dynamicAnalysisDataWriterOpt?.SerializeMethodDynamicAnalysisData(body); bodyOffsets[methodRid - 1] = bodyOffset; methodRid++; } return bodyOffsets; } private int SerializeMethodBody(MethodBodyStreamEncoder encoder, IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { int ilLength = methodBody.IL.Length; var exceptionRegions = methodBody.ExceptionRegions; bool isSmallBody = ilLength < 64 && methodBody.MaxStack <= 8 && localSignatureHandleOpt.IsNil && exceptionRegions.Length == 0; var smallBodyKey = (methodBody.IL, methodBody.AreLocalsZeroed); // Check if an identical method body has already been serialized. // If so, use the RVA of the already serialized one. // Note that we don't need to rewrite the fake tokens in the body before looking it up. // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 int bodyOffset; if (!_deterministic && isSmallBody && _smallMethodBodies.TryGetValue(smallBodyKey, out bodyOffset)) { return bodyOffset; } var encodedBody = encoder.AddMethodBody( codeSize: methodBody.IL.Length, maxStack: methodBody.MaxStack, exceptionRegionCount: exceptionRegions.Length, hasSmallExceptionRegions: MayUseSmallExceptionHeaders(exceptionRegions), localVariablesSignature: localSignatureHandleOpt, attributes: (methodBody.AreLocalsZeroed ? MethodBodyAttributes.InitLocals : 0), hasDynamicStackAllocation: methodBody.HasStackalloc); // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 if (isSmallBody && !_deterministic) { _smallMethodBodies.Add(smallBodyKey, encodedBody.Offset); } WriteInstructions(encodedBody.Instructions, methodBody.IL, ref mvidStringHandle, ref mvidStringFixup); SerializeMethodBodyExceptionHandlerTable(encodedBody.ExceptionRegions, exceptionRegions); return encodedBody.Offset; } /// <summary> /// Serialize the method local signature to the blob. /// </summary> /// <returns>Standalone signature token</returns> protected virtual StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) { Debug.Assert(!_tableIndicesAreComplete); var localVariables = body.LocalVariables; if (localVariables.Length == 0) { return default(StandaloneSignatureHandle); } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).LocalVariableSignature(localVariables.Length); foreach (ILocalDefinition local in localVariables) { SerializeLocalVariableType(encoder.AddVariable(), local); } BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var handle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return handle; } protected void SerializeLocalVariableType(LocalVariableTypeEncoder encoder, ILocalDefinition local) { if (local.CustomModifiers.Length > 0) { SerializeCustomModifiers(encoder.CustomModifiers(), local.CustomModifiers); } if (module.IsPlatformType(local.Type, PlatformType.SystemTypedReference)) { encoder.TypedReference(); return; } SerializeTypeReference(encoder.Type(local.IsReference, local.IsPinned), local.Type); } internal StandaloneSignatureHandle SerializeLocalConstantStandAloneSignature(ILocalDefinition localConstant) { var builder = PooledBlobBuilder.GetInstance(); var typeEncoder = new BlobEncoder(builder).FieldSignature(); if (localConstant.CustomModifiers.Length > 0) { SerializeCustomModifiers(typeEncoder.CustomModifiers(), localConstant.CustomModifiers); } SerializeTypeReference(typeEncoder, localConstant.Type); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var signatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return signatureHandle; } private static byte ReadByte(ImmutableArray<byte> buffer, int pos) { return buffer[pos]; } private static int ReadInt32(ImmutableArray<byte> buffer, int pos) { return buffer[pos] | buffer[pos + 1] << 8 | buffer[pos + 2] << 16 | buffer[pos + 3] << 24; } private EntityHandle GetHandle(object reference) { return reference switch { ITypeReference typeReference => GetTypeHandle(typeReference), IFieldReference fieldReference => GetFieldHandle(fieldReference), IMethodReference methodReference => GetMethodHandle(methodReference), ISignature signature => GetStandaloneSignatureHandle(signature), _ => throw ExceptionUtilities.UnexpectedValue(reference) }; } private EntityHandle ResolveEntityHandleFromPseudoToken(int pseudoSymbolToken) { int index = pseudoSymbolToken; var entity = _pseudoSymbolTokenToReferenceMap[index]; if (entity != null) { // EDMAURER since method bodies are not visited as they are in CCI, the operations // that would have been done on them are done here. if (entity is IReference reference) { _referenceVisitor.VisitMethodBodyReference(reference); } else if (entity is ISignature signature) { _referenceVisitor.VisitSignature(signature); } EntityHandle handle = GetHandle(entity); _pseudoSymbolTokenToTokenMap[index] = handle; _pseudoSymbolTokenToReferenceMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoSymbolTokenToTokenMap[index]; } private UserStringHandle ResolveUserStringHandleFromPseudoToken(int pseudoStringToken) { int index = pseudoStringToken; var str = _pseudoStringTokenToStringMap[index]; if (str != null) { var handle = GetOrAddUserString(str); _pseudoStringTokenToTokenMap[index] = handle; _pseudoStringTokenToStringMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoStringTokenToTokenMap[index]; } private UserStringHandle GetOrAddUserString(string str) { if (!_userStringTokenOverflow) { try { return metadata.GetOrAddUserString(str); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(UserStringHandle); } private ReservedBlob<UserStringHandle> ReserveUserString(int length) { if (!_userStringTokenOverflow) { try { return metadata.ReserveUserString(length); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(ReservedBlob<UserStringHandle>); } internal const uint LiteralMethodDefinitionToken = 0x80000000; internal const uint LiteralGreatestMethodDefinitionToken = 0x40000000; internal const uint SourceDocumentIndex = 0x20000000; internal const uint ModuleVersionIdStringToken = 0x80000000; private void WriteInstructions(Blob finalIL, ImmutableArray<byte> generatedIL, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { // write the raw body first and then patch tokens: var writer = new BlobWriter(finalIL); writer.WriteBytes(generatedIL); writer.Offset = 0; int offset = 0; while (offset < generatedIL.Length) { var operandType = InstructionOperandTypes.ReadOperandType(generatedIL, ref offset); switch (operandType) { case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineSig: { int pseudoToken = ReadInt32(generatedIL, offset); int token = 0; // If any bits in the high-order byte of the pseudotoken are nonzero, replace the opcode with Ldc_i4 // and either clear the high-order byte in the pseudotoken or ignore the pseudotoken. // This is a trick to enable loading raw metadata token indices as integers. if (operandType == OperandType.InlineTok) { int tokenMask = pseudoToken & unchecked((int)0xff000000); if (tokenMask != 0 && (uint)pseudoToken != 0xffffffff) { Debug.Assert(ReadByte(generatedIL, offset - 1) == (byte)ILOpCode.Ldtoken); writer.Offset = offset - 1; writer.WriteByte((byte)ILOpCode.Ldc_i4); switch ((uint)tokenMask) { case LiteralMethodDefinitionToken: // Crash the compiler if pseudo token fails to resolve to a MethodDefinitionHandle. var handle = (MethodDefinitionHandle)ResolveEntityHandleFromPseudoToken(pseudoToken & 0x00ffffff); token = MetadataTokens.GetToken(handle) & 0x00ffffff; break; case LiteralGreatestMethodDefinitionToken: token = GreatestMethodDefIndex; break; case SourceDocumentIndex: token = _dynamicAnalysisDataWriterOpt.GetOrAddDocument(((CommonPEModuleBuilder)module).GetSourceDocumentFromIndex((uint)(pseudoToken & 0x00ffffff))); break; default: throw ExceptionUtilities.UnexpectedValue(tokenMask); } } } writer.Offset = offset; writer.WriteInt32(token == 0 ? MetadataTokens.GetToken(ResolveEntityHandleFromPseudoToken(pseudoToken)) : token); offset += 4; break; } case OperandType.InlineString: { writer.Offset = offset; int pseudoToken = ReadInt32(generatedIL, offset); UserStringHandle handle; if ((uint)pseudoToken == ModuleVersionIdStringToken) { // The pseudotoken encoding indicates that the string should refer to a textual encoding of the // current module's module version ID (such that the MVID can be realized using Guid.Parse). // The value cannot be determined until very late in the compilation, so reserve a slot for it now and fill in the value later. if (mvidStringHandle.IsNil) { const int guidStringLength = 36; Debug.Assert(guidStringLength == default(Guid).ToString().Length); var reserved = ReserveUserString(guidStringLength); mvidStringHandle = reserved.Handle; mvidStringFixup = reserved.Content; } handle = mvidStringHandle; } else { handle = ResolveUserStringHandleFromPseudoToken(pseudoToken); } writer.WriteInt32(MetadataTokens.GetToken(handle)); offset += 4; break; } case OperandType.InlineBrTarget: case OperandType.InlineI: case OperandType.ShortInlineR: offset += 4; break; case OperandType.InlineSwitch: int argCount = ReadInt32(generatedIL, offset); // skip switch arguments count and arguments offset += (argCount + 1) * 4; break; case OperandType.InlineI8: case OperandType.InlineR: offset += 8; break; case OperandType.InlineNone: break; case OperandType.InlineVar: offset += 2; break; case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineI: case OperandType.ShortInlineVar: offset += 1; break; default: throw ExceptionUtilities.UnexpectedValue(operandType); } } } private void SerializeMethodBodyExceptionHandlerTable(ExceptionRegionEncoder encoder, ImmutableArray<ExceptionHandlerRegion> regions) { foreach (var region in regions) { var exceptionType = region.ExceptionType; encoder.Add( region.HandlerKind, region.TryStartOffset, region.TryLength, region.HandlerStartOffset, region.HandlerLength, (exceptionType != null) ? GetTypeHandle(exceptionType) : default(EntityHandle), region.FilterDecisionStartOffset); } } private static bool MayUseSmallExceptionHeaders(ImmutableArray<ExceptionHandlerRegion> exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallRegionCount(exceptionRegions.Length)) { return false; } foreach (var region in exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallExceptionRegion(region.TryStartOffset, region.TryLength) || !ExceptionRegionEncoder.IsSmallExceptionRegion(region.HandlerStartOffset, region.HandlerLength)) { return false; } } return true; } private void SerializeParameterInformation(ParameterTypeEncoder encoder, IParameterTypeInformation parameterTypeInformation) { var type = parameterTypeInformation.GetType(Context); if (module.IsPlatformType(type, PlatformType.SystemTypedReference)) { Debug.Assert(!parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); encoder.TypedReference(); } else { Debug.Assert(parameterTypeInformation.RefCustomModifiers.Length == 0 || parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.RefCustomModifiers); var typeEncoder = encoder.Type(parameterTypeInformation.IsByReference); SerializeCustomModifiers(typeEncoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); SerializeTypeReference(typeEncoder, type); } } private void SerializeFieldSignature(IFieldReference fieldReference, BlobBuilder builder) { var typeEncoder = new BlobEncoder(builder).FieldSignature(); SerializeTypeReference(typeEncoder, fieldReference.GetType(Context)); } private void SerializeMethodSpecificationSignature(BlobBuilder builder, IGenericMethodInstanceReference genericMethodInstanceReference) { var argsEncoder = new BlobEncoder(builder).MethodSpecificationSignature(genericMethodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference genericArgument in genericMethodInstanceReference.GetGenericArguments(Context)) { ITypeReference typeRef = genericArgument; SerializeTypeReference(argsEncoder.AddArgument(), typeRef); } } private void SerializeCustomAttributeSignature(ICustomAttribute customAttribute, BlobBuilder builder) { var parameters = customAttribute.Constructor(Context, reportDiagnostics: false).GetParameters(Context); var arguments = customAttribute.GetArguments(Context); Debug.Assert(parameters.Length == arguments.Length); FixedArgumentsEncoder fixedArgsEncoder; CustomAttributeNamedArgumentsEncoder namedArgsEncoder; new BlobEncoder(builder).CustomAttributeSignature(out fixedArgsEncoder, out namedArgsEncoder); for (int i = 0; i < parameters.Length; i++) { SerializeMetadataExpression(fixedArgsEncoder.AddArgument(), arguments[i], parameters[i].GetType(Context)); } SerializeCustomAttributeNamedArguments(namedArgsEncoder.Count(customAttribute.NamedArgumentCount), customAttribute); } private void SerializeCustomAttributeNamedArguments(NamedArgumentsEncoder encoder, ICustomAttribute customAttribute) { foreach (IMetadataNamedArgument namedArgument in customAttribute.GetNamedArguments(Context)) { NamedArgumentTypeEncoder typeEncoder; NameEncoder nameEncoder; LiteralEncoder literalEncoder; encoder.AddArgument(namedArgument.IsField, out typeEncoder, out nameEncoder, out literalEncoder); SerializeNamedArgumentType(typeEncoder, namedArgument.Type); nameEncoder.Name(namedArgument.ArgumentName); SerializeMetadataExpression(literalEncoder, namedArgument.ArgumentValue, namedArgument.Type); } } private void SerializeNamedArgumentType(NamedArgumentTypeEncoder encoder, ITypeReference type) { if (type is IArrayTypeReference arrayType) { SerializeCustomAttributeArrayType(encoder.SZArray(), arrayType); } else if (module.IsPlatformType(type, PlatformType.SystemObject)) { encoder.Object(); } else { SerializeCustomAttributeElementType(encoder.ScalarType(), type); } } private void SerializeMetadataExpression(LiteralEncoder encoder, IMetadataExpression expression, ITypeReference targetType) { if (expression is MetadataCreateArray a) { ITypeReference targetElementType; VectorEncoder vectorEncoder; if (!(targetType is IArrayTypeReference targetArrayType)) { // implicit conversion from array to object Debug.Assert(this.module.IsPlatformType(targetType, PlatformType.SystemObject)); CustomAttributeArrayTypeEncoder arrayTypeEncoder; encoder.TaggedVector(out arrayTypeEncoder, out vectorEncoder); SerializeCustomAttributeArrayType(arrayTypeEncoder, a.ArrayType); targetElementType = a.ElementType; } else { vectorEncoder = encoder.Vector(); // In FixedArg the element type of the parameter array has to match the element type of the argument array, // but in NamedArg T[] can be assigned to object[]. In that case we need to encode the arguments using // the parameter element type not the argument element type. targetElementType = targetArrayType.GetElementType(this.Context); } var literalsEncoder = vectorEncoder.Count(a.Elements.Length); foreach (IMetadataExpression elemValue in a.Elements) { SerializeMetadataExpression(literalsEncoder.AddLiteral(), elemValue, targetElementType); } } else { ScalarEncoder scalarEncoder; MetadataConstant c = expression as MetadataConstant; if (this.module.IsPlatformType(targetType, PlatformType.SystemObject)) { CustomAttributeElementTypeEncoder typeEncoder; encoder.TaggedScalar(out typeEncoder, out scalarEncoder); // special case null argument assigned to Object parameter - treat as null string if (c != null && c.Value == null && this.module.IsPlatformType(c.Type, PlatformType.SystemObject)) { typeEncoder.String(); } else { SerializeCustomAttributeElementType(typeEncoder, expression.Type); } } else { scalarEncoder = encoder.Scalar(); } if (c != null) { if (c.Type is IArrayTypeReference) { scalarEncoder.NullArray(); return; } Debug.Assert(!module.IsPlatformType(c.Type, PlatformType.SystemType) || c.Value == null); scalarEncoder.Constant(c.Value); } else { scalarEncoder.SystemType(((MetadataTypeOf)expression).TypeToGet.GetSerializedTypeName(Context)); } } } private void SerializeMarshallingDescriptor(IMarshallingInformation marshallingInformation, BlobBuilder writer) { writer.WriteCompressedInteger((int)marshallingInformation.UnmanagedType); switch (marshallingInformation.UnmanagedType) { case UnmanagedType.ByValArray: // NATIVE_TYPE_FIXEDARRAY Debug.Assert(marshallingInformation.NumberOfElements >= 0); writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); if (marshallingInformation.ElementType >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.ElementType); } break; case Constants.UnmanagedType_CustomMarshaler: writer.WriteUInt16(0); // padding object marshaller = marshallingInformation.GetCustomMarshaller(Context); switch (marshaller) { case ITypeReference marshallerTypeRef: this.SerializeTypeName(marshallerTypeRef, writer); break; case null: writer.WriteByte(0); break; default: writer.WriteSerializedString((string)marshaller); break; } var arg = marshallingInformation.CustomMarshallerRuntimeArgument; if (arg != null) { writer.WriteSerializedString(arg); } else { writer.WriteByte(0); } break; case UnmanagedType.LPArray: // NATIVE_TYPE_ARRAY Debug.Assert(marshallingInformation.ElementType >= 0); writer.WriteCompressedInteger((int)marshallingInformation.ElementType); if (marshallingInformation.ParamIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.ParamIndex); if (marshallingInformation.NumberOfElements >= 0) { writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(1); // The parameter number is valid } } else if (marshallingInformation.NumberOfElements >= 0) { writer.WriteByte(0); // Dummy parameter value emitted so that NumberOfElements can be in a known position writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(0); // The parameter number is not valid } break; case Constants.UnmanagedType_SafeArray: if (marshallingInformation.SafeArrayElementSubtype >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.SafeArrayElementSubtype); var elementType = marshallingInformation.GetSafeArrayElementUserDefinedSubtype(Context); if (elementType != null) { this.SerializeTypeName(elementType, writer); } } break; case UnmanagedType.ByValTStr: // NATIVE_TYPE_FIXEDSYSSTRING writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); break; case UnmanagedType.Interface: case Constants.UnmanagedType_IDispatch: case UnmanagedType.IUnknown: if (marshallingInformation.IidParameterIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.IidParameterIndex); } break; } } private void SerializeTypeName(ITypeReference typeReference, BlobBuilder writer) { writer.WriteSerializedString(typeReference.GetSerializedTypeName(this.Context)); } /// <summary> /// Computes the string representing the strong name of the given assembly reference. /// </summary> internal static string StrongName(IAssemblyReference assemblyReference) { var identity = assemblyReference.Identity; var pooled = PooledStringBuilder.GetInstance(); StringBuilder sb = pooled.Builder; sb.Append(identity.Name); sb.AppendFormat(CultureInfo.InvariantCulture, ", Version={0}.{1}.{2}.{3}", identity.Version.Major, identity.Version.Minor, identity.Version.Build, identity.Version.Revision); if (!string.IsNullOrEmpty(identity.CultureName)) { sb.AppendFormat(CultureInfo.InvariantCulture, ", Culture={0}", identity.CultureName); } else { sb.Append(", Culture=neutral"); } sb.Append(", PublicKeyToken="); if (identity.PublicKeyToken.Length > 0) { foreach (byte b in identity.PublicKeyToken) { sb.Append(b.ToString("x2")); } } else { sb.Append("null"); } if (identity.IsRetargetable) { sb.Append(", Retargetable=Yes"); } if (identity.ContentType == AssemblyContentType.WindowsRuntime) { sb.Append(", ContentType=WindowsRuntime"); } else { Debug.Assert(identity.ContentType == AssemblyContentType.Default); } return pooled.ToStringAndFree(); } private void SerializePermissionSet(ImmutableArray<ICustomAttribute> permissionSet, BlobBuilder writer) { EmitContext context = this.Context; foreach (ICustomAttribute customAttribute in permissionSet) { bool isAssemblyQualified = true; string typeName = customAttribute.GetType(context).GetSerializedTypeName(context, ref isAssemblyQualified); if (!isAssemblyQualified) { INamespaceTypeReference namespaceType = customAttribute.GetType(context).AsNamespaceTypeReference; if (namespaceType?.GetUnit(context) is IAssemblyReference referencedAssembly) { typeName = typeName + ", " + StrongName(referencedAssembly); } } writer.WriteSerializedString(typeName); var customAttributeArgsBuilder = PooledBlobBuilder.GetInstance(); var namedArgsEncoder = new BlobEncoder(customAttributeArgsBuilder).PermissionSetArguments(customAttribute.NamedArgumentCount); SerializeCustomAttributeNamedArguments(namedArgsEncoder, customAttribute); writer.WriteCompressedInteger(customAttributeArgsBuilder.Count); customAttributeArgsBuilder.WriteContentTo(writer); customAttributeArgsBuilder.Free(); } // TODO: xml for older platforms } private void SerializeReturnValueAndParameters(MethodSignatureEncoder encoder, ISignature signature, ImmutableArray<IParameterTypeInformation> varargParameters) { var declaredParameters = signature.GetParameters(Context); var returnType = signature.GetType(Context); ReturnTypeEncoder returnTypeEncoder; ParametersEncoder parametersEncoder; encoder.Parameters(declaredParameters.Length + varargParameters.Length, out returnTypeEncoder, out parametersEncoder); if (module.IsPlatformType(returnType, PlatformType.SystemTypedReference)) { Debug.Assert(!signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.TypedReference(); } else if (module.IsPlatformType(returnType, PlatformType.SystemVoid)) { Debug.Assert(!signature.ReturnValueIsByRef); Debug.Assert(signature.RefCustomModifiers.IsEmpty); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.Void(); } else { Debug.Assert(signature.RefCustomModifiers.IsEmpty || signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.RefCustomModifiers); var typeEncoder = returnTypeEncoder.Type(signature.ReturnValueIsByRef); SerializeCustomModifiers(typeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); SerializeTypeReference(typeEncoder, returnType); } foreach (IParameterTypeInformation parameter in declaredParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } if (varargParameters.Length > 0) { parametersEncoder = parametersEncoder.StartVarArgs(); foreach (IParameterTypeInformation parameter in varargParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } } } private void SerializeTypeReference(SignatureTypeEncoder encoder, ITypeReference typeReference) { while (true) { // TYPEDREF is only allowed in RetType, Param, LocalVarSig signatures Debug.Assert(!module.IsPlatformType(typeReference, PlatformType.SystemTypedReference)); if (typeReference is IModifiedTypeReference modifiedTypeReference) { SerializeCustomModifiers(encoder.CustomModifiers(), modifiedTypeReference.CustomModifiers); typeReference = modifiedTypeReference.UnmodifiedType; continue; } var primitiveType = typeReference.TypeCode; switch (primitiveType) { case PrimitiveTypeCode.Pointer: case PrimitiveTypeCode.FunctionPointer: case PrimitiveTypeCode.NotPrimitive: break; default: SerializePrimitiveType(encoder, primitiveType); return; } if (typeReference is IPointerTypeReference pointerTypeReference) { typeReference = pointerTypeReference.GetTargetType(Context); encoder = encoder.Pointer(); continue; } if (typeReference is IFunctionPointerTypeReference functionPointerTypeReference) { var signature = functionPointerTypeReference.Signature; var signatureEncoder = encoder.FunctionPointer(convention: signature.CallingConvention.ToSignatureConvention()); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); return; } IGenericTypeParameterReference genericTypeParameterReference = typeReference.AsGenericTypeParameterReference; if (genericTypeParameterReference != null) { encoder.GenericTypeParameter( GetNumberOfInheritedTypeParameters(genericTypeParameterReference.DefiningType) + genericTypeParameterReference.Index); return; } if (typeReference is IArrayTypeReference arrayTypeReference) { typeReference = arrayTypeReference.GetElementType(Context); if (arrayTypeReference.IsSZArray) { encoder = encoder.SZArray(); continue; } else { SignatureTypeEncoder elementType; ArrayShapeEncoder arrayShape; encoder.Array(out elementType, out arrayShape); SerializeTypeReference(elementType, typeReference); arrayShape.Shape(arrayTypeReference.Rank, arrayTypeReference.Sizes, arrayTypeReference.LowerBounds); return; } } if (module.IsPlatformType(typeReference, PlatformType.SystemObject)) { encoder.Object(); return; } IGenericMethodParameterReference genericMethodParameterReference = typeReference.AsGenericMethodParameterReference; if (genericMethodParameterReference != null) { encoder.GenericMethodTypeParameter(genericMethodParameterReference.Index); return; } if (typeReference.IsTypeSpecification()) { ITypeReference uninstantiatedTypeReference = typeReference.GetUninstantiatedGenericType(Context); // Roslyn's uninstantiated type is the same object as the instantiated type for // types closed over their type parameters, so to speak. var consolidatedTypeArguments = ArrayBuilder<ITypeReference>.GetInstance(); typeReference.GetConsolidatedTypeArguments(consolidatedTypeArguments, this.Context); var genericArgsEncoder = encoder.GenericInstantiation( GetTypeHandle(uninstantiatedTypeReference, treatRefAsPotentialTypeSpec: false), consolidatedTypeArguments.Count, typeReference.IsValueType); foreach (ITypeReference typeArgument in consolidatedTypeArguments) { SerializeTypeReference(genericArgsEncoder.AddArgument(), typeArgument); } consolidatedTypeArguments.Free(); return; } encoder.Type(GetTypeHandle(typeReference), typeReference.IsValueType); return; } } private static void SerializePrimitiveType(SignatureTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.IntPtr: encoder.IntPtr(); break; case PrimitiveTypeCode.UIntPtr: encoder.UIntPtr(); break; case PrimitiveTypeCode.String: encoder.String(); break; case PrimitiveTypeCode.Void: // "void" is handled specifically for "void*" with custom modifiers. // If SignatureTypeEncoder supports such cases directly, this can // be removed. See https://github.com/dotnet/corefx/issues/14571. encoder.Builder.WriteByte((byte)System.Reflection.Metadata.PrimitiveTypeCode.Void); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomAttributeArrayType(CustomAttributeArrayTypeEncoder encoder, IArrayTypeReference arrayTypeReference) { // A single-dimensional, zero-based array is specified as a single byte 0x1D followed by the FieldOrPropType of the element type. // only non-jagged SZ arrays are allowed in attributes // (need to encode the type of the SZ array if the parameter type is Object): Debug.Assert(arrayTypeReference.IsSZArray); var elementType = arrayTypeReference.GetElementType(Context); Debug.Assert(!(elementType is IModifiedTypeReference)); if (module.IsPlatformType(elementType, PlatformType.SystemObject)) { encoder.ObjectArray(); } else { SerializeCustomAttributeElementType(encoder.ElementType(), elementType); } } private void SerializeCustomAttributeElementType(CustomAttributeElementTypeEncoder encoder, ITypeReference typeReference) { // Spec: // The FieldOrPropType shall be exactly one of: // ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1, ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, // ELEMENT_TYPE_U4, ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, ELEMENT_TYPE_STRING. // An enum is specified as a single byte 0x55 followed by a SerString. var primitiveType = typeReference.TypeCode; if (primitiveType != PrimitiveTypeCode.NotPrimitive) { SerializePrimitiveType(encoder, primitiveType); } else if (module.IsPlatformType(typeReference, PlatformType.SystemType)) { encoder.SystemType(); } else { Debug.Assert(typeReference.IsEnum); encoder.Enum(typeReference.GetSerializedTypeName(this.Context)); } } private static void SerializePrimitiveType(CustomAttributeElementTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.String: encoder.String(); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomModifiers(CustomModifiersEncoder encoder, ImmutableArray<ICustomModifier> modifiers) { foreach (var modifier in modifiers) { encoder = encoder.AddModifier(GetTypeHandle(modifier.GetModifier(Context)), modifier.IsOptional); } } private int GetNumberOfInheritedTypeParameters(ITypeReference type) { INestedTypeReference nestedType = type.AsNestedTypeReference; if (nestedType == null) { return 0; } ISpecializedNestedTypeReference specializedNestedType = nestedType.AsSpecializedNestedTypeReference; if (specializedNestedType != null) { nestedType = specializedNestedType.GetUnspecializedVersion(Context); } int result = 0; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; while (nestedType != null) { result += nestedType.GenericParameterCount; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; } result += type.AsNamespaceTypeReference.GenericParameterCount; return result; } internal static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(IMethodBody methodBody) { ImmutableArray<LocalSlotDebugInfo> encLocalSlots; // Kickoff method of a state machine (async/iterator method) doesn't have any interesting locals, // so we use its EnC method debug info to store information about locals hoisted to the state machine. var encSlotInfo = methodBody.StateMachineHoistedLocalSlots; if (encSlotInfo.IsDefault) { encLocalSlots = GetLocalSlotDebugInfos(methodBody.LocalVariables); } else { encLocalSlots = GetLocalSlotDebugInfos(encSlotInfo); } return new EditAndContinueMethodDebugInformation(methodBody.MethodId.Ordinal, encLocalSlots, methodBody.ClosureDebugInfo, methodBody.LambdaDebugInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<ILocalDefinition> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<EncHoistedLocalInfo> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } protected abstract class HeapOrReferenceIndexBase<T> { private readonly MetadataWriter _writer; private readonly List<T> _rows; private readonly int _firstRowId; protected HeapOrReferenceIndexBase(MetadataWriter writer, int lastRowId) { _writer = writer; _rows = new List<T>(); _firstRowId = lastRowId + 1; } public abstract bool TryGetValue(T item, out int index); public int GetOrAdd(T item) { int index; if (!this.TryGetValue(item, out index)) { index = Add(item); } return index; } public IReadOnlyList<T> Rows { get { return _rows; } } public int Add(T item) { Debug.Assert(!_writer._tableIndicesAreComplete); #if DEBUG int i; Debug.Assert(!this.TryGetValue(item, out i)); #endif int index = _firstRowId + _rows.Count; this.AddItem(item, index); _rows.Add(item); return index; } protected abstract void AddItem(T item, int index); } protected sealed class HeapOrReferenceIndex<T> : HeapOrReferenceIndexBase<T> { private readonly Dictionary<T, int> _index; public HeapOrReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<T, int>(), lastRowId) { } private HeapOrReferenceIndex(MetadataWriter writer, Dictionary<T, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(T item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(T item, int index) { _index.Add(item, index); } } protected sealed class TypeReferenceIndex : HeapOrReferenceIndexBase<ITypeReference> { private readonly Dictionary<ITypeReference, int> _index; public TypeReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<ITypeReference, int>(ReferenceEqualityComparer.Instance), lastRowId) { } private TypeReferenceIndex(MetadataWriter writer, Dictionary<ITypeReference, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(ITypeReference item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(ITypeReference item, int index) { _index.Add(item, index); } } protected sealed class InstanceAndStructuralReferenceIndex<T> : HeapOrReferenceIndexBase<T> where T : class, IReference { private readonly Dictionary<T, int> _instanceIndex; private readonly Dictionary<T, int> _structuralIndex; public InstanceAndStructuralReferenceIndex(MetadataWriter writer, IEqualityComparer<T> structuralComparer, int lastRowId = 0) : base(writer, lastRowId) { _instanceIndex = new Dictionary<T, int>(ReferenceEqualityComparer.Instance); _structuralIndex = new Dictionary<T, int>(structuralComparer); } public override bool TryGetValue(T item, out int index) { if (_instanceIndex.TryGetValue(item, out index)) { return true; } if (_structuralIndex.TryGetValue(item, out index)) { _instanceIndex.Add(item, index); return true; } return false; } protected override void AddItem(T item, int index) { _instanceIndex.Add(item, index); _structuralIndex.Add(item, index); } } private class ByteSequenceBoolTupleComparer : IEqualityComparer<(ImmutableArray<byte>, bool)> { internal static readonly ByteSequenceBoolTupleComparer Instance = new ByteSequenceBoolTupleComparer(); private ByteSequenceBoolTupleComparer() { } bool IEqualityComparer<(ImmutableArray<byte>, bool)>.Equals((ImmutableArray<byte>, bool) x, (ImmutableArray<byte>, bool) y) { return x.Item2 == y.Item2 && ByteSequenceComparer.Equals(x.Item1, y.Item1); } int IEqualityComparer<(ImmutableArray<byte>, bool)>.GetHashCode((ImmutableArray<byte>, bool) x) { return Hash.Combine(ByteSequenceComparer.GetHashCode(x.Item1), x.Item2.GetHashCode()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.Cci { internal abstract partial class MetadataWriter { internal static readonly Encoding s_utf8Encoding = Encoding.UTF8; /// <summary> /// This is the maximum length of a type or member name in metadata, assuming /// the name is in UTF-8 format and not (yet) null-terminated. /// </summary> /// <remarks> /// Source names may have to be shorter still to accommodate mangling. /// Used for event names, field names, property names, field names, method def names, /// member ref names, type def (full) names, type ref (full) names, exported type /// (full) names, parameter names, manifest resource names, and unmanaged method names /// (ImplMap table). /// /// See CLI Part II, section 22. /// </remarks> internal const int NameLengthLimit = 1024 - 1; //MAX_CLASS_NAME = 1024 in dev11 /// <summary> /// This is the maximum length of a path in metadata, assuming the path is in UTF-8 /// format and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for file names, module names, and module ref names. /// /// See CLI Part II, section 22. /// </remarks> internal const int PathLengthLimit = 260 - 1; //MAX_PATH = 1024 in dev11 /// <summary> /// This is the maximum length of a string in the PDB, assuming it is in UTF-8 format /// and not (yet) null-terminated. /// </summary> /// <remarks> /// Used for import strings, locals, and local constants. /// </remarks> internal const int PdbLengthLimit = 2046; // Empirical, based on when ISymUnmanagedWriter2 methods start throwing. private readonly int _numTypeDefsEstimate; private readonly bool _deterministic; internal readonly bool MetadataOnly; internal readonly bool EmitTestCoverageData; // A map of method body before token translation to RVA. Used for deduplication of small bodies. private readonly Dictionary<(ImmutableArray<byte>, bool), int> _smallMethodBodies; private const byte TinyFormat = 2; private const int ThrowNullCodeSize = 2; private static readonly ImmutableArray<byte> ThrowNullEncodedBody = ImmutableArray.Create( (byte)((ThrowNullCodeSize << 2) | TinyFormat), (byte)ILOpCode.Ldnull, (byte)ILOpCode.Throw); protected MetadataWriter( MetadataBuilder metadata, MetadataBuilder debugMetadataOpt, DynamicAnalysisDataWriter dynamicAnalysisDataWriterOpt, EmitContext context, CommonMessageProvider messageProvider, bool metadataOnly, bool deterministic, bool emitTestCoverageData, CancellationToken cancellationToken) { Debug.Assert(metadata != debugMetadataOpt); this.module = context.Module; _deterministic = deterministic; this.MetadataOnly = metadataOnly; this.EmitTestCoverageData = emitTestCoverageData; // EDMAURER provide some reasonable size estimates for these that will avoid // much of the reallocation that would occur when growing these from empty. _signatureIndex = new Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>>(module.HintNumberOfMethodDefinitions, ReferenceEqualityComparer.Instance); //ignores field signatures _numTypeDefsEstimate = module.HintNumberOfMethodDefinitions / 6; this.Context = context; this.messageProvider = messageProvider; _cancellationToken = cancellationToken; this.metadata = metadata; _debugMetadataOpt = debugMetadataOpt; _dynamicAnalysisDataWriterOpt = dynamicAnalysisDataWriterOpt; _smallMethodBodies = new Dictionary<(ImmutableArray<byte>, bool), int>(ByteSequenceBoolTupleComparer.Instance); } private int NumberOfTypeDefsEstimate { get { return _numTypeDefsEstimate; } } /// <summary> /// Returns true if writing full metadata, false if writing delta. /// </summary> internal bool IsFullMetadata { get { return this.Generation == 0; } } /// <summary> /// True if writing delta metadata in a minimal format. /// </summary> private bool IsMinimalDelta { get { return !IsFullMetadata; } } /// <summary> /// NetModules and EnC deltas don't have AssemblyDef record. /// We don't emit it for EnC deltas since assembly identity has to be preserved across generations (CLR/debugger get confused otherwise). /// </summary> private bool EmitAssemblyDefinition => module.OutputKind != OutputKind.NetModule && !IsMinimalDelta; /// <summary> /// Returns metadata generation ordinal. Zero for /// full metadata and non-zero for delta. /// </summary> protected abstract ushort Generation { get; } /// <summary> /// Returns unique Guid for this delta, or default(Guid) /// if full metadata. /// </summary> protected abstract Guid EncId { get; } /// <summary> /// Returns Guid of previous delta, or default(Guid) /// if full metadata or generation 1 delta. /// </summary> protected abstract Guid EncBaseId { get; } /// <summary> /// Returns true and full metadata handle of the type definition /// if the type definition is recognized. Otherwise returns false. /// </summary> protected abstract bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle); /// <summary> /// Get full metadata handle of the type definition. /// </summary> protected abstract TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def); /// <summary> /// The type definition corresponding to full metadata type handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract ITypeDefinition GetTypeDef(TypeDefinitionHandle handle); /// <summary> /// The type definitions to be emitted, in row order. These /// are just the type definitions from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeDefinition> GetTypeDefs(); /// <summary> /// Get full metadata handle of the event definition. /// </summary> protected abstract EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def); /// <summary> /// The event definitions to be emitted, in row order. These /// are just the event definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IEventDefinition> GetEventDefs(); /// <summary> /// Get full metadata handle of the field definition. /// </summary> protected abstract FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def); /// <summary> /// The field definitions to be emitted, in row order. These /// are just the field definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IFieldDefinition> GetFieldDefs(); /// <summary> /// Returns true and handle of the method definition /// if the method definition is recognized. Otherwise returns false. /// The index is into the full metadata. /// </summary> protected abstract bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle); /// <summary> /// Get full metadata handle of the method definition. /// </summary> protected abstract MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def); /// <summary> /// The method definition corresponding to full metadata method handle. /// Deltas are only required to support indexing into current generation. /// </summary> protected abstract IMethodDefinition GetMethodDef(MethodDefinitionHandle handle); /// <summary> /// The method definitions to be emitted, in row order. These /// are just the method definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IMethodDefinition> GetMethodDefs(); /// <summary> /// Get full metadata handle of the property definition. /// </summary> protected abstract PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def); /// <summary> /// The property definitions to be emitted, in row order. These /// are just the property definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IPropertyDefinition> GetPropertyDefs(); /// <summary> /// The full metadata handle of the parameter definition. /// </summary> protected abstract ParameterHandle GetParameterHandle(IParameterDefinition def); /// <summary> /// The parameter definitions to be emitted, in row order. These /// are just the parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IParameterDefinition> GetParameterDefs(); /// <summary> /// The generic parameter definitions to be emitted, in row order. These /// are just the generic parameter definitions from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericParameter> GetGenericParameters(); /// <summary> /// The handle of the first field of the type. /// </summary> protected abstract FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first method of the type. /// </summary> protected abstract MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef); /// <summary> /// The handle of the first parameter of the method. /// </summary> protected abstract ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef); /// <summary> /// Return full metadata handle of the assembly reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference); /// <summary> /// The assembly references to be emitted, in row order. These /// are just the assembly references from the current generation. /// </summary> protected abstract IReadOnlyList<AssemblyIdentity> GetAssemblyRefs(); // ModuleRef table contains module names for TypeRefs that target types in netmodules (represented by IModuleReference), // and module names specified by P/Invokes (plain strings). Names in the table must be unique and are case sensitive. // // Spec 22.31 (ModuleRef : 0x1A) // "Name should match an entry in the Name column of the File table. Moreover, that entry shall enable the // CLI to locate the target module (typically it might name the file used to hold the module)" // // This is not how the Dev10 compilers and ILASM work. An entry is added to File table only for resources and netmodules. // Entries aren't added for P/Invoked modules. /// <summary> /// Return full metadata handle of the module reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference); /// <summary> /// The module references to be emitted, in row order. These /// are just the module references from the current generation. /// </summary> protected abstract IReadOnlyList<string> GetModuleRefs(); /// <summary> /// Return full metadata handle of the member reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference); /// <summary> /// The member references to be emitted, in row order. These /// are just the member references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeMemberReference> GetMemberRefs(); /// <summary> /// Return full metadata handle of the method spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference); /// <summary> /// The method specs to be emitted, in row order. These /// are just the method specs from the current generation. /// </summary> protected abstract IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs(); /// <summary> /// The greatest index given to any method definition. /// </summary> protected abstract int GreatestMethodDefIndex { get; } /// <summary> /// Return true and full metadata handle of the type reference /// if the reference is available in the current generation. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle); /// <summary> /// Return full metadata handle of the type reference, adding /// the reference to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference); /// <summary> /// The type references to be emitted, in row order. These /// are just the type references from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeRefs(); /// <summary> /// Returns full metadata handle of the type spec, adding /// the spec to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference); /// <summary> /// The type specs to be emitted, in row order. These /// are just the type specs from the current generation. /// </summary> protected abstract IReadOnlyList<ITypeReference> GetTypeSpecs(); /// <summary> /// Returns full metadata handle the standalone signature, adding /// the signature to the index for this generation if missing. /// Deltas are not required to return rows from previous generations. /// </summary> protected abstract StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle handle); /// <summary> /// The signature blob handles to be emitted, in row order. These /// are just the signature indices from the current generation. /// </summary> protected abstract IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles(); protected abstract void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef); /// <summary> /// Return a visitor for traversing all references to be emitted. /// </summary> protected abstract ReferenceIndexer CreateReferenceVisitor(); /// <summary> /// Populate EventMap table. /// </summary> protected abstract void PopulateEventMapTableRows(); /// <summary> /// Populate PropertyMap table. /// </summary> protected abstract void PopulatePropertyMapTableRows(); protected abstract void ReportReferencesToAddedSymbols(); // If true, it is allowed to have methods not have bodies (for emitting metadata-only // assembly) private readonly CancellationToken _cancellationToken; protected readonly CommonPEModuleBuilder module; public readonly EmitContext Context; protected readonly CommonMessageProvider messageProvider; // progress: private bool _tableIndicesAreComplete; private bool _usingNonSourceDocumentNameEnumerator; private ImmutableArray<string>.Enumerator _nonSourceDocumentNameEnumerator; private EntityHandle[] _pseudoSymbolTokenToTokenMap; private object[] _pseudoSymbolTokenToReferenceMap; private UserStringHandle[] _pseudoStringTokenToTokenMap; private bool _userStringTokenOverflow; private List<string> _pseudoStringTokenToStringMap; private ReferenceIndexer _referenceVisitor; protected readonly MetadataBuilder metadata; // A builder for Portable or Embedded PDB metadata, or null if we are not emitting Portable/Embedded PDB. protected readonly MetadataBuilder _debugMetadataOpt; internal bool EmitPortableDebugMetadata => _debugMetadataOpt != null; private readonly DynamicAnalysisDataWriter _dynamicAnalysisDataWriterOpt; private readonly Dictionary<ICustomAttribute, BlobHandle> _customAttributeSignatureIndex = new Dictionary<ICustomAttribute, BlobHandle>(); private readonly Dictionary<ITypeReference, BlobHandle> _typeSpecSignatureIndex = new Dictionary<ITypeReference, BlobHandle>(ReferenceEqualityComparer.Instance); private readonly Dictionary<string, int> _fileRefIndex = new Dictionary<string, int>(32); // more than enough in most cases, value is a RowId private readonly List<IFileReference> _fileRefList = new List<IFileReference>(32); private readonly Dictionary<IFieldReference, BlobHandle> _fieldSignatureIndex = new Dictionary<IFieldReference, BlobHandle>(ReferenceEqualityComparer.Instance); // We need to keep track of both the index of the signature and the actual blob to support VB static local naming scheme. private readonly Dictionary<ISignature, KeyValuePair<BlobHandle, ImmutableArray<byte>>> _signatureIndex; private readonly Dictionary<IMarshallingInformation, BlobHandle> _marshallingDescriptorIndex = new Dictionary<IMarshallingInformation, BlobHandle>(); protected readonly List<MethodImplementation> methodImplList = new List<MethodImplementation>(); private readonly Dictionary<IGenericMethodInstanceReference, BlobHandle> _methodInstanceSignatureIndex = new Dictionary<IGenericMethodInstanceReference, BlobHandle>(ReferenceEqualityComparer.Instance); // Well known dummy cor library types whose refs are used for attaching assembly attributes off within net modules // There is no guarantee the types actually exist in a cor library internal const string dummyAssemblyAttributeParentNamespace = "System.Runtime.CompilerServices"; internal const string dummyAssemblyAttributeParentName = "AssemblyAttributesGoHere"; internal static readonly string[,] dummyAssemblyAttributeParentQualifier = { { "", "M" }, { "S", "SM" } }; private readonly TypeReferenceHandle[,] _dummyAssemblyAttributeParent = { { default(TypeReferenceHandle), default(TypeReferenceHandle) }, { default(TypeReferenceHandle), default(TypeReferenceHandle) } }; internal CommonPEModuleBuilder Module => module; private void CreateMethodBodyReferenceIndex() { var referencesInIL = module.ReferencesInIL(); _pseudoSymbolTokenToTokenMap = new EntityHandle[referencesInIL.Length]; _pseudoSymbolTokenToReferenceMap = referencesInIL.ToArray(); } private void CreateIndices() { _cancellationToken.ThrowIfCancellationRequested(); this.CreateUserStringIndices(); this.CreateInitialAssemblyRefIndex(); this.CreateInitialFileRefIndex(); this.CreateIndicesForModule(); // Find all references and assign tokens. _referenceVisitor = this.CreateReferenceVisitor(); _referenceVisitor.Visit(module); this.CreateMethodBodyReferenceIndex(); this.OnIndicesCreated(); } private void CreateUserStringIndices() { _pseudoStringTokenToStringMap = new List<string>(); foreach (string str in this.module.GetStrings()) { _pseudoStringTokenToStringMap.Add(str); } _pseudoStringTokenToTokenMap = new UserStringHandle[_pseudoStringTokenToStringMap.Count]; } private void CreateIndicesForModule() { var nestedTypes = new Queue<INestedTypeDefinition>(); foreach (INamespaceTypeDefinition typeDef in module.GetTopLevelTypeDefinitions(Context)) { this.CreateIndicesFor(typeDef, nestedTypes); } while (nestedTypes.Count > 0) { var nestedType = nestedTypes.Dequeue(); this.CreateIndicesFor(nestedType, nestedTypes); } } protected virtual void OnIndicesCreated() { } private void CreateIndicesFor(ITypeDefinition typeDef, Queue<INestedTypeDefinition> nestedTypes) { _cancellationToken.ThrowIfCancellationRequested(); this.CreateIndicesForNonTypeMembers(typeDef); // Metadata spec: // The TypeDef table has a special ordering constraint: // the definition of an enclosing class shall precede the definition of all classes it encloses. foreach (var nestedType in typeDef.GetNestedTypes(Context)) { nestedTypes.Enqueue(nestedType); } } protected IEnumerable<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { if (typeDef.IsGeneric) { return typeDef.GenericParameters; } return null; } return this.GetConsolidatedTypeParameters(typeDef, typeDef); } private List<IGenericTypeParameter> GetConsolidatedTypeParameters(ITypeDefinition typeDef, ITypeDefinition owner) { List<IGenericTypeParameter> result = null; INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef != null) { result = this.GetConsolidatedTypeParameters(nestedTypeDef.ContainingTypeDefinition, owner); } if (typeDef.GenericParameterCount > 0) { ushort index = 0; if (result == null) { result = new List<IGenericTypeParameter>(); } else { index = (ushort)result.Count; } if (typeDef == owner && index == 0) { result.AddRange(typeDef.GenericParameters); } else { foreach (IGenericTypeParameter genericParameter in typeDef.GenericParameters) { result.Add(new InheritedTypeParameter(index++, owner, genericParameter)); } } } return result; } protected ImmutableArray<IParameterDefinition> GetParametersToEmit(IMethodDefinition methodDef) { if (methodDef.ParameterCount == 0 && !(methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context)))) { return ImmutableArray<IParameterDefinition>.Empty; } return GetParametersToEmitCore(methodDef); } private ImmutableArray<IParameterDefinition> GetParametersToEmitCore(IMethodDefinition methodDef) { ArrayBuilder<IParameterDefinition> builder = null; var parameters = methodDef.Parameters; if (methodDef.ReturnValueIsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(methodDef.GetReturnValueAttributes(Context))) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length + 1); builder.Add(new ReturnValueParameter(methodDef)); } for (int i = 0; i < parameters.Length; i++) { IParameterDefinition parDef = parameters[i]; // No explicit param row is needed if param has no flags (other than optionally IN), // no name and no references to the param row, such as CustomAttribute, Constant, or FieldMarshal if (parDef.Name != String.Empty || parDef.HasDefaultValue || parDef.IsOptional || parDef.IsOut || parDef.IsMarshalledExplicitly || IteratorHelper.EnumerableIsNotEmpty(parDef.GetAttributes(Context))) { if (builder != null) { builder.Add(parDef); } } else { // we have a parameter that does not need to be emitted (not common) if (builder == null) { builder = ArrayBuilder<IParameterDefinition>.GetInstance(parameters.Length); builder.AddRange(parameters, i); } } } return builder?.ToImmutableAndFree() ?? parameters; } /// <summary> /// Returns a reference to the unit that defines the given referenced type. If the referenced type is a structural type, such as a pointer or a generic type instance, /// then the result is null. /// </summary> public static IUnitReference GetDefiningUnitReference(ITypeReference typeReference, EmitContext context) { INestedTypeReference nestedTypeReference = typeReference.AsNestedTypeReference; while (nestedTypeReference != null) { if (nestedTypeReference.AsGenericTypeInstanceReference != null) { return null; } typeReference = nestedTypeReference.GetContainingType(context); nestedTypeReference = typeReference.AsNestedTypeReference; } INamespaceTypeReference namespaceTypeReference = typeReference.AsNamespaceTypeReference; if (namespaceTypeReference == null) { return null; } Debug.Assert(namespaceTypeReference.AsGenericTypeInstanceReference == null); return namespaceTypeReference.GetUnit(context); } private void CreateInitialAssemblyRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IAssemblyReference assemblyRef in this.module.GetAssemblyReferences(Context)) { this.GetOrAddAssemblyReferenceHandle(assemblyRef); } } private void CreateInitialFileRefIndex() { Debug.Assert(!_tableIndicesAreComplete); foreach (IFileReference fileRef in module.GetFiles(Context)) { string key = fileRef.FileName; if (!_fileRefIndex.ContainsKey(key)) { _fileRefList.Add(fileRef); _fileRefIndex.Add(key, _fileRefList.Count); } } } internal AssemblyReferenceHandle GetAssemblyReferenceHandle(IAssemblyReference assemblyReference) { var containingAssembly = this.module.GetContainingAssembly(Context); if (containingAssembly != null && ReferenceEquals(assemblyReference, containingAssembly)) { return default(AssemblyReferenceHandle); } return this.GetOrAddAssemblyReferenceHandle(assemblyReference); } internal ModuleReferenceHandle GetModuleReferenceHandle(string moduleName) { return this.GetOrAddModuleReferenceHandle(moduleName); } private BlobHandle GetCustomAttributeSignatureIndex(ICustomAttribute customAttribute) { BlobHandle result; if (_customAttributeSignatureIndex.TryGetValue(customAttribute, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeCustomAttributeSignature(customAttribute, writer); result = metadata.GetOrAddBlob(writer); _customAttributeSignatureIndex.Add(customAttribute, result); writer.Free(); return result; } private EntityHandle GetCustomAttributeTypeCodedIndex(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static EventAttributes GetEventAttributes(IEventDefinition eventDef) { EventAttributes result = 0; if (eventDef.IsSpecialName) { result |= EventAttributes.SpecialName; } if (eventDef.IsRuntimeSpecial) { result |= EventAttributes.RTSpecialName; } return result; } public static FieldAttributes GetFieldAttributes(IFieldDefinition fieldDef) { var result = (FieldAttributes)fieldDef.Visibility; if (fieldDef.IsStatic) { result |= FieldAttributes.Static; } if (fieldDef.IsReadOnly) { result |= FieldAttributes.InitOnly; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.Literal; } if (fieldDef.IsNotSerialized) { result |= FieldAttributes.NotSerialized; } if (!fieldDef.MappedData.IsDefault) { result |= FieldAttributes.HasFieldRVA; } if (fieldDef.IsSpecialName) { result |= FieldAttributes.SpecialName; } if (fieldDef.IsRuntimeSpecial) { result |= FieldAttributes.RTSpecialName; } if (fieldDef.IsMarshalledExplicitly) { result |= FieldAttributes.HasFieldMarshal; } if (fieldDef.IsCompileTimeConstant) { result |= FieldAttributes.HasDefault; } return result; } internal BlobHandle GetFieldSignatureIndex(IFieldReference fieldReference) { BlobHandle result; ISpecializedFieldReference specializedFieldReference = fieldReference.AsSpecializedFieldReference; if (specializedFieldReference != null) { fieldReference = specializedFieldReference.UnspecializedVersion; } if (_fieldSignatureIndex.TryGetValue(fieldReference, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeFieldSignature(fieldReference, writer); result = metadata.GetOrAddBlob(writer); _fieldSignatureIndex.Add(fieldReference, result); writer.Free(); return result; } internal EntityHandle GetFieldHandle(IFieldReference fieldReference) { IFieldDefinition fieldDef = null; IUnitReference definingUnit = GetDefiningUnitReference(fieldReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { fieldDef = fieldReference.GetResolvedField(Context); } return fieldDef != null ? (EntityHandle)GetFieldDefinitionHandle(fieldDef) : GetMemberReferenceHandle(fieldReference); } internal AssemblyFileHandle GetAssemblyFileHandle(IFileReference fileReference) { string key = fileReference.FileName; int index; if (!_fileRefIndex.TryGetValue(key, out index)) { Debug.Assert(!_tableIndicesAreComplete); _fileRefList.Add(fileReference); _fileRefIndex.Add(key, index = _fileRefList.Count); } return MetadataTokens.AssemblyFileHandle(index); } private AssemblyFileHandle GetAssemblyFileHandle(IModuleReference mref) { return MetadataTokens.AssemblyFileHandle(_fileRefIndex[mref.Name]); } private static GenericParameterAttributes GetGenericParameterAttributes(IGenericParameter genPar) { GenericParameterAttributes result = 0; switch (genPar.Variance) { case TypeParameterVariance.Covariant: result |= GenericParameterAttributes.Covariant; break; case TypeParameterVariance.Contravariant: result |= GenericParameterAttributes.Contravariant; break; } if (genPar.MustBeReferenceType) { result |= GenericParameterAttributes.ReferenceTypeConstraint; } if (genPar.MustBeValueType) { result |= GenericParameterAttributes.NotNullableValueTypeConstraint; } if (genPar.MustHaveDefaultConstructor) { result |= GenericParameterAttributes.DefaultConstructorConstraint; } return result; } private EntityHandle GetExportedTypeImplementation(INamespaceTypeReference namespaceRef) { IUnitReference uref = namespaceRef.GetUnit(Context); if (uref is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } var mref = (IModuleReference)uref; aref = mref.GetContainingAssembly(Context); return aref == null || ReferenceEquals(aref, this.module.GetContainingAssembly(Context)) ? (EntityHandle)GetAssemblyFileHandle(mref) : GetAssemblyReferenceHandle(aref); } private static uint GetManagedResourceOffset(ManagedResource resource, BlobBuilder resourceWriter) { if (resource.ExternalFile != null) { return resource.Offset; } int result = resourceWriter.Count; resource.WriteData(resourceWriter); return (uint)result; } private static uint GetManagedResourceOffset(BlobBuilder resource, BlobBuilder resourceWriter) { int result = resourceWriter.Count; resourceWriter.WriteInt32(resource.Count); resource.WriteContentTo(resourceWriter); resourceWriter.Align(8); return (uint)result; } public static string GetMangledName(INamedTypeReference namedType, int generation) { string unmangledName = (generation == 0) ? namedType.Name : namedType.Name + "#" + generation; return namedType.MangleName ? MetadataHelpers.ComposeAritySuffixedMetadataName(unmangledName, namedType.GenericParameterCount) : unmangledName; } internal MemberReferenceHandle GetMemberReferenceHandle(ITypeMemberReference memberRef) { return this.GetOrAddMemberReferenceHandle(memberRef); } internal EntityHandle GetMemberReferenceParent(ITypeMemberReference memberRef) { ITypeDefinition parentTypeDef = memberRef.GetContainingType(Context).AsTypeDefinition(Context); if (parentTypeDef != null) { TypeDefinitionHandle parentTypeDefHandle; TryGetTypeDefinitionHandle(parentTypeDef, out parentTypeDefHandle); if (!parentTypeDefHandle.IsNil) { if (memberRef is IFieldReference) { return parentTypeDefHandle; } if (memberRef is IMethodReference methodRef) { if (methodRef.AcceptsExtraArguments) { MethodDefinitionHandle methodHandle; if (this.TryGetMethodDefinitionHandle(methodRef.GetResolvedMethod(Context), out methodHandle)) { return methodHandle; } } return parentTypeDefHandle; } // TODO: error } } // TODO: special treatment for global fields and methods. Object model support would be nice. var containingType = memberRef.GetContainingType(Context); return containingType.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(containingType) : GetTypeReferenceHandle(containingType); } internal EntityHandle GetMethodDefinitionOrReferenceHandle(IMethodReference methodReference) { IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } return methodDef != null ? (EntityHandle)GetMethodDefinitionHandle(methodDef) : GetMemberReferenceHandle(methodReference); } public static MethodAttributes GetMethodAttributes(IMethodDefinition methodDef) { var result = (MethodAttributes)methodDef.Visibility; if (methodDef.IsStatic) { result |= MethodAttributes.Static; } if (methodDef.IsSealed) { result |= MethodAttributes.Final; } if (methodDef.IsVirtual) { result |= MethodAttributes.Virtual; } if (methodDef.IsHiddenBySignature) { result |= MethodAttributes.HideBySig; } if (methodDef.IsNewSlot) { result |= MethodAttributes.NewSlot; } if (methodDef.IsAccessCheckedOnOverride) { result |= MethodAttributes.CheckAccessOnOverride; } if (methodDef.IsAbstract) { result |= MethodAttributes.Abstract; } if (methodDef.IsSpecialName) { result |= MethodAttributes.SpecialName; } if (methodDef.IsRuntimeSpecial) { result |= MethodAttributes.RTSpecialName; } if (methodDef.IsPlatformInvoke) { result |= MethodAttributes.PinvokeImpl; } if (methodDef.HasDeclarativeSecurity) { result |= MethodAttributes.HasSecurity; } if (methodDef.RequiresSecurityObject) { result |= MethodAttributes.RequireSecObject; } return result; } internal BlobHandle GetMethodSpecificationSignatureHandle(IGenericMethodInstanceReference methodInstanceReference) { BlobHandle result; if (_methodInstanceSignatureIndex.TryGetValue(methodInstanceReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSpecificationSignature(methodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference typeReference in methodInstanceReference.GetGenericArguments(Context)) { var typeRef = typeReference; SerializeTypeReference(encoder.AddArgument(), typeRef); } result = metadata.GetOrAddBlob(builder); _methodInstanceSignatureIndex.Add(methodInstanceReference, result); builder.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(IMarshallingInformation marshallingInformation) { BlobHandle result; if (_marshallingDescriptorIndex.TryGetValue(marshallingInformation, out result)) { return result; } var writer = PooledBlobBuilder.GetInstance(); this.SerializeMarshallingDescriptor(marshallingInformation, writer); result = metadata.GetOrAddBlob(writer); _marshallingDescriptorIndex.Add(marshallingInformation, result); writer.Free(); return result; } private BlobHandle GetMarshallingDescriptorHandle(ImmutableArray<byte> descriptor) { return metadata.GetOrAddBlob(descriptor); } private BlobHandle GetMemberReferenceSignatureHandle(ITypeMemberReference memberRef) { return memberRef switch { IFieldReference fieldReference => this.GetFieldSignatureIndex(fieldReference), IMethodReference methodReference => this.GetMethodSignatureHandle(methodReference), _ => throw ExceptionUtilities.Unreachable }; } internal BlobHandle GetMethodSignatureHandle(IMethodReference methodReference) { return GetMethodSignatureHandleAndBlob(methodReference, out _); } internal byte[] GetMethodSignature(IMethodReference methodReference) { ImmutableArray<byte> signatureBlob; GetMethodSignatureHandleAndBlob(methodReference, out signatureBlob); return signatureBlob.ToArray(); } private BlobHandle GetMethodSignatureHandleAndBlob(IMethodReference methodReference, out ImmutableArray<byte> signatureBlob) { BlobHandle result; ISpecializedMethodReference specializedMethodReference = methodReference.AsSpecializedMethodReference; if (specializedMethodReference != null) { methodReference = specializedMethodReference.UnspecializedVersion; } KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(methodReference, out existing)) { signatureBlob = existing.Value; return existing.Key; } Debug.Assert((methodReference.CallingConvention & CallingConvention.Generic) != 0 == (methodReference.GenericParameterCount > 0)); var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).MethodSignature( new SignatureHeader((byte)methodReference.CallingConvention).CallingConvention, methodReference.GenericParameterCount, isInstanceMethod: (methodReference.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, methodReference, methodReference.ExtraParameters); signatureBlob = builder.ToImmutableArray(); result = metadata.GetOrAddBlob(signatureBlob); _signatureIndex.Add(methodReference, KeyValuePairUtil.Create(result, signatureBlob)); builder.Free(); return result; } private BlobHandle GetMethodSpecificationBlobHandle(IGenericMethodInstanceReference genericMethodInstanceReference) { var writer = PooledBlobBuilder.GetInstance(); SerializeMethodSpecificationSignature(writer, genericMethodInstanceReference); BlobHandle result = metadata.GetOrAddBlob(writer); writer.Free(); return result; } private MethodSpecificationHandle GetMethodSpecificationHandle(IGenericMethodInstanceReference methodSpec) { return this.GetOrAddMethodSpecificationHandle(methodSpec); } internal EntityHandle GetMethodHandle(IMethodReference methodReference) { MethodDefinitionHandle methodDefHandle; IMethodDefinition methodDef = null; IUnitReference definingUnit = GetDefiningUnitReference(methodReference.GetContainingType(Context), Context); if (definingUnit != null && ReferenceEquals(definingUnit, this.module)) { methodDef = methodReference.GetResolvedMethod(Context); } if (methodDef != null && (methodReference == methodDef || !methodReference.AcceptsExtraArguments) && this.TryGetMethodDefinitionHandle(methodDef, out methodDefHandle)) { return methodDefHandle; } IGenericMethodInstanceReference methodSpec = methodReference.AsGenericMethodInstanceReference; return methodSpec != null ? (EntityHandle)GetMethodSpecificationHandle(methodSpec) : GetMemberReferenceHandle(methodReference); } internal EntityHandle GetStandaloneSignatureHandle(ISignature signature) { Debug.Assert(!(signature is IMethodReference)); var builder = PooledBlobBuilder.GetInstance(); var signatureEncoder = new BlobEncoder(builder).MethodSignature(convention: signature.CallingConvention.ToSignatureConvention(), genericParameterCount: 0, isInstanceMethod: false); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); StandaloneSignatureHandle handle = GetOrAddStandaloneSignatureHandle(blobIndex); return handle; } public static ParameterAttributes GetParameterAttributes(IParameterDefinition parDef) { ParameterAttributes result = 0; if (parDef.IsIn) { result |= ParameterAttributes.In; } if (parDef.IsOut) { result |= ParameterAttributes.Out; } if (parDef.IsOptional) { result |= ParameterAttributes.Optional; } if (parDef.HasDefaultValue) { result |= ParameterAttributes.HasDefault; } if (parDef.IsMarshalledExplicitly) { result |= ParameterAttributes.HasFieldMarshal; } return result; } private BlobHandle GetPermissionSetBlobHandle(ImmutableArray<ICustomAttribute> permissionSet) { var writer = PooledBlobBuilder.GetInstance(); BlobHandle result; try { writer.WriteByte((byte)'.'); writer.WriteCompressedInteger(permissionSet.Length); this.SerializePermissionSet(permissionSet, writer); result = metadata.GetOrAddBlob(writer); } finally { writer.Free(); } return result; } public static PropertyAttributes GetPropertyAttributes(IPropertyDefinition propertyDef) { PropertyAttributes result = 0; if (propertyDef.IsSpecialName) { result |= PropertyAttributes.SpecialName; } if (propertyDef.IsRuntimeSpecial) { result |= PropertyAttributes.RTSpecialName; } if (propertyDef.HasDefaultValue) { result |= PropertyAttributes.HasDefault; } return result; } private BlobHandle GetPropertySignatureHandle(IPropertyDefinition propertyDef) { KeyValuePair<BlobHandle, ImmutableArray<byte>> existing; if (_signatureIndex.TryGetValue(propertyDef, out existing)) { return existing.Key; } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).PropertySignature( isInstanceProperty: (propertyDef.CallingConvention & CallingConvention.HasThis) != 0); SerializeReturnValueAndParameters(encoder, propertyDef, ImmutableArray<IParameterTypeInformation>.Empty); var blob = builder.ToImmutableArray(); var result = metadata.GetOrAddBlob(blob); _signatureIndex.Add(propertyDef, KeyValuePairUtil.Create(result, blob)); builder.Free(); return result; } private EntityHandle GetResolutionScopeHandle(IUnitReference unitReference) { if (unitReference is IAssemblyReference aref) { return GetAssemblyReferenceHandle(aref); } // If this is a module from a referenced multi-module assembly, // the assembly should be used as the resolution scope. var mref = (IModuleReference)unitReference; aref = mref.GetContainingAssembly(Context); if (aref != null && aref != module.GetContainingAssembly(Context)) { return GetAssemblyReferenceHandle(aref); } return GetModuleReferenceHandle(mref.Name); } private StringHandle GetStringHandleForPathAndCheckLength(string path, INamedEntity errorEntity = null) { CheckPathLength(path, errorEntity); return metadata.GetOrAddString(path); } private StringHandle GetStringHandleForNameAndCheckLength(string name, INamedEntity errorEntity = null) { CheckNameLength(name, errorEntity); return metadata.GetOrAddString(name); } /// <summary> /// The Microsoft CLR requires that {namespace} + "." + {name} fit in MAX_CLASS_NAME /// (even though the name and namespace are stored separately in the Microsoft /// implementation). Note that the namespace name of a nested type is always blank /// (since comes from the container). /// </summary> /// <param name="namespaceType">We're trying to add the containing namespace of this type to the string heap.</param> /// <param name="mangledTypeName">Namespace names are never used on their own - this is the type that is adding the namespace name. /// Used only for length checking.</param> private StringHandle GetStringHandleForNamespaceAndCheckLength(INamespaceTypeReference namespaceType, string mangledTypeName) { string namespaceName = namespaceType.NamespaceName; if (namespaceName.Length == 0) // Optimization: CheckNamespaceLength is relatively expensive. { return default(StringHandle); } CheckNamespaceLength(namespaceName, mangledTypeName, namespaceType); return metadata.GetOrAddString(namespaceName); } private void CheckNameLength(string name, INamedEntity errorEntity) { // NOTE: ildasm shows quotes around some names (e.g. explicit implementations of members of generic interfaces) // but that seems to be tool-specific - they don't seem to and up in the string heap (so they don't count against // the length limit). if (IsTooLongInternal(name, NameLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, name)); } } private void CheckPathLength(string path, INamedEntity errorEntity = null) { if (IsTooLongInternal(path, PathLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, path)); } } private void CheckNamespaceLength(string namespaceName, string mangledTypeName, INamespaceTypeReference errorEntity) { // It's never useful to report that the namespace name is too long. // If it's too long, then the full name is too long and that string is // more helpful. // PERF: We expect to check this A LOT, so we'll aggressively inline some // of the helpers (esp IsTooLongInternal) in a way that allows us to forego // string concatenation (unless a diagnostic is actually reported). if (namespaceName.Length + 1 + mangledTypeName.Length > NameLengthLimit / 3) { int utf8Length = s_utf8Encoding.GetByteCount(namespaceName) + 1 + // dot s_utf8Encoding.GetByteCount(mangledTypeName); if (utf8Length > NameLengthLimit) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_MetadataNameTooLong, location, namespaceName + "." + mangledTypeName)); } } } internal bool IsUsingStringTooLong(string usingString, INamedEntity errorEntity = null) { if (IsTooLongInternal(usingString, PdbLengthLimit)) { Location location = GetNamedEntityLocation(errorEntity); this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbUsingNameTooLong, location, usingString)); return true; } return false; } internal bool IsLocalNameTooLong(ILocalDefinition localDefinition) { string name = localDefinition.Name; if (IsTooLongInternal(name, PdbLengthLimit)) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.WRN_PdbLocalNameTooLong, localDefinition.Location, name)); return true; } return false; } /// <summary> /// Test the given name to see if it fits in metadata. /// </summary> /// <param name="str">String to test (non-null).</param> /// <param name="maxLength">Max length for name. (Expected to be at least 5.)</param> /// <returns>True if the name is too long.</returns> /// <remarks>Internal for test purposes.</remarks> internal static bool IsTooLongInternal(string str, int maxLength) { Debug.Assert(str != null); // No need to handle in an internal utility. if (str.Length < maxLength / 3) //UTF-8 uses at most 3 bytes per char { return false; } int utf8Length = s_utf8Encoding.GetByteCount(str); return utf8Length > maxLength; } private static Location GetNamedEntityLocation(INamedEntity errorEntity) { ISymbolInternal symbol; if (errorEntity is Cci.INamespace ns) { symbol = ns.GetInternalSymbol(); } else { symbol = (errorEntity as Cci.IReference)?.GetInternalSymbol(); } return GetSymbolLocation(symbol); } protected static Location GetSymbolLocation(ISymbolInternal symbolOpt) { return symbolOpt != null && !symbolOpt.Locations.IsDefaultOrEmpty ? symbolOpt.Locations[0] : Location.None; } internal TypeAttributes GetTypeAttributes(ITypeDefinition typeDef) { return GetTypeAttributes(typeDef, Context); } public static TypeAttributes GetTypeAttributes(ITypeDefinition typeDef, EmitContext context) { TypeAttributes result = 0; switch (typeDef.Layout) { case LayoutKind.Sequential: result |= TypeAttributes.SequentialLayout; break; case LayoutKind.Explicit: result |= TypeAttributes.ExplicitLayout; break; } if (typeDef.IsInterface) { result |= TypeAttributes.Interface; } if (typeDef.IsAbstract) { result |= TypeAttributes.Abstract; } if (typeDef.IsSealed) { result |= TypeAttributes.Sealed; } if (typeDef.IsSpecialName) { result |= TypeAttributes.SpecialName; } if (typeDef.IsRuntimeSpecial) { result |= TypeAttributes.RTSpecialName; } if (typeDef.IsComObject) { result |= TypeAttributes.Import; } if (typeDef.IsSerializable) { result |= TypeAttributes.Serializable; } if (typeDef.IsWindowsRuntimeImport) { result |= TypeAttributes.WindowsRuntime; } switch (typeDef.StringFormat) { case CharSet.Unicode: result |= TypeAttributes.UnicodeClass; break; case Constants.CharSet_Auto: result |= TypeAttributes.AutoClass; break; } if (typeDef.HasDeclarativeSecurity) { result |= TypeAttributes.HasSecurity; } if (typeDef.IsBeforeFieldInit) { result |= TypeAttributes.BeforeFieldInit; } INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(context); if (nestedTypeDef != null) { switch (((ITypeDefinitionMember)typeDef).Visibility) { case TypeMemberVisibility.Public: result |= TypeAttributes.NestedPublic; break; case TypeMemberVisibility.Private: result |= TypeAttributes.NestedPrivate; break; case TypeMemberVisibility.Family: result |= TypeAttributes.NestedFamily; break; case TypeMemberVisibility.Assembly: result |= TypeAttributes.NestedAssembly; break; case TypeMemberVisibility.FamilyAndAssembly: result |= TypeAttributes.NestedFamANDAssem; break; case TypeMemberVisibility.FamilyOrAssembly: result |= TypeAttributes.NestedFamORAssem; break; } return result; } INamespaceTypeDefinition namespaceTypeDef = typeDef.AsNamespaceTypeDefinition(context); if (namespaceTypeDef != null && namespaceTypeDef.IsPublic) { result |= TypeAttributes.Public; } return result; } private EntityHandle GetDeclaringTypeOrMethodHandle(IGenericParameter genPar) { IGenericTypeParameter genTypePar = genPar.AsGenericTypeParameter; if (genTypePar != null) { return GetTypeDefinitionHandle(genTypePar.DefiningType); } IGenericMethodParameter genMethPar = genPar.AsGenericMethodParameter; if (genMethPar != null) { return GetMethodDefinitionHandle(genMethPar.DefiningMethod); } throw ExceptionUtilities.Unreachable; } private TypeReferenceHandle GetTypeReferenceHandle(ITypeReference typeReference) { TypeReferenceHandle result; if (this.TryGetTypeReferenceHandle(typeReference, out result)) { return result; } // NOTE: Even though CLR documentation does not explicitly specify any requirements // NOTE: to the order of records in TypeRef table, some tools and/or APIs (e.g. // NOTE: IMetaDataEmit::MergeEnd) assume that the containing type referenced as // NOTE: ResolutionScope for its nested types should appear in TypeRef table // NOTE: *before* any of its nested types. // SEE ALSO: bug#570975 and test Bug570975() INestedTypeReference nestedTypeRef = typeReference.AsNestedTypeReference; if (nestedTypeRef != null) { GetTypeReferenceHandle(nestedTypeRef.GetContainingType(this.Context)); } return this.GetOrAddTypeReferenceHandle(typeReference); } private TypeSpecificationHandle GetTypeSpecificationHandle(ITypeReference typeReference) { return this.GetOrAddTypeSpecificationHandle(typeReference); } internal ITypeDefinition GetTypeDefinition(int token) { // The token must refer to a TypeDef row since we are // only handling indexes into the full metadata (in EnC) // for def tables. Other tables contain deltas only. return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)); } internal IMethodDefinition GetMethodDefinition(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetMethodDef(MetadataTokens.MethodDefinitionHandle(token)); } internal INestedTypeReference GetNestedTypeReference(int token) { // Must be a def table. (See comment in GetTypeDefinition.) return GetTypeDef(MetadataTokens.TypeDefinitionHandle(token)).AsNestedTypeReference; } internal BlobHandle GetTypeSpecSignatureIndex(ITypeReference typeReference) { BlobHandle result; if (_typeSpecSignatureIndex.TryGetValue(typeReference, out result)) { return result; } var builder = PooledBlobBuilder.GetInstance(); this.SerializeTypeReference(new BlobEncoder(builder).TypeSpecificationSignature(), typeReference); result = metadata.GetOrAddBlob(builder); _typeSpecSignatureIndex.Add(typeReference, result); builder.Free(); return result; } internal EntityHandle GetTypeHandle(ITypeReference typeReference, bool treatRefAsPotentialTypeSpec = true) { TypeDefinitionHandle handle; var typeDefinition = typeReference.AsTypeDefinition(this.Context); if (typeDefinition != null && this.TryGetTypeDefinitionHandle(typeDefinition, out handle)) { return handle; } return treatRefAsPotentialTypeSpec && typeReference.IsTypeSpecification() ? (EntityHandle)GetTypeSpecificationHandle(typeReference) : GetTypeReferenceHandle(typeReference); } internal EntityHandle GetDefinitionHandle(IDefinition definition) { return definition switch { ITypeDefinition typeDef => (EntityHandle)GetTypeDefinitionHandle(typeDef), IMethodDefinition methodDef => GetMethodDefinitionHandle(methodDef), IFieldDefinition fieldDef => GetFieldDefinitionHandle(fieldDef), IEventDefinition eventDef => GetEventDefinitionHandle(eventDef), IPropertyDefinition propertyDef => GetPropertyDefIndex(propertyDef), _ => throw ExceptionUtilities.Unreachable }; } public void WriteMetadataAndIL(PdbWriter nativePdbWriterOpt, Stream metadataStream, Stream ilStream, Stream portablePdbStreamOpt, out MetadataSizes metadataSizes) { Debug.Assert(nativePdbWriterOpt == null ^ portablePdbStreamOpt == null); nativePdbWriterOpt?.SetMetadataEmitter(this); // TODO: we can precalculate the exact size of IL stream var ilBuilder = new BlobBuilder(1024); var metadataBuilder = new BlobBuilder(4 * 1024); var mappedFieldDataBuilder = new BlobBuilder(0); var managedResourceDataBuilder = new BlobBuilder(0); // Add 4B of padding to the start of the separated IL stream, // so that method RVAs, which are offsets to this stream, are never 0. ilBuilder.WriteUInt32(0); // this is used to handle edit-and-continue emit, so we should have a module // version ID that is imposed by the caller (the same as the previous module version ID). // Therefore we do not have to fill in a new module version ID in the generated metadata // stream. Debug.Assert(module.SerializationProperties.PersistentIdentifier != default(Guid)); BuildMetadataAndIL( nativePdbWriterOpt, ilBuilder, mappedFieldDataBuilder, managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup); var typeSystemRowCounts = metadata.GetRowCounts(); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncLog] == 0); Debug.Assert(typeSystemRowCounts[(int)TableIndex.EncMap] == 0); PopulateEncTables(typeSystemRowCounts); Debug.Assert(mappedFieldDataBuilder.Count == 0); Debug.Assert(managedResourceDataBuilder.Count == 0); Debug.Assert(mvidFixup.IsDefault); Debug.Assert(mvidStringFixup.IsDefault); // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. var rootBuilder = new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); rootBuilder.Serialize(metadataBuilder, methodBodyStreamRva: 0, mappedFieldDataStreamRva: 0); metadataSizes = rootBuilder.Sizes; try { ilBuilder.WriteContentTo(ilStream); metadataBuilder.WriteContentTo(metadataStream); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new PeWritingException(e); } if (portablePdbStreamOpt != null) { var portablePdbBuilder = GetPortablePdbBuilder( typeSystemRowCounts, debugEntryPoint: default(MethodDefinitionHandle), deterministicIdProviderOpt: null); var portablePdbBlob = new BlobBuilder(); portablePdbBuilder.Serialize(portablePdbBlob); try { portablePdbBlob.WriteContentTo(portablePdbStreamOpt); } catch (Exception e) when (!(e is OperationCanceledException)) { throw new SymUnmanagedWriterException(e.Message, e); } } } public void BuildMetadataAndIL( PdbWriter nativePdbWriterOpt, BlobBuilder ilBuilder, BlobBuilder mappedFieldDataBuilder, BlobBuilder managedResourceDataBuilder, out Blob mvidFixup, out Blob mvidStringFixup) { // Extract information from object model into tables, indices and streams CreateIndices(); if (_debugMetadataOpt != null) { // Ensure document table lists files in command line order // This is key for us to be able to accurately rebuild a binary from a PDB. var documentsBuilder = Module.DebugDocumentsBuilder; foreach (var tree in Module.CommonCompilation.SyntaxTrees) { if (documentsBuilder.TryGetDebugDocument(tree.FilePath, basePath: null) is { } doc && !_documentIndex.ContainsKey(doc)) { AddDocument(doc, _documentIndex); } } if (Context.RebuildData is { } rebuildData) { _usingNonSourceDocumentNameEnumerator = true; _nonSourceDocumentNameEnumerator = rebuildData.NonSourceFileDocumentNames.GetEnumerator(); } DefineModuleImportScope(); if (module.SourceLinkStreamOpt != null) { EmbedSourceLink(module.SourceLinkStreamOpt); } EmbedCompilationOptions(module); EmbedMetadataReferenceInformation(module); EmbedTypeDefinitionDocumentInformation(module); } int[] methodBodyOffsets; if (MetadataOnly) { methodBodyOffsets = SerializeThrowNullMethodBodies(ilBuilder); mvidStringFixup = default(Blob); } else { methodBodyOffsets = SerializeMethodBodies(ilBuilder, nativePdbWriterOpt, out mvidStringFixup); } _cancellationToken.ThrowIfCancellationRequested(); // method body serialization adds Stand Alone Signatures _tableIndicesAreComplete = true; ReportReferencesToAddedSymbols(); BlobBuilder dynamicAnalysisDataOpt = null; if (_dynamicAnalysisDataWriterOpt != null) { dynamicAnalysisDataOpt = new BlobBuilder(); _dynamicAnalysisDataWriterOpt.SerializeMetadataTables(dynamicAnalysisDataOpt); } PopulateTypeSystemTables(methodBodyOffsets, mappedFieldDataBuilder, managedResourceDataBuilder, dynamicAnalysisDataOpt, out mvidFixup); } public virtual void PopulateEncTables(ImmutableArray<int> typeSystemRowCounts) { } public MetadataRootBuilder GetRootBuilder() { // TODO (https://github.com/dotnet/roslyn/issues/3905): // InterfaceImpl table emitted by Roslyn is not compliant with ECMA spec. // Once fixed enable validation in DEBUG builds. return new MetadataRootBuilder(metadata, module.SerializationProperties.TargetRuntimeVersion, suppressValidation: true); } public PortablePdbBuilder GetPortablePdbBuilder(ImmutableArray<int> typeSystemRowCounts, MethodDefinitionHandle debugEntryPoint, Func<IEnumerable<Blob>, BlobContentId> deterministicIdProviderOpt) { return new PortablePdbBuilder(_debugMetadataOpt, typeSystemRowCounts, debugEntryPoint, deterministicIdProviderOpt); } internal void GetEntryPoints(out MethodDefinitionHandle entryPointHandle, out MethodDefinitionHandle debugEntryPointHandle) { if (IsFullMetadata && !MetadataOnly) { // PE entry point is set for executable programs IMethodReference entryPoint = module.PEEntryPoint; entryPointHandle = entryPoint != null ? (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)entryPoint.AsDefinition(Context)) : default(MethodDefinitionHandle); // debug entry point may be different from PE entry point, it may also be set for libraries IMethodReference debugEntryPoint = module.DebugEntryPoint; if (debugEntryPoint != null && debugEntryPoint != entryPoint) { debugEntryPointHandle = (MethodDefinitionHandle)GetMethodHandle((IMethodDefinition)debugEntryPoint.AsDefinition(Context)); } else { debugEntryPointHandle = entryPointHandle; } } else { entryPointHandle = debugEntryPointHandle = default(MethodDefinitionHandle); } } private ImmutableArray<IGenericParameter> GetSortedGenericParameters() { return GetGenericParameters().OrderBy((x, y) => { // Spec: GenericParam table is sorted by Owner and then by Number. int result = CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(x)) - CodedIndex.TypeOrMethodDef(GetDeclaringTypeOrMethodHandle(y)); if (result != 0) { return result; } return x.Index - y.Index; }).ToImmutableArray(); } private void PopulateTypeSystemTables(int[] methodBodyOffsets, BlobBuilder mappedFieldDataWriter, BlobBuilder resourceWriter, BlobBuilder dynamicAnalysisDataOpt, out Blob mvidFixup) { var sortedGenericParameters = GetSortedGenericParameters(); this.PopulateAssemblyRefTableRows(); this.PopulateAssemblyTableRows(); this.PopulateClassLayoutTableRows(); this.PopulateConstantTableRows(); this.PopulateDeclSecurityTableRows(); this.PopulateEventMapTableRows(); this.PopulateEventTableRows(); this.PopulateExportedTypeTableRows(); this.PopulateFieldLayoutTableRows(); this.PopulateFieldMarshalTableRows(); this.PopulateFieldRvaTableRows(mappedFieldDataWriter); this.PopulateFieldTableRows(); this.PopulateFileTableRows(); this.PopulateGenericParameters(sortedGenericParameters); this.PopulateImplMapTableRows(); this.PopulateInterfaceImplTableRows(); this.PopulateManifestResourceTableRows(resourceWriter, dynamicAnalysisDataOpt); this.PopulateMemberRefTableRows(); this.PopulateMethodImplTableRows(); this.PopulateMethodTableRows(methodBodyOffsets); this.PopulateMethodSemanticsTableRows(); this.PopulateMethodSpecTableRows(); this.PopulateModuleRefTableRows(); this.PopulateModuleTableRow(out mvidFixup); this.PopulateNestedClassTableRows(); this.PopulateParamTableRows(); this.PopulatePropertyMapTableRows(); this.PopulatePropertyTableRows(); this.PopulateTypeDefTableRows(); this.PopulateTypeRefTableRows(); this.PopulateTypeSpecTableRows(); this.PopulateStandaloneSignatures(); // This table is populated after the others because it depends on the order of the entries of the generic parameter table. this.PopulateCustomAttributeTableRows(sortedGenericParameters); } private void PopulateAssemblyRefTableRows() { var assemblyRefs = this.GetAssemblyRefs(); metadata.SetCapacity(TableIndex.AssemblyRef, assemblyRefs.Count); foreach (var identity in assemblyRefs) { // reference has token, not full public key metadata.AddAssemblyReference( name: GetStringHandleForPathAndCheckLength(identity.Name), version: identity.Version, culture: metadata.GetOrAddString(identity.CultureName), publicKeyOrToken: metadata.GetOrAddBlob(identity.PublicKeyToken), flags: (AssemblyFlags)((int)identity.ContentType << 9) | (identity.IsRetargetable ? AssemblyFlags.Retargetable : 0), hashValue: default(BlobHandle)); } } private void PopulateAssemblyTableRows() { if (!EmitAssemblyDefinition) { return; } var sourceAssembly = module.SourceAssemblyOpt; Debug.Assert(sourceAssembly != null); var flags = sourceAssembly.AssemblyFlags & ~AssemblyFlags.PublicKey; if (!sourceAssembly.Identity.PublicKey.IsDefaultOrEmpty) { flags |= AssemblyFlags.PublicKey; } metadata.AddAssembly( flags: flags, hashAlgorithm: sourceAssembly.HashAlgorithm, version: sourceAssembly.Identity.Version, publicKey: metadata.GetOrAddBlob(sourceAssembly.Identity.PublicKey), name: GetStringHandleForPathAndCheckLength(module.Name, module), culture: metadata.GetOrAddString(sourceAssembly.Identity.CultureName)); } private void PopulateCustomAttributeTableRows(ImmutableArray<IGenericParameter> sortedGenericParameters) { if (this.IsFullMetadata) { this.AddAssemblyAttributesToTable(); } this.AddCustomAttributesToTable(GetMethodDefs(), def => GetMethodDefinitionHandle(def)); this.AddCustomAttributesToTable(GetFieldDefs(), def => GetFieldDefinitionHandle(def)); // this.AddCustomAttributesToTable(this.typeRefList, 2); var typeDefs = GetTypeDefs(); this.AddCustomAttributesToTable(typeDefs, def => GetTypeDefinitionHandle(def)); this.AddCustomAttributesToTable(GetParameterDefs(), def => GetParameterHandle(def)); // TODO: attributes on member reference entries 6 if (this.IsFullMetadata) { this.AddModuleAttributesToTable(module); } // TODO: declarative security entries 8 this.AddCustomAttributesToTable(GetPropertyDefs(), def => GetPropertyDefIndex(def)); this.AddCustomAttributesToTable(GetEventDefs(), def => GetEventDefinitionHandle(def)); // TODO: standalone signature entries 11 // TODO: type spec entries 13 // this.AddCustomAttributesToTable(this.module.AssemblyReferences, 15); // TODO: this.AddCustomAttributesToTable(assembly.Files, 16); // TODO: exported types 17 // TODO: this.AddCustomAttributesToTable(assembly.Resources, 18); this.AddCustomAttributesToTable(sortedGenericParameters, TableIndex.GenericParam); } private void AddAssemblyAttributesToTable() { bool writingNetModule = module.OutputKind == OutputKind.NetModule; if (writingNetModule) { // When writing netmodules, assembly security attributes are not emitted by PopulateDeclSecurityTableRows(). // Instead, here we make sure they are emitted as regular attributes, attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. AddAssemblyAttributesToTable( this.module.GetSourceAssemblySecurityAttributes().Select(sa => sa.Attribute), needsDummyParent: true, isSecurity: true); } AddAssemblyAttributesToTable( this.module.GetSourceAssemblyAttributes(Context.IsRefAssembly), needsDummyParent: writingNetModule, isSecurity: false); } private void AddAssemblyAttributesToTable(IEnumerable<ICustomAttribute> assemblyAttributes, bool needsDummyParent, bool isSecurity) { Debug.Assert(this.IsFullMetadata); // parentToken is not relative EntityHandle parentHandle = Handle.AssemblyDefinition; foreach (ICustomAttribute customAttribute in assemblyAttributes) { if (needsDummyParent) { // When writing netmodules, assembly attributes are attached off the appropriate placeholder // System.Runtime.CompilerServices.AssemblyAttributesGoHere* type refs. This is the contract for publishing // assembly attributes in netmodules so they may be migrated to containing/referencing multi-module assemblies, // at multi-module assembly build time. parentHandle = GetDummyAssemblyAttributeParent(isSecurity, customAttribute.AllowMultiple); } AddCustomAttributeToTable(parentHandle, customAttribute); } } private TypeReferenceHandle GetDummyAssemblyAttributeParent(bool isSecurity, bool allowMultiple) { // Lazily get or create placeholder assembly attribute parent type ref for the given combination of // whether isSecurity and allowMultiple. Convert type ref row id to corresponding attribute parent tag. // Note that according to the defacto contract, although the placeholder type refs have CorLibrary as their // resolution scope, the types backing the placeholder type refs need not actually exist. int iS = isSecurity ? 1 : 0; int iM = allowMultiple ? 1 : 0; if (_dummyAssemblyAttributeParent[iS, iM].IsNil) { _dummyAssemblyAttributeParent[iS, iM] = metadata.AddTypeReference( resolutionScope: GetResolutionScopeHandle(module.GetCorLibrary(Context)), @namespace: metadata.GetOrAddString(dummyAssemblyAttributeParentNamespace), name: metadata.GetOrAddString(dummyAssemblyAttributeParentName + dummyAssemblyAttributeParentQualifier[iS, iM])); } return _dummyAssemblyAttributeParent[iS, iM]; } private void AddModuleAttributesToTable(CommonPEModuleBuilder module) { Debug.Assert(this.IsFullMetadata); AddCustomAttributesToTable(EntityHandle.ModuleDefinition, module.GetSourceModuleAttributes()); } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, TableIndex tableIndex) where T : IReference { int parentRowId = 1; foreach (var parent in parentList) { var parentHandle = MetadataTokens.Handle(tableIndex, parentRowId++); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } private void AddCustomAttributesToTable<T>(IEnumerable<T> parentList, Func<T, EntityHandle> getDefinitionHandle) where T : IReference { foreach (var parent in parentList) { EntityHandle parentHandle = getDefinitionHandle(parent); AddCustomAttributesToTable(parentHandle, parent.GetAttributes(Context)); } } protected virtual int AddCustomAttributesToTable(EntityHandle parentHandle, IEnumerable<ICustomAttribute> attributes) { int count = 0; foreach (var attr in attributes) { count++; AddCustomAttributeToTable(parentHandle, attr); } return count; } private void AddCustomAttributeToTable(EntityHandle parentHandle, ICustomAttribute customAttribute) { IMethodReference constructor = customAttribute.Constructor(Context, reportDiagnostics: true); if (constructor != null) { metadata.AddCustomAttribute( parent: parentHandle, constructor: GetCustomAttributeTypeCodedIndex(constructor), value: GetCustomAttributeSignatureIndex(customAttribute)); } } private void PopulateDeclSecurityTableRows() { if (module.OutputKind != OutputKind.NetModule) { this.PopulateDeclSecurityTableRowsFor(EntityHandle.AssemblyDefinition, module.GetSourceAssemblySecurityAttributes()); } foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (!typeDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetTypeDefinitionHandle(typeDef), typeDef.SecurityAttributes); } foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.HasDeclarativeSecurity) { continue; } this.PopulateDeclSecurityTableRowsFor(GetMethodDefinitionHandle(methodDef), methodDef.SecurityAttributes); } } private void PopulateDeclSecurityTableRowsFor(EntityHandle parentHandle, IEnumerable<SecurityAttribute> attributes) { OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute> groupedSecurityAttributes = null; foreach (SecurityAttribute securityAttribute in attributes) { groupedSecurityAttributes = groupedSecurityAttributes ?? OrderPreservingMultiDictionary<DeclarativeSecurityAction, ICustomAttribute>.GetInstance(); groupedSecurityAttributes.Add(securityAttribute.Action, securityAttribute.Attribute); } if (groupedSecurityAttributes == null) { return; } foreach (DeclarativeSecurityAction securityAction in groupedSecurityAttributes.Keys) { metadata.AddDeclarativeSecurityAttribute( parent: parentHandle, action: securityAction, permissionSet: GetPermissionSetBlobHandle(groupedSecurityAttributes[securityAction])); } groupedSecurityAttributes.Free(); } private void PopulateEventTableRows() { var eventDefs = this.GetEventDefs(); metadata.SetCapacity(TableIndex.Event, eventDefs.Count); foreach (IEventDefinition eventDef in eventDefs) { metadata.AddEvent( attributes: GetEventAttributes(eventDef), name: GetStringHandleForNameAndCheckLength(eventDef.Name, eventDef), type: GetTypeHandle(eventDef.GetType(Context))); } } private void PopulateExportedTypeTableRows() { if (!IsFullMetadata) { return; } var exportedTypes = module.GetExportedTypes(Context.Diagnostics); if (exportedTypes.Length == 0) { return; } metadata.SetCapacity(TableIndex.ExportedType, exportedTypes.Length); foreach (var exportedType in exportedTypes) { INestedTypeReference nestedRef; INamespaceTypeReference namespaceTypeRef; TypeAttributes attributes; StringHandle typeName; StringHandle typeNamespace; EntityHandle implementation; if ((namespaceTypeRef = exportedType.Type.AsNamespaceTypeReference) != null) { // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); typeNamespace = GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); implementation = GetExportedTypeImplementation(namespaceTypeRef); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic | Constants.TypeAttributes_TypeForwarder : TypeAttributes.Public; } else if ((nestedRef = exportedType.Type.AsNestedTypeReference) != null) { Debug.Assert(exportedType.ParentIndex != -1); // exported types are not emitted in EnC deltas (hence generation 0): string mangledTypeName = GetMangledName(nestedRef, generation: 0); typeName = GetStringHandleForNameAndCheckLength(mangledTypeName, nestedRef); typeNamespace = default(StringHandle); implementation = MetadataTokens.ExportedTypeHandle(exportedType.ParentIndex + 1); attributes = exportedType.IsForwarder ? TypeAttributes.NotPublic : TypeAttributes.NestedPublic; } else { throw ExceptionUtilities.UnexpectedValue(exportedType); } metadata.AddExportedType( attributes: attributes, @namespace: typeNamespace, name: typeName, implementation: implementation, typeDefinitionId: exportedType.IsForwarder ? 0 : MetadataTokens.GetToken(exportedType.Type.TypeDef)); } } private void PopulateFieldLayoutTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.ContainingTypeDefinition.Layout != LayoutKind.Explicit || fieldDef.IsStatic) { continue; } metadata.AddFieldLayout( field: GetFieldDefinitionHandle(fieldDef), offset: fieldDef.Offset); } } private void PopulateFieldMarshalTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (!fieldDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = fieldDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(fieldDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetFieldDefinitionHandle(fieldDef), descriptor: descriptor); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { if (!parDef.IsMarshalledExplicitly) { continue; } var marshallingInformation = parDef.MarshallingInformation; BlobHandle descriptor = (marshallingInformation != null) ? GetMarshallingDescriptorHandle(marshallingInformation) : GetMarshallingDescriptorHandle(parDef.MarshallingDescriptor); metadata.AddMarshallingDescriptor( parent: GetParameterHandle(parDef), descriptor: descriptor); } } private void PopulateFieldRvaTableRows(BlobBuilder mappedFieldDataWriter) { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { if (fieldDef.MappedData.IsDefault) { continue; } int offset = mappedFieldDataWriter.Count; mappedFieldDataWriter.WriteBytes(fieldDef.MappedData); mappedFieldDataWriter.Align(ManagedPEBuilder.MappedFieldDataAlignment); metadata.AddFieldRelativeVirtualAddress( field: GetFieldDefinitionHandle(fieldDef), offset: offset); } } private void PopulateFieldTableRows() { var fieldDefs = this.GetFieldDefs(); metadata.SetCapacity(TableIndex.Field, fieldDefs.Count); foreach (IFieldDefinition fieldDef in fieldDefs) { if (fieldDef.IsContextualNamedEntity) { ((IContextualNamedEntity)fieldDef).AssociateWithMetadataWriter(this); } metadata.AddFieldDefinition( attributes: GetFieldAttributes(fieldDef), name: GetStringHandleForNameAndCheckLength(fieldDef.Name, fieldDef), signature: GetFieldSignatureIndex(fieldDef)); } } private void PopulateConstantTableRows() { foreach (IFieldDefinition fieldDef in this.GetFieldDefs()) { var constant = fieldDef.GetCompileTimeValue(Context); if (constant == null) { continue; } metadata.AddConstant( parent: GetFieldDefinitionHandle(fieldDef), value: constant.Value); } foreach (IParameterDefinition parDef in this.GetParameterDefs()) { var defaultValue = parDef.GetDefaultValue(Context); if (defaultValue == null) { continue; } metadata.AddConstant( parent: GetParameterHandle(parDef), value: defaultValue.Value); } foreach (IPropertyDefinition propDef in this.GetPropertyDefs()) { if (!propDef.HasDefaultValue) { continue; } metadata.AddConstant( parent: GetPropertyDefIndex(propDef), value: propDef.DefaultValue.Value); } } private void PopulateFileTableRows() { ISourceAssemblySymbolInternal assembly = module.SourceAssemblyOpt; if (assembly == null) { return; } var hashAlgorithm = assembly.HashAlgorithm; metadata.SetCapacity(TableIndex.File, _fileRefList.Count); foreach (IFileReference fileReference in _fileRefList) { metadata.AddAssemblyFile( name: GetStringHandleForPathAndCheckLength(fileReference.FileName), hashValue: metadata.GetOrAddBlob(fileReference.GetHashValue(hashAlgorithm)), containsMetadata: fileReference.HasMetadata); } } private void PopulateGenericParameters( ImmutableArray<IGenericParameter> sortedGenericParameters) { foreach (IGenericParameter genericParameter in sortedGenericParameters) { // CONSIDER: The CLI spec doesn't mention a restriction on the Name column of the GenericParam table, // but they go in the same string heap as all the other declaration names, so it stands to reason that // they should be restricted in the same way. var genericParameterHandle = metadata.AddGenericParameter( parent: GetDeclaringTypeOrMethodHandle(genericParameter), attributes: GetGenericParameterAttributes(genericParameter), name: GetStringHandleForNameAndCheckLength(genericParameter.Name, genericParameter), index: genericParameter.Index); foreach (var refWithAttributes in genericParameter.GetConstraints(Context)) { var genericConstraintHandle = metadata.AddGenericParameterConstraint( genericParameter: genericParameterHandle, constraint: GetTypeHandle(refWithAttributes.TypeRef)); AddCustomAttributesToTable(genericConstraintHandle, refWithAttributes.Attributes); } } } private void PopulateImplMapTableRows() { foreach (IMethodDefinition methodDef in this.GetMethodDefs()) { if (!methodDef.IsPlatformInvoke) { continue; } var data = methodDef.PlatformInvokeData; string entryPointName = data.EntryPointName; StringHandle importName = entryPointName != null && entryPointName != methodDef.Name ? GetStringHandleForNameAndCheckLength(entryPointName, methodDef) : metadata.GetOrAddString(methodDef.Name); // Length checked while populating the method def table. metadata.AddMethodImport( method: GetMethodDefinitionHandle(methodDef), attributes: data.Flags, name: importName, module: GetModuleReferenceHandle(data.ModuleName)); } } private void PopulateInterfaceImplTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { var typeDefHandle = GetTypeDefinitionHandle(typeDef); foreach (var interfaceImpl in typeDef.Interfaces(Context)) { var handle = metadata.AddInterfaceImplementation( type: typeDefHandle, implementedInterface: GetTypeHandle(interfaceImpl.TypeRef)); AddCustomAttributesToTable(handle, interfaceImpl.Attributes); } } } private void PopulateManifestResourceTableRows(BlobBuilder resourceDataWriter, BlobBuilder dynamicAnalysisDataOpt) { if (dynamicAnalysisDataOpt != null) { metadata.AddManifestResource( attributes: ManifestResourceAttributes.Private, name: metadata.GetOrAddString("<DynamicAnalysisData>"), implementation: default(EntityHandle), offset: GetManagedResourceOffset(dynamicAnalysisDataOpt, resourceDataWriter) ); } foreach (var resource in this.module.GetResources(Context)) { EntityHandle implementation; if (resource.ExternalFile != null) { // Length checked on insertion into the file table. implementation = GetAssemblyFileHandle(resource.ExternalFile); } else { // This is an embedded resource, we don't support references to resources from referenced assemblies. implementation = default(EntityHandle); } metadata.AddManifestResource( attributes: resource.IsPublic ? ManifestResourceAttributes.Public : ManifestResourceAttributes.Private, name: GetStringHandleForNameAndCheckLength(resource.Name), implementation: implementation, offset: GetManagedResourceOffset(resource, resourceDataWriter)); } // the stream should be aligned: Debug.Assert((resourceDataWriter.Count % ManagedPEBuilder.ManagedResourcesDataAlignment) == 0); } private void PopulateMemberRefTableRows() { var memberRefs = this.GetMemberRefs(); metadata.SetCapacity(TableIndex.MemberRef, memberRefs.Count); foreach (ITypeMemberReference memberRef in memberRefs) { metadata.AddMemberReference( parent: GetMemberReferenceParent(memberRef), name: GetStringHandleForNameAndCheckLength(memberRef.Name, memberRef), signature: GetMemberReferenceSignatureHandle(memberRef)); } } private void PopulateMethodImplTableRows() { metadata.SetCapacity(TableIndex.MethodImpl, methodImplList.Count); foreach (MethodImplementation methodImplementation in this.methodImplList) { metadata.AddMethodImplementation( type: GetTypeDefinitionHandle(methodImplementation.ContainingType), methodBody: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementingMethod), methodDeclaration: GetMethodDefinitionOrReferenceHandle(methodImplementation.ImplementedMethod)); } } private void PopulateMethodSpecTableRows() { var methodSpecs = this.GetMethodSpecs(); metadata.SetCapacity(TableIndex.MethodSpec, methodSpecs.Count); foreach (IGenericMethodInstanceReference genericMethodInstanceReference in methodSpecs) { metadata.AddMethodSpecification( method: GetMethodDefinitionOrReferenceHandle(genericMethodInstanceReference.GetGenericMethod(Context)), instantiation: GetMethodSpecificationBlobHandle(genericMethodInstanceReference)); } } private void PopulateMethodTableRows(int[] methodBodyOffsets) { var methodDefs = this.GetMethodDefs(); metadata.SetCapacity(TableIndex.MethodDef, methodDefs.Count); int i = 0; foreach (IMethodDefinition methodDef in methodDefs) { metadata.AddMethodDefinition( attributes: GetMethodAttributes(methodDef), implAttributes: methodDef.GetImplementationAttributes(Context), name: GetStringHandleForNameAndCheckLength(methodDef.Name, methodDef), signature: GetMethodSignatureHandle(methodDef), bodyOffset: methodBodyOffsets[i], parameterList: GetFirstParameterHandle(methodDef)); i++; } } private void PopulateMethodSemanticsTableRows() { var propertyDefs = this.GetPropertyDefs(); var eventDefs = this.GetEventDefs(); // an estimate, not necessarily accurate. metadata.SetCapacity(TableIndex.MethodSemantics, propertyDefs.Count * 2 + eventDefs.Count * 2); foreach (IPropertyDefinition propertyDef in this.GetPropertyDefs()) { var association = GetPropertyDefIndex(propertyDef); foreach (IMethodReference accessorMethod in propertyDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == propertyDef.Setter) { semantics = MethodSemanticsAttributes.Setter; } else if (accessorMethod == propertyDef.Getter) { semantics = MethodSemanticsAttributes.Getter; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } foreach (IEventDefinition eventDef in this.GetEventDefs()) { var association = GetEventDefinitionHandle(eventDef); foreach (IMethodReference accessorMethod in eventDef.GetAccessors(Context)) { MethodSemanticsAttributes semantics; if (accessorMethod == eventDef.Adder) { semantics = MethodSemanticsAttributes.Adder; } else if (accessorMethod == eventDef.Remover) { semantics = MethodSemanticsAttributes.Remover; } else if (accessorMethod == eventDef.Caller) { semantics = MethodSemanticsAttributes.Raiser; } else { semantics = MethodSemanticsAttributes.Other; } metadata.AddMethodSemantics( association: association, semantics: semantics, methodDefinition: GetMethodDefinitionHandle(accessorMethod.GetResolvedMethod(Context))); } } } private void PopulateModuleRefTableRows() { var moduleRefs = this.GetModuleRefs(); metadata.SetCapacity(TableIndex.ModuleRef, moduleRefs.Count); foreach (string moduleName in moduleRefs) { metadata.AddModuleReference(GetStringHandleForPathAndCheckLength(moduleName)); } } private void PopulateModuleTableRow(out Blob mvidFixup) { CheckPathLength(this.module.ModuleName); GuidHandle mvidHandle; Guid mvid = this.module.SerializationProperties.PersistentIdentifier; if (mvid != default(Guid)) { // MVID is specified upfront when emitting EnC delta: mvidHandle = metadata.GetOrAddGuid(mvid); mvidFixup = default(Blob); } else { // The guid will be filled in later: var reservedGuid = metadata.ReserveGuid(); mvidFixup = reservedGuid.Content; mvidHandle = reservedGuid.Handle; reservedGuid.CreateWriter().WriteBytes(0, mvidFixup.Length); } metadata.AddModule( generation: this.Generation, moduleName: metadata.GetOrAddString(this.module.ModuleName), mvid: mvidHandle, encId: metadata.GetOrAddGuid(EncId), encBaseId: metadata.GetOrAddGuid(EncBaseId)); } private void PopulateParamTableRows() { var parameterDefs = this.GetParameterDefs(); metadata.SetCapacity(TableIndex.Param, parameterDefs.Count); foreach (IParameterDefinition parDef in parameterDefs) { metadata.AddParameter( attributes: GetParameterAttributes(parDef), sequenceNumber: (parDef is ReturnValueParameter) ? 0 : parDef.Index + 1, name: GetStringHandleForNameAndCheckLength(parDef.Name, parDef)); } } private void PopulatePropertyTableRows() { var propertyDefs = this.GetPropertyDefs(); metadata.SetCapacity(TableIndex.Property, propertyDefs.Count); foreach (IPropertyDefinition propertyDef in propertyDefs) { metadata.AddProperty( attributes: GetPropertyAttributes(propertyDef), name: GetStringHandleForNameAndCheckLength(propertyDef.Name, propertyDef), signature: GetPropertySignatureHandle(propertyDef)); } } private void PopulateTypeDefTableRows() { var typeDefs = this.GetTypeDefs(); metadata.SetCapacity(TableIndex.TypeDef, typeDefs.Count); foreach (INamedTypeDefinition typeDef in typeDefs) { INamespaceTypeDefinition namespaceType = typeDef.AsNamespaceTypeDefinition(Context); var moduleBuilder = Context.Module; int generation = moduleBuilder.GetTypeDefinitionGeneration(typeDef); string mangledTypeName = GetMangledName(typeDef, generation); ITypeReference baseType = typeDef.GetBaseClass(Context); metadata.AddTypeDefinition( attributes: GetTypeAttributes(typeDef), @namespace: (namespaceType != null) ? GetStringHandleForNamespaceAndCheckLength(namespaceType, mangledTypeName) : default(StringHandle), name: GetStringHandleForNameAndCheckLength(mangledTypeName, typeDef), baseType: (baseType != null) ? GetTypeHandle(baseType) : default(EntityHandle), fieldList: GetFirstFieldDefinitionHandle(typeDef), methodList: GetFirstMethodDefinitionHandle(typeDef)); } } private void PopulateNestedClassTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { INestedTypeDefinition nestedTypeDef = typeDef.AsNestedTypeDefinition(Context); if (nestedTypeDef == null) { continue; } metadata.AddNestedType( type: GetTypeDefinitionHandle(typeDef), enclosingType: GetTypeDefinitionHandle(nestedTypeDef.ContainingTypeDefinition)); } } private void PopulateClassLayoutTableRows() { foreach (ITypeDefinition typeDef in this.GetTypeDefs()) { if (typeDef.Alignment == 0 && typeDef.SizeOf == 0) { continue; } metadata.AddTypeLayout( type: GetTypeDefinitionHandle(typeDef), packingSize: typeDef.Alignment, size: typeDef.SizeOf); } } private void PopulateTypeRefTableRows() { var typeRefs = this.GetTypeRefs(); metadata.SetCapacity(TableIndex.TypeRef, typeRefs.Count); foreach (ITypeReference typeRef in typeRefs) { EntityHandle resolutionScope; StringHandle name; StringHandle @namespace; INestedTypeReference nestedTypeRef = typeRef.AsNestedTypeReference; if (nestedTypeRef != null) { ITypeReference scopeTypeRef; ISpecializedNestedTypeReference sneTypeRef = nestedTypeRef.AsSpecializedNestedTypeReference; if (sneTypeRef != null) { scopeTypeRef = sneTypeRef.GetUnspecializedVersion(Context).GetContainingType(Context); } else { scopeTypeRef = nestedTypeRef.GetContainingType(Context); } resolutionScope = GetTypeReferenceHandle(scopeTypeRef); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(nestedTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, nestedTypeRef); @namespace = default(StringHandle); } else { INamespaceTypeReference namespaceTypeRef = typeRef.AsNamespaceTypeReference; if (namespaceTypeRef == null) { throw ExceptionUtilities.UnexpectedValue(typeRef); } resolutionScope = this.GetResolutionScopeHandle(namespaceTypeRef.GetUnit(Context)); // It's not possible to reference newer versions of reloadable types from another assembly, hence generation 0: // TODO: https://github.com/dotnet/roslyn/issues/54981 string mangledTypeName = GetMangledName(namespaceTypeRef, generation: 0); name = this.GetStringHandleForNameAndCheckLength(mangledTypeName, namespaceTypeRef); @namespace = this.GetStringHandleForNamespaceAndCheckLength(namespaceTypeRef, mangledTypeName); } metadata.AddTypeReference( resolutionScope: resolutionScope, @namespace: @namespace, name: name); } } private void PopulateTypeSpecTableRows() { var typeSpecs = this.GetTypeSpecs(); metadata.SetCapacity(TableIndex.TypeSpec, typeSpecs.Count); foreach (ITypeReference typeSpec in typeSpecs) { metadata.AddTypeSpecification(GetTypeSpecSignatureIndex(typeSpec)); } } private void PopulateStandaloneSignatures() { var signatures = GetStandaloneSignatureBlobHandles(); foreach (BlobHandle signature in signatures) { metadata.AddStandaloneSignature(signature); } } private int[] SerializeThrowNullMethodBodies(BlobBuilder ilBuilder) { Debug.Assert(MetadataOnly); var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; int bodyOffsetCache = -1; int methodRid = 0; foreach (IMethodDefinition method in methods) { if (method.HasBody()) { if (bodyOffsetCache == -1) { bodyOffsetCache = ilBuilder.Count; ilBuilder.WriteBytes(ThrowNullEncodedBody); } bodyOffsets[methodRid] = bodyOffsetCache; } else { bodyOffsets[methodRid] = -1; } methodRid++; } return bodyOffsets; } private int[] SerializeMethodBodies(BlobBuilder ilBuilder, PdbWriter nativePdbWriterOpt, out Blob mvidStringFixup) { CustomDebugInfoWriter customDebugInfoWriter = (nativePdbWriterOpt != null) ? new CustomDebugInfoWriter(nativePdbWriterOpt) : null; var methods = this.GetMethodDefs(); int[] bodyOffsets = new int[methods.Count]; var lastLocalVariableHandle = default(LocalVariableHandle); var lastLocalConstantHandle = default(LocalConstantHandle); var encoder = new MethodBodyStreamEncoder(ilBuilder); var mvidStringHandle = default(UserStringHandle); mvidStringFixup = default(Blob); int methodRid = 1; foreach (IMethodDefinition method in methods) { _cancellationToken.ThrowIfCancellationRequested(); int bodyOffset; IMethodBody body; StandaloneSignatureHandle localSignatureHandleOpt; if (method.HasBody()) { body = method.GetBody(Context); if (body != null) { localSignatureHandleOpt = this.SerializeLocalVariablesSignature(body); // TODO: consider parallelizing these (local signature tokens can be piped into IL serialization & debug info generation) bodyOffset = SerializeMethodBody(encoder, body, localSignatureHandleOpt, ref mvidStringHandle, ref mvidStringFixup); nativePdbWriterOpt?.SerializeDebugInfo(body, localSignatureHandleOpt, customDebugInfoWriter); } else { bodyOffset = 0; localSignatureHandleOpt = default(StandaloneSignatureHandle); } } else { // 0 is actually written to metadata when the row is serialized bodyOffset = -1; body = null; localSignatureHandleOpt = default(StandaloneSignatureHandle); } if (_debugMetadataOpt != null) { // methodRid is based on this delta but for async state machine debug info we need the "real" row number // of the method aggregated across generations var aggregateMethodRid = MetadataTokens.GetRowNumber(GetMethodDefinitionHandle(method)); SerializeMethodDebugInfo(body, methodRid, aggregateMethodRid, localSignatureHandleOpt, ref lastLocalVariableHandle, ref lastLocalConstantHandle); } _dynamicAnalysisDataWriterOpt?.SerializeMethodDynamicAnalysisData(body); bodyOffsets[methodRid - 1] = bodyOffset; methodRid++; } return bodyOffsets; } private int SerializeMethodBody(MethodBodyStreamEncoder encoder, IMethodBody methodBody, StandaloneSignatureHandle localSignatureHandleOpt, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { int ilLength = methodBody.IL.Length; var exceptionRegions = methodBody.ExceptionRegions; bool isSmallBody = ilLength < 64 && methodBody.MaxStack <= 8 && localSignatureHandleOpt.IsNil && exceptionRegions.Length == 0; var smallBodyKey = (methodBody.IL, methodBody.AreLocalsZeroed); // Check if an identical method body has already been serialized. // If so, use the RVA of the already serialized one. // Note that we don't need to rewrite the fake tokens in the body before looking it up. // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 int bodyOffset; if (!_deterministic && isSmallBody && _smallMethodBodies.TryGetValue(smallBodyKey, out bodyOffset)) { return bodyOffset; } var encodedBody = encoder.AddMethodBody( codeSize: methodBody.IL.Length, maxStack: methodBody.MaxStack, exceptionRegionCount: exceptionRegions.Length, hasSmallExceptionRegions: MayUseSmallExceptionHeaders(exceptionRegions), localVariablesSignature: localSignatureHandleOpt, attributes: (methodBody.AreLocalsZeroed ? MethodBodyAttributes.InitLocals : 0), hasDynamicStackAllocation: methodBody.HasStackalloc); // Don't do small body method caching during deterministic builds until this issue is fixed // https://github.com/dotnet/roslyn/issues/7595 if (isSmallBody && !_deterministic) { _smallMethodBodies.Add(smallBodyKey, encodedBody.Offset); } WriteInstructions(encodedBody.Instructions, methodBody.IL, ref mvidStringHandle, ref mvidStringFixup); SerializeMethodBodyExceptionHandlerTable(encodedBody.ExceptionRegions, exceptionRegions); return encodedBody.Offset; } /// <summary> /// Serialize the method local signature to the blob. /// </summary> /// <returns>Standalone signature token</returns> protected virtual StandaloneSignatureHandle SerializeLocalVariablesSignature(IMethodBody body) { Debug.Assert(!_tableIndicesAreComplete); var localVariables = body.LocalVariables; if (localVariables.Length == 0) { return default(StandaloneSignatureHandle); } var builder = PooledBlobBuilder.GetInstance(); var encoder = new BlobEncoder(builder).LocalVariableSignature(localVariables.Length); foreach (ILocalDefinition local in localVariables) { SerializeLocalVariableType(encoder.AddVariable(), local); } BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var handle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return handle; } protected void SerializeLocalVariableType(LocalVariableTypeEncoder encoder, ILocalDefinition local) { if (local.CustomModifiers.Length > 0) { SerializeCustomModifiers(encoder.CustomModifiers(), local.CustomModifiers); } if (module.IsPlatformType(local.Type, PlatformType.SystemTypedReference)) { encoder.TypedReference(); return; } SerializeTypeReference(encoder.Type(local.IsReference, local.IsPinned), local.Type); } internal StandaloneSignatureHandle SerializeLocalConstantStandAloneSignature(ILocalDefinition localConstant) { var builder = PooledBlobBuilder.GetInstance(); var typeEncoder = new BlobEncoder(builder).FieldSignature(); if (localConstant.CustomModifiers.Length > 0) { SerializeCustomModifiers(typeEncoder.CustomModifiers(), localConstant.CustomModifiers); } SerializeTypeReference(typeEncoder, localConstant.Type); BlobHandle blobIndex = metadata.GetOrAddBlob(builder); var signatureHandle = GetOrAddStandaloneSignatureHandle(blobIndex); builder.Free(); return signatureHandle; } private static byte ReadByte(ImmutableArray<byte> buffer, int pos) { return buffer[pos]; } private static int ReadInt32(ImmutableArray<byte> buffer, int pos) { return buffer[pos] | buffer[pos + 1] << 8 | buffer[pos + 2] << 16 | buffer[pos + 3] << 24; } private EntityHandle GetHandle(object reference) { return reference switch { ITypeReference typeReference => GetTypeHandle(typeReference), IFieldReference fieldReference => GetFieldHandle(fieldReference), IMethodReference methodReference => GetMethodHandle(methodReference), ISignature signature => GetStandaloneSignatureHandle(signature), _ => throw ExceptionUtilities.UnexpectedValue(reference) }; } private EntityHandle ResolveEntityHandleFromPseudoToken(int pseudoSymbolToken) { int index = pseudoSymbolToken; var entity = _pseudoSymbolTokenToReferenceMap[index]; if (entity != null) { // EDMAURER since method bodies are not visited as they are in CCI, the operations // that would have been done on them are done here. if (entity is IReference reference) { _referenceVisitor.VisitMethodBodyReference(reference); } else if (entity is ISignature signature) { _referenceVisitor.VisitSignature(signature); } EntityHandle handle = GetHandle(entity); _pseudoSymbolTokenToTokenMap[index] = handle; _pseudoSymbolTokenToReferenceMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoSymbolTokenToTokenMap[index]; } private UserStringHandle ResolveUserStringHandleFromPseudoToken(int pseudoStringToken) { int index = pseudoStringToken; var str = _pseudoStringTokenToStringMap[index]; if (str != null) { var handle = GetOrAddUserString(str); _pseudoStringTokenToTokenMap[index] = handle; _pseudoStringTokenToStringMap[index] = null; // Set to null to bypass next lookup return handle; } return _pseudoStringTokenToTokenMap[index]; } private UserStringHandle GetOrAddUserString(string str) { if (!_userStringTokenOverflow) { try { return metadata.GetOrAddUserString(str); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(UserStringHandle); } private ReservedBlob<UserStringHandle> ReserveUserString(int length) { if (!_userStringTokenOverflow) { try { return metadata.ReserveUserString(length); } catch (ImageFormatLimitationException) { this.Context.Diagnostics.Add(this.messageProvider.CreateDiagnostic(this.messageProvider.ERR_TooManyUserStrings, NoLocation.Singleton)); _userStringTokenOverflow = true; } } return default(ReservedBlob<UserStringHandle>); } internal const uint LiteralMethodDefinitionToken = 0x80000000; internal const uint LiteralGreatestMethodDefinitionToken = 0x40000000; internal const uint SourceDocumentIndex = 0x20000000; internal const uint ModuleVersionIdStringToken = 0x80000000; private void WriteInstructions(Blob finalIL, ImmutableArray<byte> generatedIL, ref UserStringHandle mvidStringHandle, ref Blob mvidStringFixup) { // write the raw body first and then patch tokens: var writer = new BlobWriter(finalIL); writer.WriteBytes(generatedIL); writer.Offset = 0; int offset = 0; while (offset < generatedIL.Length) { var operandType = InstructionOperandTypes.ReadOperandType(generatedIL, ref offset); switch (operandType) { case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineSig: { int pseudoToken = ReadInt32(generatedIL, offset); int token = 0; // If any bits in the high-order byte of the pseudotoken are nonzero, replace the opcode with Ldc_i4 // and either clear the high-order byte in the pseudotoken or ignore the pseudotoken. // This is a trick to enable loading raw metadata token indices as integers. if (operandType == OperandType.InlineTok) { int tokenMask = pseudoToken & unchecked((int)0xff000000); if (tokenMask != 0 && (uint)pseudoToken != 0xffffffff) { Debug.Assert(ReadByte(generatedIL, offset - 1) == (byte)ILOpCode.Ldtoken); writer.Offset = offset - 1; writer.WriteByte((byte)ILOpCode.Ldc_i4); switch ((uint)tokenMask) { case LiteralMethodDefinitionToken: // Crash the compiler if pseudo token fails to resolve to a MethodDefinitionHandle. var handle = (MethodDefinitionHandle)ResolveEntityHandleFromPseudoToken(pseudoToken & 0x00ffffff); token = MetadataTokens.GetToken(handle) & 0x00ffffff; break; case LiteralGreatestMethodDefinitionToken: token = GreatestMethodDefIndex; break; case SourceDocumentIndex: token = _dynamicAnalysisDataWriterOpt.GetOrAddDocument(((CommonPEModuleBuilder)module).GetSourceDocumentFromIndex((uint)(pseudoToken & 0x00ffffff))); break; default: throw ExceptionUtilities.UnexpectedValue(tokenMask); } } } writer.Offset = offset; writer.WriteInt32(token == 0 ? MetadataTokens.GetToken(ResolveEntityHandleFromPseudoToken(pseudoToken)) : token); offset += 4; break; } case OperandType.InlineString: { writer.Offset = offset; int pseudoToken = ReadInt32(generatedIL, offset); UserStringHandle handle; if ((uint)pseudoToken == ModuleVersionIdStringToken) { // The pseudotoken encoding indicates that the string should refer to a textual encoding of the // current module's module version ID (such that the MVID can be realized using Guid.Parse). // The value cannot be determined until very late in the compilation, so reserve a slot for it now and fill in the value later. if (mvidStringHandle.IsNil) { const int guidStringLength = 36; Debug.Assert(guidStringLength == default(Guid).ToString().Length); var reserved = ReserveUserString(guidStringLength); mvidStringHandle = reserved.Handle; mvidStringFixup = reserved.Content; } handle = mvidStringHandle; } else { handle = ResolveUserStringHandleFromPseudoToken(pseudoToken); } writer.WriteInt32(MetadataTokens.GetToken(handle)); offset += 4; break; } case OperandType.InlineBrTarget: case OperandType.InlineI: case OperandType.ShortInlineR: offset += 4; break; case OperandType.InlineSwitch: int argCount = ReadInt32(generatedIL, offset); // skip switch arguments count and arguments offset += (argCount + 1) * 4; break; case OperandType.InlineI8: case OperandType.InlineR: offset += 8; break; case OperandType.InlineNone: break; case OperandType.InlineVar: offset += 2; break; case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineI: case OperandType.ShortInlineVar: offset += 1; break; default: throw ExceptionUtilities.UnexpectedValue(operandType); } } } private void SerializeMethodBodyExceptionHandlerTable(ExceptionRegionEncoder encoder, ImmutableArray<ExceptionHandlerRegion> regions) { foreach (var region in regions) { var exceptionType = region.ExceptionType; encoder.Add( region.HandlerKind, region.TryStartOffset, region.TryLength, region.HandlerStartOffset, region.HandlerLength, (exceptionType != null) ? GetTypeHandle(exceptionType) : default(EntityHandle), region.FilterDecisionStartOffset); } } private static bool MayUseSmallExceptionHeaders(ImmutableArray<ExceptionHandlerRegion> exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallRegionCount(exceptionRegions.Length)) { return false; } foreach (var region in exceptionRegions) { if (!ExceptionRegionEncoder.IsSmallExceptionRegion(region.TryStartOffset, region.TryLength) || !ExceptionRegionEncoder.IsSmallExceptionRegion(region.HandlerStartOffset, region.HandlerLength)) { return false; } } return true; } private void SerializeParameterInformation(ParameterTypeEncoder encoder, IParameterTypeInformation parameterTypeInformation) { var type = parameterTypeInformation.GetType(Context); if (module.IsPlatformType(type, PlatformType.SystemTypedReference)) { Debug.Assert(!parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); encoder.TypedReference(); } else { Debug.Assert(parameterTypeInformation.RefCustomModifiers.Length == 0 || parameterTypeInformation.IsByReference); SerializeCustomModifiers(encoder.CustomModifiers(), parameterTypeInformation.RefCustomModifiers); var typeEncoder = encoder.Type(parameterTypeInformation.IsByReference); SerializeCustomModifiers(typeEncoder.CustomModifiers(), parameterTypeInformation.CustomModifiers); SerializeTypeReference(typeEncoder, type); } } private void SerializeFieldSignature(IFieldReference fieldReference, BlobBuilder builder) { var typeEncoder = new BlobEncoder(builder).FieldSignature(); SerializeTypeReference(typeEncoder, fieldReference.GetType(Context)); } private void SerializeMethodSpecificationSignature(BlobBuilder builder, IGenericMethodInstanceReference genericMethodInstanceReference) { var argsEncoder = new BlobEncoder(builder).MethodSpecificationSignature(genericMethodInstanceReference.GetGenericMethod(Context).GenericParameterCount); foreach (ITypeReference genericArgument in genericMethodInstanceReference.GetGenericArguments(Context)) { ITypeReference typeRef = genericArgument; SerializeTypeReference(argsEncoder.AddArgument(), typeRef); } } private void SerializeCustomAttributeSignature(ICustomAttribute customAttribute, BlobBuilder builder) { var parameters = customAttribute.Constructor(Context, reportDiagnostics: false).GetParameters(Context); var arguments = customAttribute.GetArguments(Context); Debug.Assert(parameters.Length == arguments.Length); FixedArgumentsEncoder fixedArgsEncoder; CustomAttributeNamedArgumentsEncoder namedArgsEncoder; new BlobEncoder(builder).CustomAttributeSignature(out fixedArgsEncoder, out namedArgsEncoder); for (int i = 0; i < parameters.Length; i++) { SerializeMetadataExpression(fixedArgsEncoder.AddArgument(), arguments[i], parameters[i].GetType(Context)); } SerializeCustomAttributeNamedArguments(namedArgsEncoder.Count(customAttribute.NamedArgumentCount), customAttribute); } private void SerializeCustomAttributeNamedArguments(NamedArgumentsEncoder encoder, ICustomAttribute customAttribute) { foreach (IMetadataNamedArgument namedArgument in customAttribute.GetNamedArguments(Context)) { NamedArgumentTypeEncoder typeEncoder; NameEncoder nameEncoder; LiteralEncoder literalEncoder; encoder.AddArgument(namedArgument.IsField, out typeEncoder, out nameEncoder, out literalEncoder); SerializeNamedArgumentType(typeEncoder, namedArgument.Type); nameEncoder.Name(namedArgument.ArgumentName); SerializeMetadataExpression(literalEncoder, namedArgument.ArgumentValue, namedArgument.Type); } } private void SerializeNamedArgumentType(NamedArgumentTypeEncoder encoder, ITypeReference type) { if (type is IArrayTypeReference arrayType) { SerializeCustomAttributeArrayType(encoder.SZArray(), arrayType); } else if (module.IsPlatformType(type, PlatformType.SystemObject)) { encoder.Object(); } else { SerializeCustomAttributeElementType(encoder.ScalarType(), type); } } private void SerializeMetadataExpression(LiteralEncoder encoder, IMetadataExpression expression, ITypeReference targetType) { if (expression is MetadataCreateArray a) { ITypeReference targetElementType; VectorEncoder vectorEncoder; if (!(targetType is IArrayTypeReference targetArrayType)) { // implicit conversion from array to object Debug.Assert(this.module.IsPlatformType(targetType, PlatformType.SystemObject)); CustomAttributeArrayTypeEncoder arrayTypeEncoder; encoder.TaggedVector(out arrayTypeEncoder, out vectorEncoder); SerializeCustomAttributeArrayType(arrayTypeEncoder, a.ArrayType); targetElementType = a.ElementType; } else { vectorEncoder = encoder.Vector(); // In FixedArg the element type of the parameter array has to match the element type of the argument array, // but in NamedArg T[] can be assigned to object[]. In that case we need to encode the arguments using // the parameter element type not the argument element type. targetElementType = targetArrayType.GetElementType(this.Context); } var literalsEncoder = vectorEncoder.Count(a.Elements.Length); foreach (IMetadataExpression elemValue in a.Elements) { SerializeMetadataExpression(literalsEncoder.AddLiteral(), elemValue, targetElementType); } } else { ScalarEncoder scalarEncoder; MetadataConstant c = expression as MetadataConstant; if (this.module.IsPlatformType(targetType, PlatformType.SystemObject)) { CustomAttributeElementTypeEncoder typeEncoder; encoder.TaggedScalar(out typeEncoder, out scalarEncoder); // special case null argument assigned to Object parameter - treat as null string if (c != null && c.Value == null && this.module.IsPlatformType(c.Type, PlatformType.SystemObject)) { typeEncoder.String(); } else { SerializeCustomAttributeElementType(typeEncoder, expression.Type); } } else { scalarEncoder = encoder.Scalar(); } if (c != null) { if (c.Type is IArrayTypeReference) { scalarEncoder.NullArray(); return; } Debug.Assert(!module.IsPlatformType(c.Type, PlatformType.SystemType) || c.Value == null); scalarEncoder.Constant(c.Value); } else { scalarEncoder.SystemType(((MetadataTypeOf)expression).TypeToGet.GetSerializedTypeName(Context)); } } } private void SerializeMarshallingDescriptor(IMarshallingInformation marshallingInformation, BlobBuilder writer) { writer.WriteCompressedInteger((int)marshallingInformation.UnmanagedType); switch (marshallingInformation.UnmanagedType) { case UnmanagedType.ByValArray: // NATIVE_TYPE_FIXEDARRAY Debug.Assert(marshallingInformation.NumberOfElements >= 0); writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); if (marshallingInformation.ElementType >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.ElementType); } break; case Constants.UnmanagedType_CustomMarshaler: writer.WriteUInt16(0); // padding object marshaller = marshallingInformation.GetCustomMarshaller(Context); switch (marshaller) { case ITypeReference marshallerTypeRef: this.SerializeTypeName(marshallerTypeRef, writer); break; case null: writer.WriteByte(0); break; default: writer.WriteSerializedString((string)marshaller); break; } var arg = marshallingInformation.CustomMarshallerRuntimeArgument; if (arg != null) { writer.WriteSerializedString(arg); } else { writer.WriteByte(0); } break; case UnmanagedType.LPArray: // NATIVE_TYPE_ARRAY Debug.Assert(marshallingInformation.ElementType >= 0); writer.WriteCompressedInteger((int)marshallingInformation.ElementType); if (marshallingInformation.ParamIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.ParamIndex); if (marshallingInformation.NumberOfElements >= 0) { writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(1); // The parameter number is valid } } else if (marshallingInformation.NumberOfElements >= 0) { writer.WriteByte(0); // Dummy parameter value emitted so that NumberOfElements can be in a known position writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); writer.WriteByte(0); // The parameter number is not valid } break; case Constants.UnmanagedType_SafeArray: if (marshallingInformation.SafeArrayElementSubtype >= 0) { writer.WriteCompressedInteger((int)marshallingInformation.SafeArrayElementSubtype); var elementType = marshallingInformation.GetSafeArrayElementUserDefinedSubtype(Context); if (elementType != null) { this.SerializeTypeName(elementType, writer); } } break; case UnmanagedType.ByValTStr: // NATIVE_TYPE_FIXEDSYSSTRING writer.WriteCompressedInteger(marshallingInformation.NumberOfElements); break; case UnmanagedType.Interface: case Constants.UnmanagedType_IDispatch: case UnmanagedType.IUnknown: if (marshallingInformation.IidParameterIndex >= 0) { writer.WriteCompressedInteger(marshallingInformation.IidParameterIndex); } break; } } private void SerializeTypeName(ITypeReference typeReference, BlobBuilder writer) { writer.WriteSerializedString(typeReference.GetSerializedTypeName(this.Context)); } /// <summary> /// Computes the string representing the strong name of the given assembly reference. /// </summary> internal static string StrongName(IAssemblyReference assemblyReference) { var identity = assemblyReference.Identity; var pooled = PooledStringBuilder.GetInstance(); StringBuilder sb = pooled.Builder; sb.Append(identity.Name); sb.AppendFormat(CultureInfo.InvariantCulture, ", Version={0}.{1}.{2}.{3}", identity.Version.Major, identity.Version.Minor, identity.Version.Build, identity.Version.Revision); if (!string.IsNullOrEmpty(identity.CultureName)) { sb.AppendFormat(CultureInfo.InvariantCulture, ", Culture={0}", identity.CultureName); } else { sb.Append(", Culture=neutral"); } sb.Append(", PublicKeyToken="); if (identity.PublicKeyToken.Length > 0) { foreach (byte b in identity.PublicKeyToken) { sb.Append(b.ToString("x2")); } } else { sb.Append("null"); } if (identity.IsRetargetable) { sb.Append(", Retargetable=Yes"); } if (identity.ContentType == AssemblyContentType.WindowsRuntime) { sb.Append(", ContentType=WindowsRuntime"); } else { Debug.Assert(identity.ContentType == AssemblyContentType.Default); } return pooled.ToStringAndFree(); } private void SerializePermissionSet(ImmutableArray<ICustomAttribute> permissionSet, BlobBuilder writer) { EmitContext context = this.Context; foreach (ICustomAttribute customAttribute in permissionSet) { bool isAssemblyQualified = true; string typeName = customAttribute.GetType(context).GetSerializedTypeName(context, ref isAssemblyQualified); if (!isAssemblyQualified) { INamespaceTypeReference namespaceType = customAttribute.GetType(context).AsNamespaceTypeReference; if (namespaceType?.GetUnit(context) is IAssemblyReference referencedAssembly) { typeName = typeName + ", " + StrongName(referencedAssembly); } } writer.WriteSerializedString(typeName); var customAttributeArgsBuilder = PooledBlobBuilder.GetInstance(); var namedArgsEncoder = new BlobEncoder(customAttributeArgsBuilder).PermissionSetArguments(customAttribute.NamedArgumentCount); SerializeCustomAttributeNamedArguments(namedArgsEncoder, customAttribute); writer.WriteCompressedInteger(customAttributeArgsBuilder.Count); customAttributeArgsBuilder.WriteContentTo(writer); customAttributeArgsBuilder.Free(); } // TODO: xml for older platforms } private void SerializeReturnValueAndParameters(MethodSignatureEncoder encoder, ISignature signature, ImmutableArray<IParameterTypeInformation> varargParameters) { var declaredParameters = signature.GetParameters(Context); var returnType = signature.GetType(Context); ReturnTypeEncoder returnTypeEncoder; ParametersEncoder parametersEncoder; encoder.Parameters(declaredParameters.Length + varargParameters.Length, out returnTypeEncoder, out parametersEncoder); if (module.IsPlatformType(returnType, PlatformType.SystemTypedReference)) { Debug.Assert(!signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.TypedReference(); } else if (module.IsPlatformType(returnType, PlatformType.SystemVoid)) { Debug.Assert(!signature.ReturnValueIsByRef); Debug.Assert(signature.RefCustomModifiers.IsEmpty); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); returnTypeEncoder.Void(); } else { Debug.Assert(signature.RefCustomModifiers.IsEmpty || signature.ReturnValueIsByRef); SerializeCustomModifiers(returnTypeEncoder.CustomModifiers(), signature.RefCustomModifiers); var typeEncoder = returnTypeEncoder.Type(signature.ReturnValueIsByRef); SerializeCustomModifiers(typeEncoder.CustomModifiers(), signature.ReturnValueCustomModifiers); SerializeTypeReference(typeEncoder, returnType); } foreach (IParameterTypeInformation parameter in declaredParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } if (varargParameters.Length > 0) { parametersEncoder = parametersEncoder.StartVarArgs(); foreach (IParameterTypeInformation parameter in varargParameters) { SerializeParameterInformation(parametersEncoder.AddParameter(), parameter); } } } private void SerializeTypeReference(SignatureTypeEncoder encoder, ITypeReference typeReference) { while (true) { // TYPEDREF is only allowed in RetType, Param, LocalVarSig signatures Debug.Assert(!module.IsPlatformType(typeReference, PlatformType.SystemTypedReference)); if (typeReference is IModifiedTypeReference modifiedTypeReference) { SerializeCustomModifiers(encoder.CustomModifiers(), modifiedTypeReference.CustomModifiers); typeReference = modifiedTypeReference.UnmodifiedType; continue; } var primitiveType = typeReference.TypeCode; switch (primitiveType) { case PrimitiveTypeCode.Pointer: case PrimitiveTypeCode.FunctionPointer: case PrimitiveTypeCode.NotPrimitive: break; default: SerializePrimitiveType(encoder, primitiveType); return; } if (typeReference is IPointerTypeReference pointerTypeReference) { typeReference = pointerTypeReference.GetTargetType(Context); encoder = encoder.Pointer(); continue; } if (typeReference is IFunctionPointerTypeReference functionPointerTypeReference) { var signature = functionPointerTypeReference.Signature; var signatureEncoder = encoder.FunctionPointer(convention: signature.CallingConvention.ToSignatureConvention()); SerializeReturnValueAndParameters(signatureEncoder, signature, varargParameters: ImmutableArray<IParameterTypeInformation>.Empty); return; } IGenericTypeParameterReference genericTypeParameterReference = typeReference.AsGenericTypeParameterReference; if (genericTypeParameterReference != null) { encoder.GenericTypeParameter( GetNumberOfInheritedTypeParameters(genericTypeParameterReference.DefiningType) + genericTypeParameterReference.Index); return; } if (typeReference is IArrayTypeReference arrayTypeReference) { typeReference = arrayTypeReference.GetElementType(Context); if (arrayTypeReference.IsSZArray) { encoder = encoder.SZArray(); continue; } else { SignatureTypeEncoder elementType; ArrayShapeEncoder arrayShape; encoder.Array(out elementType, out arrayShape); SerializeTypeReference(elementType, typeReference); arrayShape.Shape(arrayTypeReference.Rank, arrayTypeReference.Sizes, arrayTypeReference.LowerBounds); return; } } if (module.IsPlatformType(typeReference, PlatformType.SystemObject)) { encoder.Object(); return; } IGenericMethodParameterReference genericMethodParameterReference = typeReference.AsGenericMethodParameterReference; if (genericMethodParameterReference != null) { encoder.GenericMethodTypeParameter(genericMethodParameterReference.Index); return; } if (typeReference.IsTypeSpecification()) { ITypeReference uninstantiatedTypeReference = typeReference.GetUninstantiatedGenericType(Context); // Roslyn's uninstantiated type is the same object as the instantiated type for // types closed over their type parameters, so to speak. var consolidatedTypeArguments = ArrayBuilder<ITypeReference>.GetInstance(); typeReference.GetConsolidatedTypeArguments(consolidatedTypeArguments, this.Context); var genericArgsEncoder = encoder.GenericInstantiation( GetTypeHandle(uninstantiatedTypeReference, treatRefAsPotentialTypeSpec: false), consolidatedTypeArguments.Count, typeReference.IsValueType); foreach (ITypeReference typeArgument in consolidatedTypeArguments) { SerializeTypeReference(genericArgsEncoder.AddArgument(), typeArgument); } consolidatedTypeArguments.Free(); return; } encoder.Type(GetTypeHandle(typeReference), typeReference.IsValueType); return; } } private static void SerializePrimitiveType(SignatureTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.IntPtr: encoder.IntPtr(); break; case PrimitiveTypeCode.UIntPtr: encoder.UIntPtr(); break; case PrimitiveTypeCode.String: encoder.String(); break; case PrimitiveTypeCode.Void: // "void" is handled specifically for "void*" with custom modifiers. // If SignatureTypeEncoder supports such cases directly, this can // be removed. See https://github.com/dotnet/corefx/issues/14571. encoder.Builder.WriteByte((byte)System.Reflection.Metadata.PrimitiveTypeCode.Void); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomAttributeArrayType(CustomAttributeArrayTypeEncoder encoder, IArrayTypeReference arrayTypeReference) { // A single-dimensional, zero-based array is specified as a single byte 0x1D followed by the FieldOrPropType of the element type. // only non-jagged SZ arrays are allowed in attributes // (need to encode the type of the SZ array if the parameter type is Object): Debug.Assert(arrayTypeReference.IsSZArray); var elementType = arrayTypeReference.GetElementType(Context); Debug.Assert(!(elementType is IModifiedTypeReference)); if (module.IsPlatformType(elementType, PlatformType.SystemObject)) { encoder.ObjectArray(); } else { SerializeCustomAttributeElementType(encoder.ElementType(), elementType); } } private void SerializeCustomAttributeElementType(CustomAttributeElementTypeEncoder encoder, ITypeReference typeReference) { // Spec: // The FieldOrPropType shall be exactly one of: // ELEMENT_TYPE_BOOLEAN, ELEMENT_TYPE_CHAR, ELEMENT_TYPE_I1, ELEMENT_TYPE_U1, ELEMENT_TYPE_I2, ELEMENT_TYPE_U2, ELEMENT_TYPE_I4, // ELEMENT_TYPE_U4, ELEMENT_TYPE_I8, ELEMENT_TYPE_U8, ELEMENT_TYPE_R4, ELEMENT_TYPE_R8, ELEMENT_TYPE_STRING. // An enum is specified as a single byte 0x55 followed by a SerString. var primitiveType = typeReference.TypeCode; if (primitiveType != PrimitiveTypeCode.NotPrimitive) { SerializePrimitiveType(encoder, primitiveType); } else if (module.IsPlatformType(typeReference, PlatformType.SystemType)) { encoder.SystemType(); } else { Debug.Assert(typeReference.IsEnum); encoder.Enum(typeReference.GetSerializedTypeName(this.Context)); } } private static void SerializePrimitiveType(CustomAttributeElementTypeEncoder encoder, PrimitiveTypeCode primitiveType) { switch (primitiveType) { case PrimitiveTypeCode.Boolean: encoder.Boolean(); break; case PrimitiveTypeCode.UInt8: encoder.Byte(); break; case PrimitiveTypeCode.Int8: encoder.SByte(); break; case PrimitiveTypeCode.Char: encoder.Char(); break; case PrimitiveTypeCode.Int16: encoder.Int16(); break; case PrimitiveTypeCode.UInt16: encoder.UInt16(); break; case PrimitiveTypeCode.Int32: encoder.Int32(); break; case PrimitiveTypeCode.UInt32: encoder.UInt32(); break; case PrimitiveTypeCode.Int64: encoder.Int64(); break; case PrimitiveTypeCode.UInt64: encoder.UInt64(); break; case PrimitiveTypeCode.Float32: encoder.Single(); break; case PrimitiveTypeCode.Float64: encoder.Double(); break; case PrimitiveTypeCode.String: encoder.String(); break; default: throw ExceptionUtilities.UnexpectedValue(primitiveType); } } private void SerializeCustomModifiers(CustomModifiersEncoder encoder, ImmutableArray<ICustomModifier> modifiers) { foreach (var modifier in modifiers) { encoder = encoder.AddModifier(GetTypeHandle(modifier.GetModifier(Context)), modifier.IsOptional); } } private int GetNumberOfInheritedTypeParameters(ITypeReference type) { INestedTypeReference nestedType = type.AsNestedTypeReference; if (nestedType == null) { return 0; } ISpecializedNestedTypeReference specializedNestedType = nestedType.AsSpecializedNestedTypeReference; if (specializedNestedType != null) { nestedType = specializedNestedType.GetUnspecializedVersion(Context); } int result = 0; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; while (nestedType != null) { result += nestedType.GenericParameterCount; type = nestedType.GetContainingType(Context); nestedType = type.AsNestedTypeReference; } result += type.AsNamespaceTypeReference.GenericParameterCount; return result; } internal static EditAndContinueMethodDebugInformation GetEncMethodDebugInfo(IMethodBody methodBody) { ImmutableArray<LocalSlotDebugInfo> encLocalSlots; // Kickoff method of a state machine (async/iterator method) doesn't have any interesting locals, // so we use its EnC method debug info to store information about locals hoisted to the state machine. var encSlotInfo = methodBody.StateMachineHoistedLocalSlots; if (encSlotInfo.IsDefault) { encLocalSlots = GetLocalSlotDebugInfos(methodBody.LocalVariables); } else { encLocalSlots = GetLocalSlotDebugInfos(encSlotInfo); } return new EditAndContinueMethodDebugInformation(methodBody.MethodId.Ordinal, encLocalSlots, methodBody.ClosureDebugInfo, methodBody.LambdaDebugInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<ILocalDefinition> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } internal static ImmutableArray<LocalSlotDebugInfo> GetLocalSlotDebugInfos(ImmutableArray<EncHoistedLocalInfo> locals) { if (!locals.Any(variable => !variable.SlotInfo.Id.IsNone)) { return ImmutableArray<LocalSlotDebugInfo>.Empty; } return locals.SelectAsArray(variable => variable.SlotInfo); } protected abstract class HeapOrReferenceIndexBase<T> { private readonly MetadataWriter _writer; private readonly List<T> _rows; private readonly int _firstRowId; protected HeapOrReferenceIndexBase(MetadataWriter writer, int lastRowId) { _writer = writer; _rows = new List<T>(); _firstRowId = lastRowId + 1; } public abstract bool TryGetValue(T item, out int index); public int GetOrAdd(T item) { int index; if (!this.TryGetValue(item, out index)) { index = Add(item); } return index; } public IReadOnlyList<T> Rows { get { return _rows; } } public int Add(T item) { Debug.Assert(!_writer._tableIndicesAreComplete); #if DEBUG int i; Debug.Assert(!this.TryGetValue(item, out i)); #endif int index = _firstRowId + _rows.Count; this.AddItem(item, index); _rows.Add(item); return index; } protected abstract void AddItem(T item, int index); } protected sealed class HeapOrReferenceIndex<T> : HeapOrReferenceIndexBase<T> { private readonly Dictionary<T, int> _index; public HeapOrReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<T, int>(), lastRowId) { } private HeapOrReferenceIndex(MetadataWriter writer, Dictionary<T, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(T item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(T item, int index) { _index.Add(item, index); } } protected sealed class TypeReferenceIndex : HeapOrReferenceIndexBase<ITypeReference> { private readonly Dictionary<ITypeReference, int> _index; public TypeReferenceIndex(MetadataWriter writer, int lastRowId = 0) : this(writer, new Dictionary<ITypeReference, int>(ReferenceEqualityComparer.Instance), lastRowId) { } private TypeReferenceIndex(MetadataWriter writer, Dictionary<ITypeReference, int> index, int lastRowId) : base(writer, lastRowId) { Debug.Assert(index.Count == 0); _index = index; } public override bool TryGetValue(ITypeReference item, out int index) { return _index.TryGetValue(item, out index); } protected override void AddItem(ITypeReference item, int index) { _index.Add(item, index); } } protected sealed class InstanceAndStructuralReferenceIndex<T> : HeapOrReferenceIndexBase<T> where T : class, IReference { private readonly Dictionary<T, int> _instanceIndex; private readonly Dictionary<T, int> _structuralIndex; public InstanceAndStructuralReferenceIndex(MetadataWriter writer, IEqualityComparer<T> structuralComparer, int lastRowId = 0) : base(writer, lastRowId) { _instanceIndex = new Dictionary<T, int>(ReferenceEqualityComparer.Instance); _structuralIndex = new Dictionary<T, int>(structuralComparer); } public override bool TryGetValue(T item, out int index) { if (_instanceIndex.TryGetValue(item, out index)) { return true; } if (_structuralIndex.TryGetValue(item, out index)) { _instanceIndex.Add(item, index); return true; } return false; } protected override void AddItem(T item, int index) { _instanceIndex.Add(item, index); _structuralIndex.Add(item, index); } } private class ByteSequenceBoolTupleComparer : IEqualityComparer<(ImmutableArray<byte>, bool)> { internal static readonly ByteSequenceBoolTupleComparer Instance = new ByteSequenceBoolTupleComparer(); private ByteSequenceBoolTupleComparer() { } bool IEqualityComparer<(ImmutableArray<byte>, bool)>.Equals((ImmutableArray<byte>, bool) x, (ImmutableArray<byte>, bool) y) { return x.Item2 == y.Item2 && ByteSequenceComparer.Equals(x.Item1, y.Item1); } int IEqualityComparer<(ImmutableArray<byte>, bool)>.GetHashCode((ImmutableArray<byte>, bool) x) { return Hash.Combine(ByteSequenceComparer.GetHashCode(x.Item1), x.Item2.GetHashCode()); } } } }
1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Partial Friend MustInherit Class PEModuleBuilder Inherits PEModuleBuilder(Of VisualBasicCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState) ' Not many methods should end up here. Private ReadOnly _disableJITOptimization As ConcurrentDictionary(Of MethodSymbol, Boolean) = New ConcurrentDictionary(Of MethodSymbol, Boolean)(ReferenceEqualityComparer.Instance) ' Gives the name of this module (may not reflect the name of the underlying symbol). ' See Assembly.MetadataName. Private ReadOnly _metadataName As String Private _lazyExportedTypes As ImmutableArray(Of Cci.ExportedType) Private ReadOnly _lazyNumberOfTypesFromOtherModules As Integer Private _lazyTranslatedImports As ImmutableArray(Of Cci.UsedNamespaceOrType) Private _lazyDefaultNamespace As String Friend Sub New(sourceModule As SourceModuleSymbol, emitOptions As EmitOptions, outputKind As OutputKind, serializationProperties As Cci.ModulePropertiesForSerialization, manifestResources As IEnumerable(Of ResourceDescription)) MyBase.New(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, New ModuleCompilationState()) Dim specifiedName = sourceModule.MetadataName _metadataName = If(specifiedName <> CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName, specifiedName, If(emitOptions.OutputNameOverride, specifiedName)) m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, Me) If sourceModule.AnyReferencedAssembliesAreLinked Then _embeddedTypesManagerOpt = New NoPia.EmbeddedTypesManager(Me) End If End Sub ''' <summary> ''' True if conditional calls may be omitted when the required preprocessor symbols are not defined. ''' </summary> ''' <remarks> ''' Only false in debugger scenarios (where calls should never be omitted). ''' </remarks> Friend MustOverride ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Public Overrides ReadOnly Property Name As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property ModuleName As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property CorLibrary As AssemblySymbol Get Return SourceModule.ContainingSourceAssembly.CorLibrary End Get End Property Public NotOverridable Overrides ReadOnly Property GenerateVisualBasicStylePdb As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String) Get ' NOTE: Dev12 does not seem to emit anything but the name (i.e. no version, token, etc). ' See Builder::WriteNoPiaPdbList Return SourceModule.ReferencedAssemblySymbols.Where(Function(a) a.IsLinked).Select(Function(a) a.Name) End Get End Property Public NotOverridable Overrides Function GetImports() As ImmutableArray(Of Cci.UsedNamespaceOrType) ' Imports should have been translated in code gen phase. Debug.Assert(Not _lazyTranslatedImports.IsDefault) Return _lazyTranslatedImports End Function Public Sub TranslateImports(diagnostics As DiagnosticBag) If _lazyTranslatedImports.IsDefault Then ImmutableInterlocked.InterlockedInitialize( _lazyTranslatedImports, NamespaceScopeBuilder.BuildNamespaceScope(Me, SourceModule.XmlNamespaces, SourceModule.AliasImports, SourceModule.MemberImports, diagnostics)) End If End Sub Public NotOverridable Overrides ReadOnly Property DefaultNamespace As String Get If _lazyDefaultNamespace IsNot Nothing Then Return _lazyDefaultNamespace End If Dim rootNamespace = SourceModule.RootNamespace If rootNamespace.IsGlobalNamespace Then Return String.Empty End If _lazyDefaultNamespace = rootNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) Return _lazyDefaultNamespace End Get End Property Protected NotOverridable Overrides Iterator Function GetAssemblyReferencesFromAddedModules(diagnostics As DiagnosticBag) As IEnumerable(Of Cci.IAssemblyReference) Dim modules As ImmutableArray(Of ModuleSymbol) = SourceModule.ContainingAssembly.Modules For i As Integer = 1 To modules.Length - 1 For Each aRef As AssemblySymbol In modules(i).GetReferencedAssemblySymbols() Yield Translate(aRef, diagnostics) Next Next End Function Private Sub ValidateReferencedAssembly(assembly As AssemblySymbol, asmRef As AssemblyReference, diagnostics As DiagnosticBag) Dim asmIdentity As AssemblyIdentity = SourceModule.ContainingAssembly.Identity Dim refIdentity As AssemblyIdentity = asmRef.Identity If asmIdentity.IsStrongName AndAlso Not refIdentity.IsStrongName AndAlso asmRef.Identity.ContentType <> Reflection.AssemblyContentType.WindowsRuntime Then ' Dev12 reported error, we have changed it to a warning to allow referencing libraries ' built for platforms that don't support strong names. diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton) End If If OutputKind <> OutputKind.NetModule AndAlso Not String.IsNullOrEmpty(refIdentity.CultureName) AndAlso Not String.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase) Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton) End If Dim refMachine = assembly.Machine ' If other assembly is agnostic, this is always safe ' Also, if no mscorlib was specified for back compat we add a reference to mscorlib ' that resolves to the current framework directory. If the compiler Is 64-bit ' this Is a 64-bit mscorlib, which will produce a warning if /platform:x86 Is ' specified.A reference to the default mscorlib should always succeed without ' warning so we ignore it here. If assembly IsNot assembly.CorLibrary AndAlso Not (refMachine = Machine.I386 AndAlso Not assembly.Bit32Required) Then Dim machine = SourceModule.Machine If Not (machine = Machine.I386 AndAlso Not SourceModule.Bit32Required) AndAlso machine <> refMachine Then ' Different machine types, and neither is agnostic diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton) End If End If If _embeddedTypesManagerOpt IsNot Nothing AndAlso _embeddedTypesManagerOpt.IsFrozen Then _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics) End If End Sub Friend NotOverridable Overrides Function SynthesizeAttribute(attributeConstructor As WellKnownMember) As Cci.ICustomAttribute Return Me.Compilation.TrySynthesizeAttribute(attributeConstructor) End Function Public NotOverridable Overrides Function GetSourceAssemblyAttributes(isRefAssembly As Boolean) As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.ContainingSourceAssembly.GetAssemblyCustomAttributesToEmit(Me.CompilationState, isRefAssembly, emittingAssemblyAttributesInNetModule:=OutputKind.IsNetModule()) End Function Public NotOverridable Overrides Function GetSourceAssemblySecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute) Return SourceModule.ContainingSourceAssembly.GetSecurityAttributes() End Function Public NotOverridable Overrides Function GetSourceModuleAttributes() As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.GetCustomAttributesToEmit(Me.CompilationState) End Function Public NotOverridable Overrides Function GetSymbolToLocationMap() As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation) Dim result As New MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)() Dim namespacesAndTypesToProcess As New Stack(Of NamespaceOrTypeSymbol)() namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace) Dim location As Location = Nothing While namespacesAndTypesToProcess.Count > 0 Dim symbol As NamespaceOrTypeSymbol = namespacesAndTypesToProcess.Pop() Select Case symbol.Kind Case SymbolKind.Namespace location = GetSmallestSourceLocationOrNull(symbol) ' filtering out synthesized symbols not having real source ' locations such as anonymous types, my types, etc... If location IsNot Nothing Then For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case SymbolKind.NamedType location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then ' add this named type location AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case SymbolKind.Method Dim method = DirectCast(member, MethodSymbol) If method.IsDefaultValueTypeConstructor() OrElse method.IsPartialWithoutImplementation Then Exit Select End If AddSymbolLocation(result, member) Case SymbolKind.Property, SymbolKind.Field AddSymbolLocation(result, member) Case SymbolKind.Event AddSymbolLocation(result, member) Dim AssociatedField = (DirectCast(member, EventSymbol)).AssociatedField If AssociatedField IsNot Nothing Then ' event backing fields do not show up in GetMembers AddSymbolLocation(result, AssociatedField) End If Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select End While Return result End Function Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), symbol As Symbol) Dim location As Location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) End If End Sub Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), location As Location, definition As Cci.IDefinition) Dim span As FileLinePositionSpan = location.GetLineSpan() Dim doc As Cci.DebugSourceDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=location.SourceTree.FilePath) If (doc IsNot Nothing) Then result.Add(doc, New Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)) End If End Sub Private Function GetSmallestSourceLocationOrNull(symbol As Symbol) As Location Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation Debug.Assert(Me.Compilation Is compilation, "How did we get symbol from different compilation?") Dim result As Location = Nothing For Each loc In symbol.Locations If loc.IsInSource AndAlso (result Is Nothing OrElse compilation.CompareSourceLocations(result, loc) > 0) Then result = loc End If Next Return result End Function ''' <summary> ''' Ignore accessibility when resolving well-known type ''' members, in particular for generic type arguments ''' (e.g.: binding to internal types in the EE). ''' </summary> Friend Overridable ReadOnly Property IgnoreAccessibility As Boolean Get Return False End Get End Property Friend Overridable Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator Return Nothing End Function Friend Overridable Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey) Return ImmutableArray(Of AnonymousTypeKey).Empty End Function Friend Overridable Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer Return 0 End Function Friend Overridable Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Debug.Assert(Compilation Is template.DeclaringCompilation) name = Nothing index = -1 Return False End Function Public NotOverridable Overrides Function GetAnonymousTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) If context.MetadataOnly Then Return SpecializedCollections.EmptyEnumerable(Of Cci.INamespaceTypeDefinition) End If #If DEBUG Then Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates.Select(Function(t) t.GetCciAdapter()) #Else Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates #End If End Function Public Overrides Iterator Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) Dim embeddedSymbolManager As EmbeddedSymbolManager = SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager Dim stack As New Stack(Of NamespaceOrTypeSymbol)() stack.Push(SourceModule.GlobalNamespace) Do Dim sym As NamespaceOrTypeSymbol = stack.Pop() If sym.Kind = SymbolKind.NamedType Then Debug.Assert(sym Is sym.OriginalDefinition) Debug.Assert(sym.ContainingType Is Nothing) ' Skip unreferenced embedded types. If Not sym.IsEmbedded OrElse embeddedSymbolManager.IsSymbolReferenced(sym) Then Yield DirectCast(sym, NamedTypeSymbol).GetCciAdapter() End If Else Debug.Assert(sym.Kind = SymbolKind.Namespace) Dim members As ImmutableArray(Of Symbol) = sym.GetMembers() For i As Integer = members.Length - 1 To 0 Step -1 Dim namespaceOrType As NamespaceOrTypeSymbol = TryCast(members(i), NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then stack.Push(namespaceOrType) End If Next End If Loop While stack.Count > 0 End Function Public NotOverridable Overrides Function GetExportedTypes(diagnostics As DiagnosticBag) As ImmutableArray(Of Cci.ExportedType) Debug.Assert(HaveDeterminedTopLevelTypes) If _lazyExportedTypes.IsDefault Then _lazyExportedTypes = CalculateExportedTypes() If _lazyExportedTypes.Length > 0 Then ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics) End If End If Return _lazyExportedTypes End Function ''' <summary> ''' Builds an array of public type symbols defined in netmodules included in the compilation ''' And type forwarders defined in this compilation Or any included netmodule (in this order). ''' </summary> Private Function CalculateExportedTypes() As ImmutableArray(Of Cci.ExportedType) Dim builder = ArrayBuilder(Of Cci.ExportedType).GetInstance() Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly If Not OutputKind.IsNetModule() Then Dim modules = sourceAssembly.Modules For i As Integer = 1 To modules.Length - 1 'NOTE: skipping modules(0) GetExportedTypes(modules(i).GlobalNamespace, -1, builder) Next End If Debug.Assert(OutputKind.IsNetModule() = sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) GetForwardedTypes(sourceAssembly, builder) Return builder.ToImmutableAndFree() End Function ''' <summary> ''' Returns a set of top-level forwarded types ''' </summary> Friend Shared Function GetForwardedTypes(sourceAssembly As SourceAssemblySymbol, builderOpt As ArrayBuilder(Of Cci.ExportedType)) As HashSet(Of NamedTypeSymbol) Dim seenTopLevelForwardedTypes = New HashSet(Of NamedTypeSymbol)() GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builderOpt) If Not sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule() Then GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builderOpt) End If Return seenTopLevelForwardedTypes End Function Private Sub ReportExportedTypeNameCollisions(exportedTypes As ImmutableArray(Of Cci.ExportedType), diagnostics As DiagnosticBag) Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly Dim exportedNamesMap = New Dictionary(Of String, NamedTypeSymbol)() For Each exportedType In _lazyExportedTypes Dim typeReference As Cci.ITypeReference = exportedType.Type Dim type = DirectCast(typeReference.GetInternalSymbol(), NamedTypeSymbol) Debug.Assert(type.IsDefinition) If type.ContainingType IsNot Nothing Then Continue For End If ' exported types are not emitted in EnC deltas (hence generation 0): Dim fullEmittedName As String = MetadataHelpers.BuildQualifiedName( DirectCast(typeReference, Cci.INamespaceTypeReference).NamespaceName, Cci.MetadataWriter.GetMangledName(DirectCast(typeReference, Cci.INamedTypeReference), generation:=0)) ' First check against types declared in the primary module If ContainsTopLevelType(fullEmittedName) Then If type.ContainingAssembly Is sourceAssembly Then diagnostics.Add(ERRID.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule) Else diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type)) End If Continue For End If Dim contender As NamedTypeSymbol = Nothing ' Now check against other exported types If exportedNamesMap.TryGetValue(fullEmittedName, contender) Then If type.ContainingAssembly Is sourceAssembly Then ' all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly Is sourceAssembly) diagnostics.Add(ERRID.ERR_ExportedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), CustomSymbolDisplayFormatter.DefaultErrorFormat(type.ContainingModule), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) ElseIf contender.ContainingAssembly Is sourceAssembly Then ' Forwarded type conflicts with exported type diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) Else ' Forwarded type conflicts with another forwarded type diagnostics.Add(ERRID.ERR_ForwardedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), contender.ContainingAssembly) End If Continue For End If exportedNamesMap.Add(fullEmittedName, type) Next End Sub Private Overloads Sub GetExportedTypes(symbol As NamespaceOrTypeSymbol, parentIndex As Integer, builder As ArrayBuilder(Of Cci.ExportedType)) Dim index As Integer If symbol.Kind = SymbolKind.NamedType Then If symbol.DeclaredAccessibility <> Accessibility.Public Then Return End If Debug.Assert(symbol.IsDefinition) index = builder.Count builder.Add(New Cci.ExportedType(DirectCast(symbol, NamedTypeSymbol).GetCciAdapter(), parentIndex, isForwarder:=False)) Else index = -1 End If For Each member In symbol.GetMembers() Dim namespaceOrType = TryCast(member, NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then GetExportedTypes(namespaceOrType, index, builder) End If Next End Sub Private Shared Sub GetForwardedTypes( seenTopLevelTypes As HashSet(Of NamedTypeSymbol), wellKnownAttributeData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol), builderOpt As ArrayBuilder(Of Cci.ExportedType)) If wellKnownAttributeData?.ForwardedTypes?.Count > 0 Then ' (type, index of the parent exported type in builder, or -1 if the type is a top-level type) Dim stack = ArrayBuilder(Of (type As NamedTypeSymbol, parentIndex As Integer)).GetInstance() ' Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. Dim orderedForwardedTypes As IEnumerable(Of NamedTypeSymbol) = wellKnownAttributeData.ForwardedTypes If builderOpt IsNot Nothing Then orderedForwardedTypes = orderedForwardedTypes.OrderBy(Function(t) t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)) End If For Each forwardedType As NamedTypeSymbol In orderedForwardedTypes Dim originalDefinition As NamedTypeSymbol = forwardedType.OriginalDefinition Debug.Assert(originalDefinition.ContainingType Is Nothing, "How did a nested type get forwarded?") ' De-dup the original definitions before emitting. If Not seenTopLevelTypes.Add(originalDefinition) Then Continue For End If If builderOpt IsNot Nothing Then ' Return all nested types. ' Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count = 0) stack.Push((originalDefinition, -1)) While stack.Count > 0 Dim entry = stack.Pop() ' In general, we don't want private types to appear in the ExportedTypes table. If entry.type.DeclaredAccessibility = Accessibility.Private Then ' NOTE: this will also exclude nested types of curr. Continue While End If ' NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. Dim index = builderOpt.Count builderOpt.Add(New Cci.ExportedType(entry.type.GetCciAdapter(), entry.parentIndex, isForwarder:=True)) ' Iterate backwards so they get popped in forward order. Dim nested As ImmutableArray(Of NamedTypeSymbol) = entry.type.GetTypeMembers() ' Ordered. For i As Integer = nested.Length - 1 To 0 Step -1 stack.Push((nested(i), index)) Next End While End If Next stack.Free() End If End Sub Friend Iterator Function GetReferencedAssembliesUsedSoFar() As IEnumerable(Of AssemblySymbol) For Each assembly In SourceModule.GetReferencedAssemblySymbols() If Not assembly.IsLinked AndAlso Not assembly.IsMissing AndAlso m_AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(assembly) Then Yield assembly End If Next End Function Friend NotOverridable Overrides Function GetSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference Return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), needDeclaration:=True, syntaxNodeOpt:=syntaxNodeOpt, diagnostics:=diagnostics) End Function Private Function GetUntranslatedSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As NamedTypeSymbol Dim typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType) Dim info = Binder.GetUseSiteInfoForSpecialType(typeSymbol) If info.DiagnosticInfo IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, If(syntaxNodeOpt IsNot Nothing, syntaxNodeOpt.GetLocation(), NoLocation.Singleton), info.DiagnosticInfo) End If Return typeSymbol End Function Public NotOverridable Overrides Function GetInitArrayHelper() As Cci.IMethodReference Return DirectCast(Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle), MethodSymbol)?.GetCciAdapter() End Function Public NotOverridable Overrides Function IsPlatformType(typeRef As Cci.ITypeReference, platformType As Cci.PlatformType) As Boolean Dim namedType = TryCast(typeRef.GetInternalSymbol(), NamedTypeSymbol) If namedType IsNot Nothing Then If platformType = Cci.PlatformType.SystemType Then Return namedType Is Compilation.GetWellKnownType(WellKnownType.System_Type) End If Return namedType.SpecialType = CType(platformType, SpecialType) End If Return False End Function Protected NotOverridable Overrides Function GetCorLibraryReferenceToEmit(context As EmitContext) As Cci.IAssemblyReference Dim corLib = CorLibrary If Not corLib.IsMissing AndAlso Not corLib.IsLinked AndAlso corLib IsNot SourceModule.ContainingAssembly Then Return Translate(corLib, context.Diagnostics) End If Return Nothing End Function Friend NotOverridable Overrides Function GetSynthesizedNestedTypes(container As NamedTypeSymbol) As IEnumerable(Of Cci.INestedTypeDefinition) Return container.GetSynthesizedNestedTypes() End Function Public Sub SetDisableJITOptimization(methodSymbol As MethodSymbol) Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) _disableJITOptimization.TryAdd(methodSymbol, True) End Sub Public Function JITOptimizationIsDisabled(methodSymbol As MethodSymbol) As Boolean Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) Return _disableJITOptimization.ContainsKey(methodSymbol) End Function Protected NotOverridable Overrides Function CreatePrivateImplementationDetailsStaticConstructor(details As PrivateImplementationDetails, syntaxOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.IMethodDefinition Return New SynthesizedPrivateImplementationDetailsSharedConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter() End Function Public Overrides Function GetAdditionalTopLevelTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetAdditionalTopLevelTypes().Select(Function(t) t.GetCciAdapter()) #Else Return GetAdditionalTopLevelTypes() #End If End Function Public Overrides Function GetEmbeddedTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetEmbeddedTypes(context.Diagnostics).Select(Function(t) t.GetCciAdapter()) #Else Return GetEmbeddedTypes(context.Diagnostics) #End If End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Partial Friend MustInherit Class PEModuleBuilder Inherits PEModuleBuilder(Of VisualBasicCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState) ' Not many methods should end up here. Private ReadOnly _disableJITOptimization As ConcurrentDictionary(Of MethodSymbol, Boolean) = New ConcurrentDictionary(Of MethodSymbol, Boolean)(ReferenceEqualityComparer.Instance) ' Gives the name of this module (may not reflect the name of the underlying symbol). ' See Assembly.MetadataName. Private ReadOnly _metadataName As String Private _lazyExportedTypes As ImmutableArray(Of Cci.ExportedType) Private ReadOnly _lazyNumberOfTypesFromOtherModules As Integer Private _lazyTranslatedImports As ImmutableArray(Of Cci.UsedNamespaceOrType) Private _lazyDefaultNamespace As String Friend Sub New(sourceModule As SourceModuleSymbol, emitOptions As EmitOptions, outputKind As OutputKind, serializationProperties As Cci.ModulePropertiesForSerialization, manifestResources As IEnumerable(Of ResourceDescription)) MyBase.New(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, New ModuleCompilationState()) Dim specifiedName = sourceModule.MetadataName _metadataName = If(specifiedName <> CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName, specifiedName, If(emitOptions.OutputNameOverride, specifiedName)) m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, Me) If sourceModule.AnyReferencedAssembliesAreLinked Then _embeddedTypesManagerOpt = New NoPia.EmbeddedTypesManager(Me) End If End Sub ''' <summary> ''' True if conditional calls may be omitted when the required preprocessor symbols are not defined. ''' </summary> ''' <remarks> ''' Only false in debugger scenarios (where calls should never be omitted). ''' </remarks> Friend MustOverride ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Public Overrides ReadOnly Property Name As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property ModuleName As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property CorLibrary As AssemblySymbol Get Return SourceModule.ContainingSourceAssembly.CorLibrary End Get End Property Public NotOverridable Overrides ReadOnly Property GenerateVisualBasicStylePdb As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String) Get ' NOTE: Dev12 does not seem to emit anything but the name (i.e. no version, token, etc). ' See Builder::WriteNoPiaPdbList Return SourceModule.ReferencedAssemblySymbols.Where(Function(a) a.IsLinked).Select(Function(a) a.Name) End Get End Property Public NotOverridable Overrides Function GetImports() As ImmutableArray(Of Cci.UsedNamespaceOrType) ' Imports should have been translated in code gen phase. Debug.Assert(Not _lazyTranslatedImports.IsDefault) Return _lazyTranslatedImports End Function Public Sub TranslateImports(diagnostics As DiagnosticBag) If _lazyTranslatedImports.IsDefault Then ImmutableInterlocked.InterlockedInitialize( _lazyTranslatedImports, NamespaceScopeBuilder.BuildNamespaceScope(Me, SourceModule.XmlNamespaces, SourceModule.AliasImports, SourceModule.MemberImports, diagnostics)) End If End Sub Public NotOverridable Overrides ReadOnly Property DefaultNamespace As String Get If _lazyDefaultNamespace IsNot Nothing Then Return _lazyDefaultNamespace End If Dim rootNamespace = SourceModule.RootNamespace If rootNamespace.IsGlobalNamespace Then Return String.Empty End If _lazyDefaultNamespace = rootNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) Return _lazyDefaultNamespace End Get End Property Protected NotOverridable Overrides Iterator Function GetAssemblyReferencesFromAddedModules(diagnostics As DiagnosticBag) As IEnumerable(Of Cci.IAssemblyReference) Dim modules As ImmutableArray(Of ModuleSymbol) = SourceModule.ContainingAssembly.Modules For i As Integer = 1 To modules.Length - 1 For Each aRef As AssemblySymbol In modules(i).GetReferencedAssemblySymbols() Yield Translate(aRef, diagnostics) Next Next End Function Private Sub ValidateReferencedAssembly(assembly As AssemblySymbol, asmRef As AssemblyReference, diagnostics As DiagnosticBag) Dim asmIdentity As AssemblyIdentity = SourceModule.ContainingAssembly.Identity Dim refIdentity As AssemblyIdentity = asmRef.Identity If asmIdentity.IsStrongName AndAlso Not refIdentity.IsStrongName AndAlso asmRef.Identity.ContentType <> Reflection.AssemblyContentType.WindowsRuntime Then ' Dev12 reported error, we have changed it to a warning to allow referencing libraries ' built for platforms that don't support strong names. diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton) End If If OutputKind <> OutputKind.NetModule AndAlso Not String.IsNullOrEmpty(refIdentity.CultureName) AndAlso Not String.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase) Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton) End If Dim refMachine = assembly.Machine ' If other assembly is agnostic, this is always safe ' Also, if no mscorlib was specified for back compat we add a reference to mscorlib ' that resolves to the current framework directory. If the compiler Is 64-bit ' this Is a 64-bit mscorlib, which will produce a warning if /platform:x86 Is ' specified.A reference to the default mscorlib should always succeed without ' warning so we ignore it here. If assembly IsNot assembly.CorLibrary AndAlso Not (refMachine = Machine.I386 AndAlso Not assembly.Bit32Required) Then Dim machine = SourceModule.Machine If Not (machine = Machine.I386 AndAlso Not SourceModule.Bit32Required) AndAlso machine <> refMachine Then ' Different machine types, and neither is agnostic diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton) End If End If If _embeddedTypesManagerOpt IsNot Nothing AndAlso _embeddedTypesManagerOpt.IsFrozen Then _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics) End If End Sub Friend NotOverridable Overrides Function SynthesizeAttribute(attributeConstructor As WellKnownMember) As Cci.ICustomAttribute Return Me.Compilation.TrySynthesizeAttribute(attributeConstructor) End Function Public NotOverridable Overrides Function GetSourceAssemblyAttributes(isRefAssembly As Boolean) As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.ContainingSourceAssembly.GetAssemblyCustomAttributesToEmit(Me.CompilationState, isRefAssembly, emittingAssemblyAttributesInNetModule:=OutputKind.IsNetModule()) End Function Public NotOverridable Overrides Function GetSourceAssemblySecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute) Return SourceModule.ContainingSourceAssembly.GetSecurityAttributes() End Function Public NotOverridable Overrides Function GetSourceModuleAttributes() As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.GetCustomAttributesToEmit(Me.CompilationState) End Function Public NotOverridable Overrides Function GetSymbolToLocationMap() As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation) Dim result As New MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)() Dim namespacesAndTypesToProcess As New Stack(Of NamespaceOrTypeSymbol)() namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace) Dim location As Location = Nothing While namespacesAndTypesToProcess.Count > 0 Dim symbol As NamespaceOrTypeSymbol = namespacesAndTypesToProcess.Pop() Select Case symbol.Kind Case SymbolKind.Namespace location = GetSmallestSourceLocationOrNull(symbol) ' filtering out synthesized symbols not having real source ' locations such as anonymous types, my types, etc... If location IsNot Nothing Then For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case SymbolKind.NamedType location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then ' add this named type location AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case SymbolKind.Method Dim method = DirectCast(member, MethodSymbol) If method.IsDefaultValueTypeConstructor() OrElse method.IsPartialWithoutImplementation Then Exit Select End If AddSymbolLocation(result, member) Case SymbolKind.Property, SymbolKind.Field AddSymbolLocation(result, member) Case SymbolKind.Event AddSymbolLocation(result, member) Dim AssociatedField = (DirectCast(member, EventSymbol)).AssociatedField If AssociatedField IsNot Nothing Then ' event backing fields do not show up in GetMembers AddSymbolLocation(result, AssociatedField) End If Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select End While Return result End Function Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), symbol As Symbol) Dim location As Location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) End If End Sub Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), location As Location, definition As Cci.IDefinition) Dim span As FileLinePositionSpan = location.GetLineSpan() Dim doc As Cci.DebugSourceDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=location.SourceTree.FilePath) If (doc IsNot Nothing) Then result.Add(doc, New Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)) End If End Sub Private Function GetSmallestSourceLocationOrNull(symbol As Symbol) As Location Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation Debug.Assert(Me.Compilation Is compilation, "How did we get symbol from different compilation?") Dim result As Location = Nothing For Each loc In symbol.Locations If loc.IsInSource AndAlso (result Is Nothing OrElse compilation.CompareSourceLocations(result, loc) > 0) Then result = loc End If Next Return result End Function ''' <summary> ''' Ignore accessibility when resolving well-known type ''' members, in particular for generic type arguments ''' (e.g.: binding to internal types in the EE). ''' </summary> Friend Overridable ReadOnly Property IgnoreAccessibility As Boolean Get Return False End Get End Property Friend Overridable Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator Return Nothing End Function Friend Overridable Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey) Return ImmutableArray(Of AnonymousTypeKey).Empty End Function Friend Overridable Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer Return 0 End Function Friend Overridable Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Debug.Assert(Compilation Is template.DeclaringCompilation) name = Nothing index = -1 Return False End Function Public NotOverridable Overrides Function GetAnonymousTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) If context.MetadataOnly Then Return SpecializedCollections.EmptyEnumerable(Of Cci.INamespaceTypeDefinition) End If #If DEBUG Then Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates.Select(Function(t) t.GetCciAdapter()) #Else Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates #End If End Function Public Overrides Iterator Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) Dim embeddedSymbolManager As EmbeddedSymbolManager = SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager Dim stack As New Stack(Of NamespaceOrTypeSymbol)() stack.Push(SourceModule.GlobalNamespace) Do Dim sym As NamespaceOrTypeSymbol = stack.Pop() If sym.Kind = SymbolKind.NamedType Then Debug.Assert(sym Is sym.OriginalDefinition) Debug.Assert(sym.ContainingType Is Nothing) ' Skip unreferenced embedded types. If Not sym.IsEmbedded OrElse embeddedSymbolManager.IsSymbolReferenced(sym) Then Yield DirectCast(sym, NamedTypeSymbol).GetCciAdapter() End If Else Debug.Assert(sym.Kind = SymbolKind.Namespace) Dim members As ImmutableArray(Of Symbol) = sym.GetMembers() For i As Integer = members.Length - 1 To 0 Step -1 Dim namespaceOrType As NamespaceOrTypeSymbol = TryCast(members(i), NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then stack.Push(namespaceOrType) End If Next End If Loop While stack.Count > 0 End Function Public NotOverridable Overrides Function GetExportedTypes(diagnostics As DiagnosticBag) As ImmutableArray(Of Cci.ExportedType) Debug.Assert(HaveDeterminedTopLevelTypes) If _lazyExportedTypes.IsDefault Then _lazyExportedTypes = CalculateExportedTypes() If _lazyExportedTypes.Length > 0 Then ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics) End If End If Return _lazyExportedTypes End Function ''' <summary> ''' Builds an array of public type symbols defined in netmodules included in the compilation ''' And type forwarders defined in this compilation Or any included netmodule (in this order). ''' </summary> Private Function CalculateExportedTypes() As ImmutableArray(Of Cci.ExportedType) Dim builder = ArrayBuilder(Of Cci.ExportedType).GetInstance() Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly If Not OutputKind.IsNetModule() Then Dim modules = sourceAssembly.Modules For i As Integer = 1 To modules.Length - 1 'NOTE: skipping modules(0) GetExportedTypes(modules(i).GlobalNamespace, -1, builder) Next End If Debug.Assert(OutputKind.IsNetModule() = sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) GetForwardedTypes(sourceAssembly, builder) Return builder.ToImmutableAndFree() End Function ''' <summary> ''' Returns a set of top-level forwarded types ''' </summary> Friend Shared Function GetForwardedTypes(sourceAssembly As SourceAssemblySymbol, builderOpt As ArrayBuilder(Of Cci.ExportedType)) As HashSet(Of NamedTypeSymbol) Dim seenTopLevelForwardedTypes = New HashSet(Of NamedTypeSymbol)() GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builderOpt) If Not sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule() Then GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builderOpt) End If Return seenTopLevelForwardedTypes End Function Private Sub ReportExportedTypeNameCollisions(exportedTypes As ImmutableArray(Of Cci.ExportedType), diagnostics As DiagnosticBag) Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly Dim exportedNamesMap = New Dictionary(Of String, NamedTypeSymbol)() For Each exportedType In _lazyExportedTypes Dim typeReference As Cci.ITypeReference = exportedType.Type Dim type = DirectCast(typeReference.GetInternalSymbol(), NamedTypeSymbol) Debug.Assert(type.IsDefinition) If type.ContainingType IsNot Nothing Then Continue For End If ' exported types are not emitted in EnC deltas (hence generation 0): Dim fullEmittedName As String = MetadataHelpers.BuildQualifiedName( DirectCast(typeReference, Cci.INamespaceTypeReference).NamespaceName, Cci.MetadataWriter.GetMangledName(DirectCast(typeReference, Cci.INamedTypeReference), generation:=0)) ' First check against types declared in the primary module If ContainsTopLevelType(fullEmittedName) Then If type.ContainingAssembly Is sourceAssembly Then diagnostics.Add(ERRID.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule) Else diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type)) End If Continue For End If Dim contender As NamedTypeSymbol = Nothing ' Now check against other exported types If exportedNamesMap.TryGetValue(fullEmittedName, contender) Then If type.ContainingAssembly Is sourceAssembly Then ' all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly Is sourceAssembly) diagnostics.Add(ERRID.ERR_ExportedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), CustomSymbolDisplayFormatter.DefaultErrorFormat(type.ContainingModule), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) ElseIf contender.ContainingAssembly Is sourceAssembly Then ' Forwarded type conflicts with exported type diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) Else ' Forwarded type conflicts with another forwarded type diagnostics.Add(ERRID.ERR_ForwardedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), contender.ContainingAssembly) End If Continue For End If exportedNamesMap.Add(fullEmittedName, type) Next End Sub Private Overloads Sub GetExportedTypes(symbol As NamespaceOrTypeSymbol, parentIndex As Integer, builder As ArrayBuilder(Of Cci.ExportedType)) Dim index As Integer If symbol.Kind = SymbolKind.NamedType Then If symbol.DeclaredAccessibility <> Accessibility.Public Then Return End If Debug.Assert(symbol.IsDefinition) index = builder.Count builder.Add(New Cci.ExportedType(DirectCast(symbol, NamedTypeSymbol).GetCciAdapter(), parentIndex, isForwarder:=False)) Else index = -1 End If For Each member In symbol.GetMembers() Dim namespaceOrType = TryCast(member, NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then GetExportedTypes(namespaceOrType, index, builder) End If Next End Sub Private Shared Sub GetForwardedTypes( seenTopLevelTypes As HashSet(Of NamedTypeSymbol), wellKnownAttributeData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol), builderOpt As ArrayBuilder(Of Cci.ExportedType)) If wellKnownAttributeData?.ForwardedTypes?.Count > 0 Then ' (type, index of the parent exported type in builder, or -1 if the type is a top-level type) Dim stack = ArrayBuilder(Of (type As NamedTypeSymbol, parentIndex As Integer)).GetInstance() ' Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. Dim orderedForwardedTypes As IEnumerable(Of NamedTypeSymbol) = wellKnownAttributeData.ForwardedTypes If builderOpt IsNot Nothing Then orderedForwardedTypes = orderedForwardedTypes.OrderBy(Function(t) t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)) End If For Each forwardedType As NamedTypeSymbol In orderedForwardedTypes Dim originalDefinition As NamedTypeSymbol = forwardedType.OriginalDefinition Debug.Assert(originalDefinition.ContainingType Is Nothing, "How did a nested type get forwarded?") ' De-dup the original definitions before emitting. If Not seenTopLevelTypes.Add(originalDefinition) Then Continue For End If If builderOpt IsNot Nothing Then ' Return all nested types. ' Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count = 0) stack.Push((originalDefinition, -1)) While stack.Count > 0 Dim entry = stack.Pop() ' In general, we don't want private types to appear in the ExportedTypes table. If entry.type.DeclaredAccessibility = Accessibility.Private Then ' NOTE: this will also exclude nested types of curr. Continue While End If ' NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. Dim index = builderOpt.Count builderOpt.Add(New Cci.ExportedType(entry.type.GetCciAdapter(), entry.parentIndex, isForwarder:=True)) ' Iterate backwards so they get popped in forward order. Dim nested As ImmutableArray(Of NamedTypeSymbol) = entry.type.GetTypeMembers() ' Ordered. For i As Integer = nested.Length - 1 To 0 Step -1 stack.Push((nested(i), index)) Next End While End If Next stack.Free() End If End Sub Friend Iterator Function GetReferencedAssembliesUsedSoFar() As IEnumerable(Of AssemblySymbol) For Each assembly In SourceModule.GetReferencedAssemblySymbols() If Not assembly.IsLinked AndAlso Not assembly.IsMissing AndAlso m_AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(assembly) Then Yield assembly End If Next End Function Friend NotOverridable Overrides Function GetSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference Return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), needDeclaration:=True, syntaxNodeOpt:=syntaxNodeOpt, diagnostics:=diagnostics) End Function Private Function GetUntranslatedSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As NamedTypeSymbol Dim typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType) Dim info = Binder.GetUseSiteInfoForSpecialType(typeSymbol) If info.DiagnosticInfo IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, If(syntaxNodeOpt IsNot Nothing, syntaxNodeOpt.GetLocation(), NoLocation.Singleton), info.DiagnosticInfo) End If Return typeSymbol End Function Public NotOverridable Overrides Function GetInitArrayHelper() As Cci.IMethodReference Return DirectCast(Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle), MethodSymbol)?.GetCciAdapter() End Function Public NotOverridable Overrides Function IsPlatformType(typeRef As Cci.ITypeReference, platformType As Cci.PlatformType) As Boolean Dim namedType = TryCast(typeRef.GetInternalSymbol(), NamedTypeSymbol) If namedType IsNot Nothing Then If platformType = Cci.PlatformType.SystemType Then Return namedType Is Compilation.GetWellKnownType(WellKnownType.System_Type) End If Return namedType.SpecialType = CType(platformType, SpecialType) End If Return False End Function Protected NotOverridable Overrides Function GetCorLibraryReferenceToEmit(context As EmitContext) As Cci.IAssemblyReference Dim corLib = CorLibrary If Not corLib.IsMissing AndAlso Not corLib.IsLinked AndAlso corLib IsNot SourceModule.ContainingAssembly Then Return Translate(corLib, context.Diagnostics) End If Return Nothing End Function Friend NotOverridable Overrides Function GetSynthesizedNestedTypes(container As NamedTypeSymbol) As IEnumerable(Of Cci.INestedTypeDefinition) Return container.GetSynthesizedNestedTypes() End Function Public Overrides Iterator Function GetTypeToDebugDocumentMap(context As EmitContext) As IEnumerable(Of (Cci.ITypeDefinition, ImmutableArray(Of Cci.DebugSourceDocument))) Dim typesToProcess = ArrayBuilder(Of Cci.ITypeDefinition).GetInstance() Dim debugDocuments = ArrayBuilder(Of Cci.DebugSourceDocument).GetInstance() Dim methodDocumentList = PooledHashSet(Of Cci.DebugSourceDocument).GetInstance() Dim namespacesAndTopLevelTypesToProcess = ArrayBuilder(Of NamespaceOrTypeSymbol).GetInstance() namespacesAndTopLevelTypesToProcess.Push(SourceModule.GlobalNamespace) While namespacesAndTopLevelTypesToProcess.Count > 0 Dim symbol = namespacesAndTopLevelTypesToProcess.Pop() If symbol.Locations.Length = 0 Then Continue While End If Select Case symbol.Kind Case SymbolKind.Namespace Dim location = GetSmallestSourceLocationOrNull(symbol) ' filtering out synthesized symbols not having real source ' locations such as anonymous types, my types, etc... If location IsNot Nothing Then For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType namespacesAndTopLevelTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case SymbolKind.NamedType ' We only process top level types in this method, and only return documents for types if there are no ' methods that would refer to the same document, either in the type or in any nested type. Debug.Assert(debugDocuments.Count = 0) Debug.Assert(methodDocumentList.Count = 0) Debug.Assert(typesToProcess.Count = 0) Dim typeDefinition = DirectCast(symbol.GetCciAdapter(), Cci.ITypeDefinition) typesToProcess.Push(typeDefinition) GetDocumentsForMethodsAndNestedTypes(methodDocumentList, typesToProcess, context) For Each loc In symbol.Locations If Not loc.IsInSource Then Continue For End If Dim span = loc.GetLineSpan() Dim debugDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=Nothing) If debugDocument IsNot Nothing AndAlso Not methodDocumentList.Contains(debugDocument) Then debugDocuments.Add(debugDocument) End If Next If debugDocuments.Count > 0 Then Yield (typeDefinition, debugDocuments.ToImmutable()) End If debugDocuments.Clear() methodDocumentList.Clear() Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select End While namespacesAndTopLevelTypesToProcess.Free() debugDocuments.Free() methodDocumentList.Free() typesToProcess.Free() End Function Private Shared Sub GetDocumentsForMethodsAndNestedTypes(documentList As PooledHashSet(Of Cci.DebugSourceDocument), typesToProcess As ArrayBuilder(Of Cci.ITypeDefinition), context As EmitContext) While typesToProcess.Count > 0 Dim definition = typesToProcess.Pop() Dim typeMethods = definition.GetMethods(context) For Each method In typeMethods Dim body = method.GetBody(context) If body Is Nothing Then Continue For End If For Each point In body.SequencePoints documentList.Add(point.Document) Next Next Dim nestedTypes = definition.GetNestedTypes(context) For Each nestedTypeDefinition In nestedTypes typesToProcess.Push(nestedTypeDefinition) Next End While End Sub Public Sub SetDisableJITOptimization(methodSymbol As MethodSymbol) Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) _disableJITOptimization.TryAdd(methodSymbol, True) End Sub Public Function JITOptimizationIsDisabled(methodSymbol As MethodSymbol) As Boolean Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) Return _disableJITOptimization.ContainsKey(methodSymbol) End Function Protected NotOverridable Overrides Function CreatePrivateImplementationDetailsStaticConstructor(details As PrivateImplementationDetails, syntaxOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.IMethodDefinition Return New SynthesizedPrivateImplementationDetailsSharedConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter() End Function Public Overrides Function GetAdditionalTopLevelTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetAdditionalTopLevelTypes().Select(Function(t) t.GetCciAdapter()) #Else Return GetAdditionalTopLevelTypes() #End If End Function Public Overrides Function GetEmbeddedTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetEmbeddedTypes(context.Diagnostics).Select(Function(t) t.GetCciAdapter()) #Else Return GetEmbeddedTypes(context.Diagnostics) #End If End Function End Class End Namespace
1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Dependencies/CodeAnalysis.Debugging/PortableCustomDebugInfoKinds.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Debugging { internal static class PortableCustomDebugInfoKinds { public static readonly Guid AsyncMethodSteppingInformationBlob = new("54FD2AC5-E925-401A-9C2A-F94F171072F8"); public static readonly Guid StateMachineHoistedLocalScopes = new("6DA9A61E-F8C7-4874-BE62-68BC5630DF71"); public static readonly Guid DynamicLocalVariables = new("83C563C4-B4F3-47D5-B824-BA5441477EA8"); public static readonly Guid TupleElementNames = new("ED9FDF71-8879-4747-8ED3-FE5EDE3CE710"); public static readonly Guid DefaultNamespace = new("58b2eab6-209f-4e4e-a22c-b2d0f910c782"); public static readonly Guid EncLocalSlotMap = new("755F52A8-91C5-45BE-B4B8-209571E552BD"); public static readonly Guid EncLambdaAndClosureMap = new("A643004C-0240-496F-A783-30D64F4979DE"); public static readonly Guid SourceLink = new("CC110556-A091-4D38-9FEC-25AB9A351A6A"); public static readonly Guid EmbeddedSource = new("0E8A571B-6926-466E-B4AD-8AB04611F5FE"); public static readonly Guid CompilationMetadataReferences = new("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D"); public static readonly Guid CompilationOptions = new("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Debugging { internal static class PortableCustomDebugInfoKinds { public static readonly Guid AsyncMethodSteppingInformationBlob = new("54FD2AC5-E925-401A-9C2A-F94F171072F8"); public static readonly Guid StateMachineHoistedLocalScopes = new("6DA9A61E-F8C7-4874-BE62-68BC5630DF71"); public static readonly Guid DynamicLocalVariables = new("83C563C4-B4F3-47D5-B824-BA5441477EA8"); public static readonly Guid TupleElementNames = new("ED9FDF71-8879-4747-8ED3-FE5EDE3CE710"); public static readonly Guid DefaultNamespace = new("58b2eab6-209f-4e4e-a22c-b2d0f910c782"); public static readonly Guid EncLocalSlotMap = new("755F52A8-91C5-45BE-B4B8-209571E552BD"); public static readonly Guid EncLambdaAndClosureMap = new("A643004C-0240-496F-A783-30D64F4979DE"); public static readonly Guid SourceLink = new("CC110556-A091-4D38-9FEC-25AB9A351A6A"); public static readonly Guid EmbeddedSource = new("0E8A571B-6926-466E-B4AD-8AB04611F5FE"); public static readonly Guid CompilationMetadataReferences = new("7E4D4708-096E-4C5C-AEDA-CB10BA6A740D"); public static readonly Guid CompilationOptions = new("B5FEEC05-8CD0-4A83-96DA-466284BB4BD8"); public static readonly Guid TypeDefinitionDocuments = new("932E74BC-DBA9-4478-8D46-0F32A7BAB3D3"); } }
1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/Symbols/TypeKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Enumeration for possible kinds of type symbols. /// </summary> public enum TypeKind : byte { /// <summary> /// Type's kind is undefined. /// </summary> Unknown = 0, /// <summary> /// Type is an array type. /// </summary> Array = 1, /// <summary> /// Type is a class. /// </summary> Class = 2, /// <summary> /// Type is a delegate. /// </summary> Delegate = 3, /// <summary> /// Type is dynamic. /// </summary> Dynamic = 4, /// <summary> /// Type is an enumeration. /// </summary> Enum = 5, /// <summary> /// Type is an error type. /// </summary> Error = 6, /// <summary> /// Type is an interface. /// </summary> Interface = 7, /// <summary> /// Type is a module. /// </summary> Module = 8, /// <summary> /// Type is a pointer. /// </summary> Pointer = 9, /// <summary> /// Type is a C# struct or VB Structure /// </summary> Struct = 10, /// <summary> /// Type is a C# struct or VB Structure /// </summary> Structure = 10, /// <summary> /// Type is a type parameter. /// </summary> TypeParameter = 11, /// <summary> /// Type is an interactive submission. /// </summary> Submission = 12, /// <summary> /// Type is a function pointer. /// </summary> FunctionPointer = 13, } internal static class TypeKindInternal { /// <summary> /// Internal Symbol representing the inferred signature of /// a lambda expression or method group. /// </summary> internal const TypeKind FunctionType = (TypeKind)255; #if DEBUG static TypeKindInternal() { Debug.Assert(!EnumUtilities.ContainsValue(FunctionType)); } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Enumeration for possible kinds of type symbols. /// </summary> public enum TypeKind : byte { /// <summary> /// Type's kind is undefined. /// </summary> Unknown = 0, /// <summary> /// Type is an array type. /// </summary> Array = 1, /// <summary> /// Type is a class. /// </summary> Class = 2, /// <summary> /// Type is a delegate. /// </summary> Delegate = 3, /// <summary> /// Type is dynamic. /// </summary> Dynamic = 4, /// <summary> /// Type is an enumeration. /// </summary> Enum = 5, /// <summary> /// Type is an error type. /// </summary> Error = 6, /// <summary> /// Type is an interface. /// </summary> Interface = 7, /// <summary> /// Type is a module. /// </summary> Module = 8, /// <summary> /// Type is a pointer. /// </summary> Pointer = 9, /// <summary> /// Type is a C# struct or VB Structure /// </summary> Struct = 10, /// <summary> /// Type is a C# struct or VB Structure /// </summary> Structure = 10, /// <summary> /// Type is a type parameter. /// </summary> TypeParameter = 11, /// <summary> /// Type is an interactive submission. /// </summary> Submission = 12, /// <summary> /// Type is a function pointer. /// </summary> FunctionPointer = 13, } internal static class TypeKindInternal { /// <summary> /// Internal Symbol representing the inferred signature of /// a lambda expression or method group. /// </summary> internal const TypeKind FunctionType = (TypeKind)255; #if DEBUG static TypeKindInternal() { Debug.Assert(!EnumUtilities.ContainsValue(FunctionType)); } #endif } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/VariableDeclaratorExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class VariableDeclaratorExtensions { public static TypeSyntax GetVariableType(this VariableDeclaratorSyntax declarator) { if (declarator.Parent is VariableDeclarationSyntax variableDeclaration) { return variableDeclaration.Type; } return null; } public static bool IsTypeInferred(this VariableDeclaratorSyntax variable, SemanticModel semanticModel) { var variableTypeName = variable.GetVariableType(); if (variableTypeName == null) { return false; } return variableTypeName.IsTypeInferred(semanticModel); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class VariableDeclaratorExtensions { public static TypeSyntax GetVariableType(this VariableDeclaratorSyntax declarator) { if (declarator.Parent is VariableDeclarationSyntax variableDeclaration) { return variableDeclaration.Type; } return null; } public static bool IsTypeInferred(this VariableDeclaratorSyntax variable, SemanticModel semanticModel) { var variableTypeName = variable.GetVariableType(); if (variableTypeName == null) { return false; } return variableTypeName.IsTypeInferred(semanticModel); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/Core/Def/Implementation/Progression/IProgressionLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal interface IProgressionLanguageService : ILanguageService { IEnumerable<SyntaxNode> GetTopLevelNodesFromDocument(SyntaxNode root, CancellationToken cancellationToken); string GetDescriptionForSymbol(ISymbol symbol, bool includeContainingSymbol); string GetLabelForSymbol(ISymbol symbol, bool includeContainingSymbol); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal interface IProgressionLanguageService : ILanguageService { IEnumerable<SyntaxNode> GetTopLevelNodesFromDocument(SyntaxNode root, CancellationToken cancellationToken); string GetDescriptionForSymbol(ISymbol symbol, bool includeContainingSymbol); string GetLabelForSymbol(ISymbol symbol, bool includeContainingSymbol); } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/ErrorList_OutOfProc.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public partial class ErrorList_OutOfProc : OutOfProcComponent { private readonly ErrorList_InProc _inProc; private readonly VisualStudioInstance _instance; public Verifier Verify { get; } public ErrorList_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _instance = visualStudioInstance; _inProc = CreateInProcComponent<ErrorList_InProc>(visualStudioInstance); Verify = new Verifier(this, _instance); } public int ErrorListErrorCount => _inProc.ErrorListErrorCount; public void ShowErrorList() { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorSquiggles); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorList); _inProc.ShowErrorList(); } public void WaitForNoErrorsInErrorList(TimeSpan timeout) => _inProc.WaitForNoErrorsInErrorList(timeout); public int GetErrorListErrorCount() => _inProc.GetErrorCount(); public ErrorListItem[] GetErrorListContents() { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorSquiggles); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorList); return _inProc.GetErrorListContents(); } public ErrorListItem NavigateToErrorListItem(int itemIndex) { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorSquiggles); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorList); return _inProc.NavigateToErrorListItem(itemIndex); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public partial class ErrorList_OutOfProc : OutOfProcComponent { private readonly ErrorList_InProc _inProc; private readonly VisualStudioInstance _instance; public Verifier Verify { get; } public ErrorList_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { _instance = visualStudioInstance; _inProc = CreateInProcComponent<ErrorList_InProc>(visualStudioInstance); Verify = new Verifier(this, _instance); } public int ErrorListErrorCount => _inProc.ErrorListErrorCount; public void ShowErrorList() { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorSquiggles); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorList); _inProc.ShowErrorList(); } public void WaitForNoErrorsInErrorList(TimeSpan timeout) => _inProc.WaitForNoErrorsInErrorList(timeout); public int GetErrorListErrorCount() => _inProc.GetErrorCount(); public ErrorListItem[] GetErrorListContents() { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorSquiggles); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorList); return _inProc.GetErrorListContents(); } public ErrorListItem NavigateToErrorListItem(int itemIndex) { _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.SolutionCrawler); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.DiagnosticService); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorSquiggles); _instance.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.ErrorList); return _inProc.NavigateToErrorListItem(itemIndex); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/Core/Portable/CodeLens/ICodeLensReferencesService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeLens { internal interface ICodeLensReferencesService : IWorkspaceService { ValueTask<VersionStamp> GetProjectCodeLensVersionAsync(Solution solution, ProjectId projectId, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the number of locations where the located node is referenced. /// <para> /// Optionally, the service supports capping the reference count to a value specified by <paramref name="maxSearchResults"/> /// if <paramref name="maxSearchResults"/> is greater than 0. /// </para> /// </summary> Task<ReferenceCount?> GetReferenceCountAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, int maxSearchResults, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations where the located node is referenced. /// </summary> Task<ImmutableArray<ReferenceLocationDescriptor>?> FindReferenceLocationsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations of methods that refer to the located node. /// </summary> Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the fully qualified name of the located node's declaration. /// </summary> Task<string?> GetFullyQualifiedNameAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.CodeLens { internal interface ICodeLensReferencesService : IWorkspaceService { ValueTask<VersionStamp> GetProjectCodeLensVersionAsync(Solution solution, ProjectId projectId, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the number of locations where the located node is referenced. /// <para> /// Optionally, the service supports capping the reference count to a value specified by <paramref name="maxSearchResults"/> /// if <paramref name="maxSearchResults"/> is greater than 0. /// </para> /// </summary> Task<ReferenceCount?> GetReferenceCountAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, int maxSearchResults, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations where the located node is referenced. /// </summary> Task<ImmutableArray<ReferenceLocationDescriptor>?> FindReferenceLocationsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations of methods that refer to the located node. /// </summary> Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the fully qualified name of the located node's declaration. /// </summary> Task<string?> GetFullyQualifiedNameAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Binder/LockOrUsingBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <remarks> /// This type exists to share code between UsingStatementBinder and LockBinder. /// </remarks> internal abstract class LockOrUsingBinder : LocalScopeBinder { private ImmutableHashSet<Symbol> _lazyLockedOrDisposedVariables; private ExpressionAndDiagnostics _lazyExpressionAndDiagnostics; internal LockOrUsingBinder(Binder enclosing) : base(enclosing) { } protected abstract ExpressionSyntax TargetExpressionSyntax { get; } internal sealed override ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { if (_lazyLockedOrDisposedVariables == null) { ImmutableHashSet<Symbol> lockedOrDisposedVariables = this.Next.LockedOrDisposedVariables; ExpressionSyntax targetExpressionSyntax = TargetExpressionSyntax; if (targetExpressionSyntax != null) { // We rely on this in the GetBinder call below. Debug.Assert(targetExpressionSyntax.Parent.Kind() == SyntaxKind.LockStatement || targetExpressionSyntax.Parent.Kind() == SyntaxKind.UsingStatement); // For some reason, dev11 only warnings about locals and parameters. If you do the same thing // with a field of a local or parameter (e.g. lock(p.x)), there's no warning when you modify // the local/parameter or its field. We're going to take advantage of this restriction to break // a cycle: if the expression contains any lvalues, the binder is going to check LockedOrDisposedVariables, // which is going to bind the expression, which is going to check LockedOrDisposedVariables, etc. // Fortunately, SyntaxKind.IdentifierName includes local and parameter accesses, but no expressions // that require lvalue checks. if (targetExpressionSyntax.Kind() == SyntaxKind.IdentifierName) { BoundExpression expression = BindTargetExpression(diagnostics: null, // Diagnostics reported by BindUsingStatementParts. originalBinder: GetBinder(targetExpressionSyntax.Parent)); switch (expression.Kind) { case BoundKind.Local: lockedOrDisposedVariables = lockedOrDisposedVariables.Add(((BoundLocal)expression).LocalSymbol); break; case BoundKind.Parameter: lockedOrDisposedVariables = lockedOrDisposedVariables.Add(((BoundParameter)expression).ParameterSymbol); break; } } } Interlocked.CompareExchange(ref _lazyLockedOrDisposedVariables, lockedOrDisposedVariables, null); } Debug.Assert(_lazyLockedOrDisposedVariables != null); return _lazyLockedOrDisposedVariables; } } protected BoundExpression BindTargetExpression(BindingDiagnosticBag diagnostics, Binder originalBinder, TypeSymbol targetTypeOpt = null) { if (_lazyExpressionAndDiagnostics == null) { // Filter out method group in conversion. var expressionDiagnostics = BindingDiagnosticBag.GetInstance(); BoundExpression boundExpression = originalBinder.BindValue(TargetExpressionSyntax, expressionDiagnostics, Binder.BindValueKind.RValueOrMethodGroup); if (targetTypeOpt is object) { boundExpression = originalBinder.GenerateConversionForAssignment(targetTypeOpt, boundExpression, expressionDiagnostics); } else { boundExpression = originalBinder.BindToNaturalType(boundExpression, expressionDiagnostics); } Interlocked.CompareExchange(ref _lazyExpressionAndDiagnostics, new ExpressionAndDiagnostics(boundExpression, expressionDiagnostics.ToReadOnlyAndFree()), null); } Debug.Assert(_lazyExpressionAndDiagnostics != null); if (diagnostics != null) { diagnostics.AddRange(_lazyExpressionAndDiagnostics.Diagnostics, allowMismatchInDependencyAccumulation: true); } return _lazyExpressionAndDiagnostics.Expression; } /// <remarks> /// This class exists so these two fields can be set atomically. /// CONSIDER: If this causes too many allocations, we could use start and end flags plus spinlocking /// as for completion parts. /// </remarks> private class ExpressionAndDiagnostics { public readonly BoundExpression Expression; public readonly ImmutableBindingDiagnostic<AssemblySymbol> Diagnostics; public ExpressionAndDiagnostics(BoundExpression expression, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics) { this.Expression = expression; this.Diagnostics = diagnostics; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <remarks> /// This type exists to share code between UsingStatementBinder and LockBinder. /// </remarks> internal abstract class LockOrUsingBinder : LocalScopeBinder { private ImmutableHashSet<Symbol> _lazyLockedOrDisposedVariables; private ExpressionAndDiagnostics _lazyExpressionAndDiagnostics; internal LockOrUsingBinder(Binder enclosing) : base(enclosing) { } protected abstract ExpressionSyntax TargetExpressionSyntax { get; } internal sealed override ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { if (_lazyLockedOrDisposedVariables == null) { ImmutableHashSet<Symbol> lockedOrDisposedVariables = this.Next.LockedOrDisposedVariables; ExpressionSyntax targetExpressionSyntax = TargetExpressionSyntax; if (targetExpressionSyntax != null) { // We rely on this in the GetBinder call below. Debug.Assert(targetExpressionSyntax.Parent.Kind() == SyntaxKind.LockStatement || targetExpressionSyntax.Parent.Kind() == SyntaxKind.UsingStatement); // For some reason, dev11 only warnings about locals and parameters. If you do the same thing // with a field of a local or parameter (e.g. lock(p.x)), there's no warning when you modify // the local/parameter or its field. We're going to take advantage of this restriction to break // a cycle: if the expression contains any lvalues, the binder is going to check LockedOrDisposedVariables, // which is going to bind the expression, which is going to check LockedOrDisposedVariables, etc. // Fortunately, SyntaxKind.IdentifierName includes local and parameter accesses, but no expressions // that require lvalue checks. if (targetExpressionSyntax.Kind() == SyntaxKind.IdentifierName) { BoundExpression expression = BindTargetExpression(diagnostics: null, // Diagnostics reported by BindUsingStatementParts. originalBinder: GetBinder(targetExpressionSyntax.Parent)); switch (expression.Kind) { case BoundKind.Local: lockedOrDisposedVariables = lockedOrDisposedVariables.Add(((BoundLocal)expression).LocalSymbol); break; case BoundKind.Parameter: lockedOrDisposedVariables = lockedOrDisposedVariables.Add(((BoundParameter)expression).ParameterSymbol); break; } } } Interlocked.CompareExchange(ref _lazyLockedOrDisposedVariables, lockedOrDisposedVariables, null); } Debug.Assert(_lazyLockedOrDisposedVariables != null); return _lazyLockedOrDisposedVariables; } } protected BoundExpression BindTargetExpression(BindingDiagnosticBag diagnostics, Binder originalBinder, TypeSymbol targetTypeOpt = null) { if (_lazyExpressionAndDiagnostics == null) { // Filter out method group in conversion. var expressionDiagnostics = BindingDiagnosticBag.GetInstance(); BoundExpression boundExpression = originalBinder.BindValue(TargetExpressionSyntax, expressionDiagnostics, Binder.BindValueKind.RValueOrMethodGroup); if (targetTypeOpt is object) { boundExpression = originalBinder.GenerateConversionForAssignment(targetTypeOpt, boundExpression, expressionDiagnostics); } else { boundExpression = originalBinder.BindToNaturalType(boundExpression, expressionDiagnostics); } Interlocked.CompareExchange(ref _lazyExpressionAndDiagnostics, new ExpressionAndDiagnostics(boundExpression, expressionDiagnostics.ToReadOnlyAndFree()), null); } Debug.Assert(_lazyExpressionAndDiagnostics != null); if (diagnostics != null) { diagnostics.AddRange(_lazyExpressionAndDiagnostics.Diagnostics, allowMismatchInDependencyAccumulation: true); } return _lazyExpressionAndDiagnostics.Expression; } /// <remarks> /// This class exists so these two fields can be set atomically. /// CONSIDER: If this causes too many allocations, we could use start and end flags plus spinlocking /// as for completion parts. /// </remarks> private class ExpressionAndDiagnostics { public readonly BoundExpression Expression; public readonly ImmutableBindingDiagnostic<AssemblySymbol> Diagnostics; public ExpressionAndDiagnostics(BoundExpression expression, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics) { this.Expression = expression; this.Diagnostics = diagnostics; } } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/EditorFeatures/CSharp/InheritanceMargin/CSharpInheritanceMarginService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InheritanceMargin; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.InheritanceMargin { [ExportLanguageService(typeof(IInheritanceMarginService), LanguageNames.CSharp), Shared] internal class CSharpInheritanceMarginService : AbstractInheritanceMarginService { [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] [ImportingConstructor] public CSharpInheritanceMarginService() { } protected override ImmutableArray<SyntaxNode> GetMembers(IEnumerable<SyntaxNode> nodesToSearch) { var typeDeclarationNodes = nodesToSearch.OfType<TypeDeclarationSyntax>(); using var _ = PooledObjects.ArrayBuilder<SyntaxNode>.GetInstance(out var builder); foreach (var typeDeclarationNode in typeDeclarationNodes) { // 1. Add the type declaration node.(e.g. class, struct etc..) // Use its identifier's position as the line number, since we want the margin to be placed with the identifier builder.Add(typeDeclarationNode); // 2. Add type members inside this type declaration. foreach (var member in typeDeclarationNode.Members) { if (member.IsKind( SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.EventDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.OperatorDeclaration, SyntaxKind.ConversionOperatorDeclaration)) { builder.Add(member); } // For multiple events that declared in the same EventFieldDeclaration, // add all VariableDeclarators if (member is EventFieldDeclarationSyntax eventFieldDeclarationNode) { builder.AddRange(eventFieldDeclarationNode.Declaration.Variables); } } } return builder.ToImmutableArray(); } protected override SyntaxToken GetDeclarationToken(SyntaxNode declarationNode) => declarationNode switch { MethodDeclarationSyntax methodDeclarationNode => methodDeclarationNode.Identifier, PropertyDeclarationSyntax propertyDeclarationNode => propertyDeclarationNode.Identifier, EventDeclarationSyntax eventDeclarationNode => eventDeclarationNode.Identifier, VariableDeclaratorSyntax variableDeclaratorNode => variableDeclaratorNode.Identifier, TypeDeclarationSyntax baseTypeDeclarationNode => baseTypeDeclarationNode.Identifier, IndexerDeclarationSyntax indexerDeclarationNode => indexerDeclarationNode.ThisKeyword, OperatorDeclarationSyntax operatorDeclarationNode => operatorDeclarationNode.OperatorToken, ConversionOperatorDeclarationSyntax conversionOperatorDeclarationNode => conversionOperatorDeclarationNode.Type.GetFirstToken(), // Shouldn't reach here since the input declaration nodes are coming from GetMembers() method above _ => throw ExceptionUtilities.UnexpectedValue(declarationNode), }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InheritanceMargin; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.InheritanceMargin { [ExportLanguageService(typeof(IInheritanceMarginService), LanguageNames.CSharp), Shared] internal class CSharpInheritanceMarginService : AbstractInheritanceMarginService { [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] [ImportingConstructor] public CSharpInheritanceMarginService() { } protected override ImmutableArray<SyntaxNode> GetMembers(IEnumerable<SyntaxNode> nodesToSearch) { var typeDeclarationNodes = nodesToSearch.OfType<TypeDeclarationSyntax>(); using var _ = PooledObjects.ArrayBuilder<SyntaxNode>.GetInstance(out var builder); foreach (var typeDeclarationNode in typeDeclarationNodes) { // 1. Add the type declaration node.(e.g. class, struct etc..) // Use its identifier's position as the line number, since we want the margin to be placed with the identifier builder.Add(typeDeclarationNode); // 2. Add type members inside this type declaration. foreach (var member in typeDeclarationNode.Members) { if (member.IsKind( SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration, SyntaxKind.EventDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.OperatorDeclaration, SyntaxKind.ConversionOperatorDeclaration)) { builder.Add(member); } // For multiple events that declared in the same EventFieldDeclaration, // add all VariableDeclarators if (member is EventFieldDeclarationSyntax eventFieldDeclarationNode) { builder.AddRange(eventFieldDeclarationNode.Declaration.Variables); } } } return builder.ToImmutableArray(); } protected override SyntaxToken GetDeclarationToken(SyntaxNode declarationNode) => declarationNode switch { MethodDeclarationSyntax methodDeclarationNode => methodDeclarationNode.Identifier, PropertyDeclarationSyntax propertyDeclarationNode => propertyDeclarationNode.Identifier, EventDeclarationSyntax eventDeclarationNode => eventDeclarationNode.Identifier, VariableDeclaratorSyntax variableDeclaratorNode => variableDeclaratorNode.Identifier, TypeDeclarationSyntax baseTypeDeclarationNode => baseTypeDeclarationNode.Identifier, IndexerDeclarationSyntax indexerDeclarationNode => indexerDeclarationNode.ThisKeyword, OperatorDeclarationSyntax operatorDeclarationNode => operatorDeclarationNode.OperatorToken, ConversionOperatorDeclarationSyntax conversionOperatorDeclarationNode => conversionOperatorDeclarationNode.Type.GetFirstToken(), // Shouldn't reach here since the input declaration nodes are coming from GetMembers() method above _ => throw ExceptionUtilities.UnexpectedValue(declarationNode), }; } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Operations/CSharpOperationFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString { InterpolationData: not null } or BoundBinaryOperator { InterpolatedStringHandlerData: not null }); var interpolatedString = Create(boundOperand); return new NoneOperation(ImmutableArray.Create(interpolatedString), _semanticModel, boundConversion.Syntax, boundConversion.GetPublicTypeSymbol(), boundConversion.ConstantValue, isImplicit); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = boundAsOperator.Conversion; bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = boundCompoundAssignmentOperator.LeftConversion; Conversion outConversion = boundCompoundAssignmentOperator.FinalConversion; bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { if (boundBinaryOperatorBase is BoundBinaryOperator { InterpolatedStringHandlerData: not null } binary) { return CreateBoundInterpolatedStringBinaryOperator(binary); } // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null and not BoundBinaryOperator { InterpolatedStringHandlerData: not null }); Debug.Assert(stack.Count > 0); IOperation? left = null; while (stack.TryPop(out currentBinary)) { left ??= Create(currentBinary.Left); IOperation right = Create(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => CreateBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private IBinaryOperation CreateBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundInterpolatedStringBinaryOperator(BoundBinaryOperator boundBinaryOperator) { Debug.Assert(boundBinaryOperator.InterpolatedStringHandlerData is not null); Func<BoundInterpolatedString, int, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createInterpolatedString = createInterpolatedStringOperand; Func<BoundBinaryOperator, IOperation, IOperation, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createBinaryOperator = createBoundBinaryOperatorOperation; return boundBinaryOperator.RewriteInterpolatedStringAddition((this, boundBinaryOperator.InterpolatedStringHandlerData.GetValueOrDefault()), createInterpolatedString, createBinaryOperator); static IInterpolatedStringOperation createInterpolatedStringOperand( BoundInterpolatedString boundInterpolatedString, int i, (CSharpOperationFactory @this, InterpolatedStringHandlerData Data) arg) => [email protected](boundInterpolatedString, arg.Data.PositionInfo[i]); static IBinaryOperation createBoundBinaryOperatorOperation( BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right, (CSharpOperationFactory @this, InterpolatedStringHandlerData _) arg) => [email protected](boundBinaryOperator, left, right); } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = boundNullCoalescingOperator.LeftConversion; if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), enumeratorInfoOpt.CurrentConversion, boundForEachStatement.ElementConversion, getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo = null) { Debug.Assert(positionInfo == null || boundInterpolatedString.InterpolationData == null); ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, positionInfo ?? boundInterpolatedString.InterpolationData?.PositionInfo[0]); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo) { return positionInfo is { } info ? createHandlerInterpolatedStringContent(info) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Operations { internal sealed partial class CSharpOperationFactory { private readonly SemanticModel _semanticModel; public CSharpOperationFactory(SemanticModel semanticModel) { _semanticModel = semanticModel; } [return: NotNullIfNotNull("boundNode")] public IOperation? Create(BoundNode? boundNode) { if (boundNode == null) { return null; } switch (boundNode.Kind) { case BoundKind.DeconstructValuePlaceholder: return CreateBoundDeconstructValuePlaceholderOperation((BoundDeconstructValuePlaceholder)boundNode); case BoundKind.DeconstructionAssignmentOperator: return CreateBoundDeconstructionAssignmentOperator((BoundDeconstructionAssignmentOperator)boundNode); case BoundKind.Call: return CreateBoundCallOperation((BoundCall)boundNode); case BoundKind.Local: return CreateBoundLocalOperation((BoundLocal)boundNode); case BoundKind.FieldAccess: return CreateBoundFieldAccessOperation((BoundFieldAccess)boundNode); case BoundKind.PropertyAccess: return CreateBoundPropertyAccessOperation((BoundPropertyAccess)boundNode); case BoundKind.IndexerAccess: return CreateBoundIndexerAccessOperation((BoundIndexerAccess)boundNode); case BoundKind.EventAccess: return CreateBoundEventAccessOperation((BoundEventAccess)boundNode); case BoundKind.EventAssignmentOperator: return CreateBoundEventAssignmentOperatorOperation((BoundEventAssignmentOperator)boundNode); case BoundKind.Parameter: return CreateBoundParameterOperation((BoundParameter)boundNode); case BoundKind.Literal: return CreateBoundLiteralOperation((BoundLiteral)boundNode); case BoundKind.DynamicInvocation: return CreateBoundDynamicInvocationExpressionOperation((BoundDynamicInvocation)boundNode); case BoundKind.DynamicIndexerAccess: return CreateBoundDynamicIndexerAccessExpressionOperation((BoundDynamicIndexerAccess)boundNode); case BoundKind.ObjectCreationExpression: return CreateBoundObjectCreationExpressionOperation((BoundObjectCreationExpression)boundNode); case BoundKind.WithExpression: return CreateBoundWithExpressionOperation((BoundWithExpression)boundNode); case BoundKind.DynamicObjectCreationExpression: return CreateBoundDynamicObjectCreationExpressionOperation((BoundDynamicObjectCreationExpression)boundNode); case BoundKind.ObjectInitializerExpression: return CreateBoundObjectInitializerExpressionOperation((BoundObjectInitializerExpression)boundNode); case BoundKind.CollectionInitializerExpression: return CreateBoundCollectionInitializerExpressionOperation((BoundCollectionInitializerExpression)boundNode); case BoundKind.ObjectInitializerMember: return CreateBoundObjectInitializerMemberOperation((BoundObjectInitializerMember)boundNode); case BoundKind.CollectionElementInitializer: return CreateBoundCollectionElementInitializerOperation((BoundCollectionElementInitializer)boundNode); case BoundKind.DynamicObjectInitializerMember: return CreateBoundDynamicObjectInitializerMemberOperation((BoundDynamicObjectInitializerMember)boundNode); case BoundKind.DynamicMemberAccess: return CreateBoundDynamicMemberAccessOperation((BoundDynamicMemberAccess)boundNode); case BoundKind.DynamicCollectionElementInitializer: return CreateBoundDynamicCollectionElementInitializerOperation((BoundDynamicCollectionElementInitializer)boundNode); case BoundKind.UnboundLambda: return CreateUnboundLambdaOperation((UnboundLambda)boundNode); case BoundKind.Lambda: return CreateBoundLambdaOperation((BoundLambda)boundNode); case BoundKind.Conversion: return CreateBoundConversionOperation((BoundConversion)boundNode); case BoundKind.AsOperator: return CreateBoundAsOperatorOperation((BoundAsOperator)boundNode); case BoundKind.IsOperator: return CreateBoundIsOperatorOperation((BoundIsOperator)boundNode); case BoundKind.SizeOfOperator: return CreateBoundSizeOfOperatorOperation((BoundSizeOfOperator)boundNode); case BoundKind.TypeOfOperator: return CreateBoundTypeOfOperatorOperation((BoundTypeOfOperator)boundNode); case BoundKind.ArrayCreation: return CreateBoundArrayCreationOperation((BoundArrayCreation)boundNode); case BoundKind.ArrayInitialization: return CreateBoundArrayInitializationOperation((BoundArrayInitialization)boundNode); case BoundKind.DefaultLiteral: return CreateBoundDefaultLiteralOperation((BoundDefaultLiteral)boundNode); case BoundKind.DefaultExpression: return CreateBoundDefaultExpressionOperation((BoundDefaultExpression)boundNode); case BoundKind.BaseReference: return CreateBoundBaseReferenceOperation((BoundBaseReference)boundNode); case BoundKind.ThisReference: return CreateBoundThisReferenceOperation((BoundThisReference)boundNode); case BoundKind.AssignmentOperator: return CreateBoundAssignmentOperatorOrMemberInitializerOperation((BoundAssignmentOperator)boundNode); case BoundKind.CompoundAssignmentOperator: return CreateBoundCompoundAssignmentOperatorOperation((BoundCompoundAssignmentOperator)boundNode); case BoundKind.IncrementOperator: return CreateBoundIncrementOperatorOperation((BoundIncrementOperator)boundNode); case BoundKind.BadExpression: return CreateBoundBadExpressionOperation((BoundBadExpression)boundNode); case BoundKind.NewT: return CreateBoundNewTOperation((BoundNewT)boundNode); case BoundKind.NoPiaObjectCreationExpression: return CreateNoPiaObjectCreationExpressionOperation((BoundNoPiaObjectCreationExpression)boundNode); case BoundKind.UnaryOperator: return CreateBoundUnaryOperatorOperation((BoundUnaryOperator)boundNode); case BoundKind.BinaryOperator: case BoundKind.UserDefinedConditionalLogicalOperator: return CreateBoundBinaryOperatorBase((BoundBinaryOperatorBase)boundNode); case BoundKind.TupleBinaryOperator: return CreateBoundTupleBinaryOperatorOperation((BoundTupleBinaryOperator)boundNode); case BoundKind.ConditionalOperator: return CreateBoundConditionalOperatorOperation((BoundConditionalOperator)boundNode); case BoundKind.NullCoalescingOperator: return CreateBoundNullCoalescingOperatorOperation((BoundNullCoalescingOperator)boundNode); case BoundKind.AwaitExpression: return CreateBoundAwaitExpressionOperation((BoundAwaitExpression)boundNode); case BoundKind.ArrayAccess: return CreateBoundArrayAccessOperation((BoundArrayAccess)boundNode); case BoundKind.NameOfOperator: return CreateBoundNameOfOperatorOperation((BoundNameOfOperator)boundNode); case BoundKind.ThrowExpression: return CreateBoundThrowExpressionOperation((BoundThrowExpression)boundNode); case BoundKind.AddressOfOperator: return CreateBoundAddressOfOperatorOperation((BoundAddressOfOperator)boundNode); case BoundKind.ImplicitReceiver: return CreateBoundImplicitReceiverOperation((BoundImplicitReceiver)boundNode); case BoundKind.ConditionalAccess: return CreateBoundConditionalAccessOperation((BoundConditionalAccess)boundNode); case BoundKind.ConditionalReceiver: return CreateBoundConditionalReceiverOperation((BoundConditionalReceiver)boundNode); case BoundKind.FieldEqualsValue: return CreateBoundFieldEqualsValueOperation((BoundFieldEqualsValue)boundNode); case BoundKind.PropertyEqualsValue: return CreateBoundPropertyEqualsValueOperation((BoundPropertyEqualsValue)boundNode); case BoundKind.ParameterEqualsValue: return CreateBoundParameterEqualsValueOperation((BoundParameterEqualsValue)boundNode); case BoundKind.Block: return CreateBoundBlockOperation((BoundBlock)boundNode); case BoundKind.ContinueStatement: return CreateBoundContinueStatementOperation((BoundContinueStatement)boundNode); case BoundKind.BreakStatement: return CreateBoundBreakStatementOperation((BoundBreakStatement)boundNode); case BoundKind.YieldBreakStatement: return CreateBoundYieldBreakStatementOperation((BoundYieldBreakStatement)boundNode); case BoundKind.GotoStatement: return CreateBoundGotoStatementOperation((BoundGotoStatement)boundNode); case BoundKind.NoOpStatement: return CreateBoundNoOpStatementOperation((BoundNoOpStatement)boundNode); case BoundKind.IfStatement: return CreateBoundIfStatementOperation((BoundIfStatement)boundNode); case BoundKind.WhileStatement: return CreateBoundWhileStatementOperation((BoundWhileStatement)boundNode); case BoundKind.DoStatement: return CreateBoundDoStatementOperation((BoundDoStatement)boundNode); case BoundKind.ForStatement: return CreateBoundForStatementOperation((BoundForStatement)boundNode); case BoundKind.ForEachStatement: return CreateBoundForEachStatementOperation((BoundForEachStatement)boundNode); case BoundKind.TryStatement: return CreateBoundTryStatementOperation((BoundTryStatement)boundNode); case BoundKind.CatchBlock: return CreateBoundCatchBlockOperation((BoundCatchBlock)boundNode); case BoundKind.FixedStatement: return CreateBoundFixedStatementOperation((BoundFixedStatement)boundNode); case BoundKind.UsingStatement: return CreateBoundUsingStatementOperation((BoundUsingStatement)boundNode); case BoundKind.ThrowStatement: return CreateBoundThrowStatementOperation((BoundThrowStatement)boundNode); case BoundKind.ReturnStatement: return CreateBoundReturnStatementOperation((BoundReturnStatement)boundNode); case BoundKind.YieldReturnStatement: return CreateBoundYieldReturnStatementOperation((BoundYieldReturnStatement)boundNode); case BoundKind.LockStatement: return CreateBoundLockStatementOperation((BoundLockStatement)boundNode); case BoundKind.BadStatement: return CreateBoundBadStatementOperation((BoundBadStatement)boundNode); case BoundKind.LocalDeclaration: return CreateBoundLocalDeclarationOperation((BoundLocalDeclaration)boundNode); case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: return CreateBoundMultipleLocalDeclarationsBaseOperation((BoundMultipleLocalDeclarationsBase)boundNode); case BoundKind.LabelStatement: return CreateBoundLabelStatementOperation((BoundLabelStatement)boundNode); case BoundKind.LabeledStatement: return CreateBoundLabeledStatementOperation((BoundLabeledStatement)boundNode); case BoundKind.ExpressionStatement: return CreateBoundExpressionStatementOperation((BoundExpressionStatement)boundNode); case BoundKind.TupleLiteral: case BoundKind.ConvertedTupleLiteral: return CreateBoundTupleOperation((BoundTupleExpression)boundNode); case BoundKind.UnconvertedInterpolatedString: throw ExceptionUtilities.Unreachable; case BoundKind.InterpolatedString: return CreateBoundInterpolatedStringExpressionOperation((BoundInterpolatedString)boundNode); case BoundKind.StringInsert: return CreateBoundInterpolationOperation((BoundStringInsert)boundNode); case BoundKind.LocalFunctionStatement: return CreateBoundLocalFunctionStatementOperation((BoundLocalFunctionStatement)boundNode); case BoundKind.AnonymousObjectCreationExpression: return CreateBoundAnonymousObjectCreationExpressionOperation((BoundAnonymousObjectCreationExpression)boundNode); case BoundKind.AnonymousPropertyDeclaration: throw ExceptionUtilities.Unreachable; case BoundKind.ConstantPattern: return CreateBoundConstantPatternOperation((BoundConstantPattern)boundNode); case BoundKind.DeclarationPattern: return CreateBoundDeclarationPatternOperation((BoundDeclarationPattern)boundNode); case BoundKind.RecursivePattern: return CreateBoundRecursivePatternOperation((BoundRecursivePattern)boundNode); case BoundKind.ITuplePattern: return CreateBoundRecursivePatternOperation((BoundITuplePattern)boundNode); case BoundKind.DiscardPattern: return CreateBoundDiscardPatternOperation((BoundDiscardPattern)boundNode); case BoundKind.BinaryPattern: return CreateBoundBinaryPatternOperation((BoundBinaryPattern)boundNode); case BoundKind.NegatedPattern: return CreateBoundNegatedPatternOperation((BoundNegatedPattern)boundNode); case BoundKind.RelationalPattern: return CreateBoundRelationalPatternOperation((BoundRelationalPattern)boundNode); case BoundKind.TypePattern: return CreateBoundTypePatternOperation((BoundTypePattern)boundNode); case BoundKind.SwitchStatement: return CreateBoundSwitchStatementOperation((BoundSwitchStatement)boundNode); case BoundKind.SwitchLabel: return CreateBoundSwitchLabelOperation((BoundSwitchLabel)boundNode); case BoundKind.IsPatternExpression: return CreateBoundIsPatternExpressionOperation((BoundIsPatternExpression)boundNode); case BoundKind.QueryClause: return CreateBoundQueryClauseOperation((BoundQueryClause)boundNode); case BoundKind.DelegateCreationExpression: return CreateBoundDelegateCreationExpressionOperation((BoundDelegateCreationExpression)boundNode); case BoundKind.RangeVariable: return CreateBoundRangeVariableOperation((BoundRangeVariable)boundNode); case BoundKind.ConstructorMethodBody: return CreateConstructorBodyOperation((BoundConstructorMethodBody)boundNode); case BoundKind.NonConstructorMethodBody: return CreateMethodBodyOperation((BoundNonConstructorMethodBody)boundNode); case BoundKind.DiscardExpression: return CreateBoundDiscardExpressionOperation((BoundDiscardExpression)boundNode); case BoundKind.NullCoalescingAssignmentOperator: return CreateBoundNullCoalescingAssignmentOperatorOperation((BoundNullCoalescingAssignmentOperator)boundNode); case BoundKind.FromEndIndexExpression: return CreateFromEndIndexExpressionOperation((BoundFromEndIndexExpression)boundNode); case BoundKind.RangeExpression: return CreateRangeExpressionOperation((BoundRangeExpression)boundNode); case BoundKind.SwitchSection: return CreateBoundSwitchSectionOperation((BoundSwitchSection)boundNode); case BoundKind.UnconvertedConditionalOperator: throw ExceptionUtilities.Unreachable; case BoundKind.UnconvertedSwitchExpression: throw ExceptionUtilities.Unreachable; case BoundKind.ConvertedSwitchExpression: return CreateBoundSwitchExpressionOperation((BoundConvertedSwitchExpression)boundNode); case BoundKind.SwitchExpressionArm: return CreateBoundSwitchExpressionArmOperation((BoundSwitchExpressionArm)boundNode); case BoundKind.ObjectOrCollectionValuePlaceholder: return CreateCollectionValuePlaceholderOperation((BoundObjectOrCollectionValuePlaceholder)boundNode); case BoundKind.FunctionPointerInvocation: return CreateBoundFunctionPointerInvocationOperation((BoundFunctionPointerInvocation)boundNode); case BoundKind.UnconvertedAddressOfOperator: return CreateBoundUnconvertedAddressOfOperatorOperation((BoundUnconvertedAddressOfOperator)boundNode); case BoundKind.Attribute: case BoundKind.ArgList: case BoundKind.ArgListOperator: case BoundKind.ConvertedStackAllocExpression: case BoundKind.FixedLocalCollectionInitializer: case BoundKind.GlobalStatementInitializer: case BoundKind.HostObjectMemberReference: case BoundKind.MakeRefOperator: case BoundKind.MethodGroup: case BoundKind.NamespaceExpression: case BoundKind.PointerElementAccess: case BoundKind.PointerIndirectionOperator: case BoundKind.PreviousSubmissionReference: case BoundKind.RefTypeOperator: case BoundKind.RefValueOperator: case BoundKind.Sequence: case BoundKind.StackAllocArrayCreation: case BoundKind.TypeExpression: case BoundKind.TypeOrValueExpression: case BoundKind.IndexOrRangePatternIndexerAccess: ConstantValue? constantValue = (boundNode as BoundExpression)?.ConstantValue; bool isImplicit = boundNode.WasCompilerGenerated; if (!isImplicit) { switch (boundNode.Kind) { case BoundKind.FixedLocalCollectionInitializer: isImplicit = true; break; } } ImmutableArray<IOperation> children = GetIOperationChildren(boundNode); return new NoneOperation(children, _semanticModel, boundNode.Syntax, type: null, constantValue, isImplicit: isImplicit); default: // If you're hitting this because the IOperation test hook has failed, see // <roslyn-root>/docs/Compilers/IOperation Test Hook.md for instructions on how to fix. throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } public ImmutableArray<TOperation> CreateFromArray<TBoundNode, TOperation>(ImmutableArray<TBoundNode> boundNodes) where TBoundNode : BoundNode where TOperation : class, IOperation { if (boundNodes.IsDefault) { return ImmutableArray<TOperation>.Empty; } var builder = ArrayBuilder<TOperation>.GetInstance(boundNodes.Length); foreach (var node in boundNodes) { builder.AddIfNotNull((TOperation)Create(node)); } return builder.ToImmutableAndFree(); } private IMethodBodyOperation CreateMethodBodyOperation(BoundNonConstructorMethodBody boundNode) { return new MethodBodyOperation( (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } private IConstructorBodyOperation CreateConstructorBodyOperation(BoundConstructorMethodBody boundNode) { return new ConstructorBodyOperation( boundNode.Locals.GetPublicSymbols(), Create(boundNode.Initializer), (IBlockOperation?)Create(boundNode.BlockBody), (IBlockOperation?)Create(boundNode.ExpressionBody), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal ImmutableArray<IOperation> GetIOperationChildren(IBoundNodeWithIOperationChildren boundNodeWithChildren) { var children = boundNodeWithChildren.Children; if (children.IsDefaultOrEmpty) { return ImmutableArray<IOperation>.Empty; } var builder = ArrayBuilder<IOperation>.GetInstance(children.Length); foreach (BoundNode? childNode in children) { if (childNode == null) { continue; } IOperation operation = Create(childNode); builder.Add(operation); } return builder.ToImmutableAndFree(); } internal ImmutableArray<IVariableDeclaratorOperation> CreateVariableDeclarator(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { return ImmutableArray.Create(CreateVariableDeclaratorInternal((BoundLocalDeclaration)declaration, (declarationSyntax as VariableDeclarationSyntax)?.Variables[0] ?? declarationSyntax)); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var multipleDeclaration = (BoundMultipleLocalDeclarationsBase)declaration; var builder = ArrayBuilder<IVariableDeclaratorOperation>.GetInstance(multipleDeclaration.LocalDeclarations.Length); foreach (var decl in multipleDeclaration.LocalDeclarations) { builder.Add((IVariableDeclaratorOperation)CreateVariableDeclaratorInternal(decl, decl.Syntax)); } return builder.ToImmutableAndFree(); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } private IPlaceholderOperation CreateBoundDeconstructValuePlaceholderOperation(BoundDeconstructValuePlaceholder boundDeconstructValuePlaceholder) { SyntaxNode syntax = boundDeconstructValuePlaceholder.Syntax; ITypeSymbol? type = boundDeconstructValuePlaceholder.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructValuePlaceholder.WasCompilerGenerated; return new PlaceholderOperation(PlaceholderKind.Unspecified, _semanticModel, syntax, type, isImplicit); } private IDeconstructionAssignmentOperation CreateBoundDeconstructionAssignmentOperator(BoundDeconstructionAssignmentOperator boundDeconstructionAssignmentOperator) { IOperation target = Create(boundDeconstructionAssignmentOperator.Left); // Skip the synthetic deconstruction conversion wrapping the right operand. This is a compiler-generated conversion that we don't want to reflect // in the public API because it's an implementation detail. IOperation value = Create(boundDeconstructionAssignmentOperator.Right.Operand); SyntaxNode syntax = boundDeconstructionAssignmentOperator.Syntax; ITypeSymbol? type = boundDeconstructionAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundDeconstructionAssignmentOperator.WasCompilerGenerated; return new DeconstructionAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCallOperation(BoundCall boundCall) { MethodSymbol targetMethod = boundCall.Method; SyntaxNode syntax = boundCall.Syntax; ITypeSymbol? type = boundCall.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCall.ConstantValue; bool isImplicit = boundCall.WasCompilerGenerated; if (!boundCall.OriginalMethodsOpt.IsDefault || IsMethodInvalid(boundCall.ResultKind, targetMethod)) { ImmutableArray<IOperation> children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCall).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(targetMethod, boundCall.ReceiverOpt); IOperation? receiver = CreateReceiverOperation(boundCall.ReceiverOpt, targetMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCall); return new InvocationOperation(targetMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundFunctionPointerInvocationOperation(BoundFunctionPointerInvocation boundFunctionPointerInvocation) { ITypeSymbol? type = boundFunctionPointerInvocation.GetPublicTypeSymbol(); SyntaxNode syntax = boundFunctionPointerInvocation.Syntax; bool isImplicit = boundFunctionPointerInvocation.WasCompilerGenerated; ImmutableArray<IOperation> children; if (boundFunctionPointerInvocation.ResultKind != LookupResultKind.Viable) { children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundFunctionPointerInvocation).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } children = GetIOperationChildren(boundFunctionPointerInvocation); return new NoneOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IOperation CreateBoundUnconvertedAddressOfOperatorOperation(BoundUnconvertedAddressOfOperator boundUnconvertedAddressOf) { return new AddressOfOperation( Create(boundUnconvertedAddressOf.Operand), _semanticModel, boundUnconvertedAddressOf.Syntax, boundUnconvertedAddressOf.GetPublicTypeSymbol(), boundUnconvertedAddressOf.WasCompilerGenerated); } internal ImmutableArray<IOperation> CreateIgnoredDimensions(BoundNode declaration, SyntaxNode declarationSyntax) { switch (declaration.Kind) { case BoundKind.LocalDeclaration: { BoundTypeExpression? declaredTypeOpt = ((BoundLocalDeclaration)declaration).DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); return CreateFromArray<BoundExpression, IOperation>(declaredTypeOpt.BoundDimensionsOpt); } case BoundKind.MultipleLocalDeclarations: case BoundKind.UsingLocalDeclarations: { var declarations = ((BoundMultipleLocalDeclarationsBase)declaration).LocalDeclarations; ImmutableArray<BoundExpression> dimensions; if (declarations.Length > 0) { BoundTypeExpression? declaredTypeOpt = declarations[0].DeclaredTypeOpt; Debug.Assert(declaredTypeOpt != null); dimensions = declaredTypeOpt.BoundDimensionsOpt; } else { dimensions = ImmutableArray<BoundExpression>.Empty; } return CreateFromArray<BoundExpression, IOperation>(dimensions); } default: throw ExceptionUtilities.UnexpectedValue(declaration.Kind); } } internal IOperation CreateBoundLocalOperation(BoundLocal boundLocal, bool createDeclaration = true) { ILocalSymbol local = boundLocal.LocalSymbol.GetPublicSymbol(); bool isDeclaration = boundLocal.DeclarationKind != BoundLocalDeclarationKind.None; SyntaxNode syntax = boundLocal.Syntax; ITypeSymbol? type = boundLocal.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLocal.ConstantValue; bool isImplicit = boundLocal.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation localReference = CreateBoundLocalOperation(boundLocal, createDeclaration: false); return new DeclarationExpressionOperation(localReference, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } return new LocalReferenceOperation(local, isDeclaration, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation CreateBoundFieldAccessOperation(BoundFieldAccess boundFieldAccess, bool createDeclaration = true) { IFieldSymbol field = boundFieldAccess.FieldSymbol.GetPublicSymbol(); bool isDeclaration = boundFieldAccess.IsDeclaration; SyntaxNode syntax = boundFieldAccess.Syntax; ITypeSymbol? type = boundFieldAccess.GetPublicTypeSymbol(); ConstantValue? constantValue = boundFieldAccess.ConstantValue; bool isImplicit = boundFieldAccess.WasCompilerGenerated; if (isDeclaration && syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { IOperation fieldAccess = CreateBoundFieldAccessOperation(boundFieldAccess, createDeclaration: false); return new DeclarationExpressionOperation(fieldAccess, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } IOperation? instance = CreateReceiverOperation(boundFieldAccess.ReceiverOpt, boundFieldAccess.FieldSymbol); return new FieldReferenceOperation(field, isDeclaration, instance, _semanticModel, syntax, type, constantValue, isImplicit); } internal IOperation? CreateBoundPropertyReferenceInstance(BoundNode boundNode) { switch (boundNode) { case BoundPropertyAccess boundPropertyAccess: return CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); case BoundObjectInitializerMember boundObjectInitializerMember: return boundObjectInitializerMember.MemberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); case BoundIndexerAccess boundIndexerAccess: return CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); default: throw ExceptionUtilities.UnexpectedValue(boundNode.Kind); } } private IPropertyReferenceOperation CreateBoundPropertyAccessOperation(BoundPropertyAccess boundPropertyAccess) { IOperation? instance = CreateReceiverOperation(boundPropertyAccess.ReceiverOpt, boundPropertyAccess.PropertySymbol); var arguments = ImmutableArray<IArgumentOperation>.Empty; IPropertySymbol property = boundPropertyAccess.PropertySymbol.GetPublicSymbol(); SyntaxNode syntax = boundPropertyAccess.Syntax; ITypeSymbol? type = boundPropertyAccess.GetPublicTypeSymbol(); bool isImplicit = boundPropertyAccess.WasCompilerGenerated; return new PropertyReferenceOperation(property, arguments, instance, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundIndexerAccessOperation(BoundIndexerAccess boundIndexerAccess) { PropertySymbol property = boundIndexerAccess.Indexer; SyntaxNode syntax = boundIndexerAccess.Syntax; ITypeSymbol? type = boundIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundIndexerAccess.WasCompilerGenerated; if (!boundIndexerAccess.OriginalIndexersOpt.IsDefault || boundIndexerAccess.ResultKind == LookupResultKind.OverloadResolutionFailure) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundIndexerAccess).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundIndexerAccess, isObjectOrCollectionInitializer: false); IOperation? instance = CreateReceiverOperation(boundIndexerAccess.ReceiverOpt, boundIndexerAccess.ExpressionSymbol); return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, instance, _semanticModel, syntax, type, isImplicit); } private IEventReferenceOperation CreateBoundEventAccessOperation(BoundEventAccess boundEventAccess) { IEventSymbol @event = boundEventAccess.EventSymbol.GetPublicSymbol(); IOperation? instance = CreateReceiverOperation(boundEventAccess.ReceiverOpt, boundEventAccess.EventSymbol); SyntaxNode syntax = boundEventAccess.Syntax; ITypeSymbol? type = boundEventAccess.GetPublicTypeSymbol(); bool isImplicit = boundEventAccess.WasCompilerGenerated; return new EventReferenceOperation(@event, instance, _semanticModel, syntax, type, isImplicit); } private IEventAssignmentOperation CreateBoundEventAssignmentOperatorOperation(BoundEventAssignmentOperator boundEventAssignmentOperator) { IOperation eventReference = CreateBoundEventAccessOperation(boundEventAssignmentOperator); IOperation handlerValue = Create(boundEventAssignmentOperator.Argument); SyntaxNode syntax = boundEventAssignmentOperator.Syntax; bool adds = boundEventAssignmentOperator.IsAddition; ITypeSymbol? type = boundEventAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundEventAssignmentOperator.WasCompilerGenerated; return new EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, syntax, type, isImplicit); } private IParameterReferenceOperation CreateBoundParameterOperation(BoundParameter boundParameter) { IParameterSymbol parameter = boundParameter.ParameterSymbol.GetPublicSymbol(); SyntaxNode syntax = boundParameter.Syntax; ITypeSymbol? type = boundParameter.GetPublicTypeSymbol(); bool isImplicit = boundParameter.WasCompilerGenerated; return new ParameterReferenceOperation(parameter, _semanticModel, syntax, type, isImplicit); } internal ILiteralOperation CreateBoundLiteralOperation(BoundLiteral boundLiteral, bool @implicit = false) { SyntaxNode syntax = boundLiteral.Syntax; ITypeSymbol? type = boundLiteral.GetPublicTypeSymbol(); ConstantValue? constantValue = boundLiteral.ConstantValue; bool isImplicit = boundLiteral.WasCompilerGenerated || @implicit; return new LiteralOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IAnonymousObjectCreationOperation CreateBoundAnonymousObjectCreationExpressionOperation(BoundAnonymousObjectCreationExpression boundAnonymousObjectCreationExpression) { SyntaxNode syntax = boundAnonymousObjectCreationExpression.Syntax; ITypeSymbol? type = boundAnonymousObjectCreationExpression.GetPublicTypeSymbol(); Debug.Assert(type is not null); bool isImplicit = boundAnonymousObjectCreationExpression.WasCompilerGenerated; ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers(boundAnonymousObjectCreationExpression.Arguments, boundAnonymousObjectCreationExpression.Declarations, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectCreationExpressionOperation(BoundObjectCreationExpression boundObjectCreationExpression) { MethodSymbol constructor = boundObjectCreationExpression.Constructor; SyntaxNode syntax = boundObjectCreationExpression.Syntax; ITypeSymbol? type = boundObjectCreationExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundObjectCreationExpression.ConstantValue; bool isImplicit = boundObjectCreationExpression.WasCompilerGenerated; if (boundObjectCreationExpression.ResultKind == LookupResultKind.OverloadResolutionFailure || constructor == null || constructor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectCreationExpression).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } else if (boundObjectCreationExpression.Type.IsAnonymousType) { // Workaround for https://github.com/dotnet/roslyn/issues/28157 Debug.Assert(isImplicit); Debug.Assert(type is not null); ImmutableArray<IOperation> initializers = GetAnonymousObjectCreationInitializers( boundObjectCreationExpression.Arguments, declarations: ImmutableArray<BoundAnonymousPropertyDeclaration>.Empty, syntax, type, isImplicit); return new AnonymousObjectCreationOperation(initializers, _semanticModel, syntax, type, isImplicit); } ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundObjectCreationExpression); IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundObjectCreationExpression.InitializerExpressionOpt); return new ObjectCreationOperation(constructor.GetPublicSymbol(), initializer, arguments, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundWithExpressionOperation(BoundWithExpression boundWithExpression) { IOperation operand = Create(boundWithExpression.Receiver); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundWithExpression.InitializerExpression); MethodSymbol? constructor = boundWithExpression.CloneMethod; SyntaxNode syntax = boundWithExpression.Syntax; ITypeSymbol? type = boundWithExpression.GetPublicTypeSymbol(); bool isImplicit = boundWithExpression.WasCompilerGenerated; return new WithOperation(operand, constructor.GetPublicSymbol(), initializer, _semanticModel, syntax, type, isImplicit); } private IDynamicObjectCreationOperation CreateBoundDynamicObjectCreationExpressionOperation(BoundDynamicObjectCreationExpression boundDynamicObjectCreationExpression) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundDynamicObjectCreationExpression.InitializerExpressionOpt); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicObjectCreationExpression.Arguments); ImmutableArray<string> argumentNames = boundDynamicObjectCreationExpression.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicObjectCreationExpression.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicObjectCreationExpression.Syntax; ITypeSymbol? type = boundDynamicObjectCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectCreationExpression.WasCompilerGenerated; return new DynamicObjectCreationOperation(initializer, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicInvocationExpressionReceiver(BoundNode receiver) { switch (receiver) { case BoundObjectOrCollectionValuePlaceholder implicitReceiver: return CreateBoundDynamicMemberAccessOperation(implicitReceiver, typeArgumentsOpt: ImmutableArray<TypeSymbol>.Empty, memberName: "Add", implicitReceiver.Syntax, type: null, isImplicit: true); case BoundMethodGroup methodGroup: return CreateBoundDynamicMemberAccessOperation(methodGroup.ReceiverOpt, TypeMap.AsTypeSymbols(methodGroup.TypeArgumentsOpt), methodGroup.Name, methodGroup.Syntax, methodGroup.GetPublicTypeSymbol(), methodGroup.WasCompilerGenerated); default: return Create(receiver); } } private IDynamicInvocationOperation CreateBoundDynamicInvocationExpressionOperation(BoundDynamicInvocation boundDynamicInvocation) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundDynamicInvocation.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundDynamicInvocation.Arguments); ImmutableArray<string> argumentNames = boundDynamicInvocation.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicInvocation.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicInvocation.Syntax; ITypeSymbol? type = boundDynamicInvocation.GetPublicTypeSymbol(); bool isImplicit = boundDynamicInvocation.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } internal IOperation CreateBoundDynamicIndexerAccessExpressionReceiver(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicIndexerAccess: return Create(boundDynamicIndexerAccess.Receiver); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } internal ImmutableArray<IOperation> CreateBoundDynamicIndexerAccessArguments(BoundExpression indexer) { switch (indexer) { case BoundDynamicIndexerAccess boundDynamicAccess: return CreateFromArray<BoundExpression, IOperation>(boundDynamicAccess.Arguments); case BoundObjectInitializerMember boundObjectInitializerMember: return CreateFromArray<BoundExpression, IOperation>(boundObjectInitializerMember.Arguments); default: throw ExceptionUtilities.UnexpectedValue(indexer.Kind); } } private IDynamicIndexerAccessOperation CreateBoundDynamicIndexerAccessExpressionOperation(BoundDynamicIndexerAccess boundDynamicIndexerAccess) { IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundDynamicIndexerAccess); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundDynamicIndexerAccess); ImmutableArray<string> argumentNames = boundDynamicIndexerAccess.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundDynamicIndexerAccess.ArgumentRefKindsOpt.NullToEmpty(); SyntaxNode syntax = boundDynamicIndexerAccess.Syntax; ITypeSymbol? type = boundDynamicIndexerAccess.GetPublicTypeSymbol(); bool isImplicit = boundDynamicIndexerAccess.WasCompilerGenerated; return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundObjectInitializerExpressionOperation(BoundObjectInitializerExpression boundObjectInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundObjectInitializerExpression)); SyntaxNode syntax = boundObjectInitializerExpression.Syntax; ITypeSymbol? type = boundObjectInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IObjectOrCollectionInitializerOperation CreateBoundCollectionInitializerExpressionOperation(BoundCollectionInitializerExpression boundCollectionInitializerExpression) { ImmutableArray<IOperation> initializers = CreateFromArray<BoundExpression, IOperation>(BoundObjectCreationExpression.GetChildInitializers(boundCollectionInitializerExpression)); SyntaxNode syntax = boundCollectionInitializerExpression.Syntax; ITypeSymbol? type = boundCollectionInitializerExpression.GetPublicTypeSymbol(); bool isImplicit = boundCollectionInitializerExpression.WasCompilerGenerated; return new ObjectOrCollectionInitializerOperation(initializers, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundObjectInitializerMemberOperation(BoundObjectInitializerMember boundObjectInitializerMember, bool isObjectOrCollectionInitializer = false) { Symbol? memberSymbol = boundObjectInitializerMember.MemberSymbol; SyntaxNode syntax = boundObjectInitializerMember.Syntax; ITypeSymbol? type = boundObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundObjectInitializerMember.WasCompilerGenerated; if ((object?)memberSymbol == null) { Debug.Assert(boundObjectInitializerMember.Type.IsDynamic()); IOperation operation = CreateBoundDynamicIndexerAccessExpressionReceiver(boundObjectInitializerMember); ImmutableArray<IOperation> arguments = CreateBoundDynamicIndexerAccessArguments(boundObjectInitializerMember); ImmutableArray<string> argumentNames = boundObjectInitializerMember.ArgumentNamesOpt.NullToEmpty(); ImmutableArray<RefKind> argumentRefKinds = boundObjectInitializerMember.ArgumentRefKindsOpt.NullToEmpty(); return new DynamicIndexerAccessOperation(operation, arguments, argumentNames, argumentRefKinds, _semanticModel, syntax, type, isImplicit); } switch (memberSymbol.Kind) { case SymbolKind.Field: var field = (FieldSymbol)memberSymbol; bool isDeclaration = false; return new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration, createReceiver(), _semanticModel, syntax, type, constantValue: null, isImplicit); case SymbolKind.Event: var eventSymbol = (EventSymbol)memberSymbol; return new EventReferenceOperation(eventSymbol.GetPublicSymbol(), createReceiver(), _semanticModel, syntax, type, isImplicit); case SymbolKind.Property: var property = (PropertySymbol)memberSymbol; ImmutableArray<IArgumentOperation> arguments; if (!boundObjectInitializerMember.Arguments.IsEmpty) { // In nested member initializers, the property is not actually set. Instead, it is retrieved for a series of Add method calls or nested property setter calls, // so we need to use the getter for this property MethodSymbol? accessor = isObjectOrCollectionInitializer ? property.GetOwnOrInheritedGetMethod() : property.GetOwnOrInheritedSetMethod(); if (accessor == null || boundObjectInitializerMember.ResultKind == LookupResultKind.OverloadResolutionFailure || accessor.OriginalDefinition is ErrorMethodSymbol) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundObjectInitializerMember).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } arguments = DeriveArguments(boundObjectInitializerMember, isObjectOrCollectionInitializer); } else { arguments = ImmutableArray<IArgumentOperation>.Empty; } return new PropertyReferenceOperation(property.GetPublicSymbol(), arguments, createReceiver(), _semanticModel, syntax, type, isImplicit); default: throw ExceptionUtilities.Unreachable; } IOperation? createReceiver() => memberSymbol?.IsStatic == true ? null : CreateImplicitReceiver(boundObjectInitializerMember.Syntax, boundObjectInitializerMember.ReceiverType); } private IOperation CreateBoundDynamicObjectInitializerMemberOperation(BoundDynamicObjectInitializerMember boundDynamicObjectInitializerMember) { IOperation instanceReceiver = CreateImplicitReceiver(boundDynamicObjectInitializerMember.Syntax, boundDynamicObjectInitializerMember.ReceiverType); string memberName = boundDynamicObjectInitializerMember.MemberName; ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; ITypeSymbol containingType = boundDynamicObjectInitializerMember.ReceiverType.GetPublicSymbol(); SyntaxNode syntax = boundDynamicObjectInitializerMember.Syntax; ITypeSymbol? type = boundDynamicObjectInitializerMember.GetPublicTypeSymbol(); bool isImplicit = boundDynamicObjectInitializerMember.WasCompilerGenerated; return new DynamicMemberReferenceOperation(instanceReceiver, memberName, typeArguments, containingType, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundCollectionElementInitializerOperation(BoundCollectionElementInitializer boundCollectionElementInitializer) { MethodSymbol addMethod = boundCollectionElementInitializer.AddMethod; IOperation? receiver = CreateReceiverOperation(boundCollectionElementInitializer.ImplicitReceiverOpt, addMethod); ImmutableArray<IArgumentOperation> arguments = DeriveArguments(boundCollectionElementInitializer); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); ConstantValue? constantValue = boundCollectionElementInitializer.ConstantValue; bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; if (IsMethodInvalid(boundCollectionElementInitializer.ResultKind, addMethod)) { var children = CreateFromArray<BoundNode, IOperation>(((IBoundInvalidNode)boundCollectionElementInitializer).InvalidNodeChildren); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue, isImplicit); } bool isVirtual = IsCallVirtual(addMethod, boundCollectionElementInitializer.ImplicitReceiverOpt); return new InvocationOperation(addMethod.GetPublicSymbol(), receiver, isVirtual, arguments, _semanticModel, syntax, type, isImplicit); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation(BoundDynamicMemberAccess boundDynamicMemberAccess) { return CreateBoundDynamicMemberAccessOperation(boundDynamicMemberAccess.Receiver, TypeMap.AsTypeSymbols(boundDynamicMemberAccess.TypeArgumentsOpt), boundDynamicMemberAccess.Name, boundDynamicMemberAccess.Syntax, boundDynamicMemberAccess.GetPublicTypeSymbol(), boundDynamicMemberAccess.WasCompilerGenerated); } private IDynamicMemberReferenceOperation CreateBoundDynamicMemberAccessOperation( BoundExpression? receiver, ImmutableArray<TypeSymbol> typeArgumentsOpt, string memberName, SyntaxNode syntaxNode, ITypeSymbol? type, bool isImplicit) { ITypeSymbol? containingType = null; if (receiver?.Kind == BoundKind.TypeExpression) { containingType = receiver.GetPublicTypeSymbol(); receiver = null; } ImmutableArray<ITypeSymbol> typeArguments = ImmutableArray<ITypeSymbol>.Empty; if (!typeArgumentsOpt.IsDefault) { typeArguments = typeArgumentsOpt.GetPublicSymbols(); } IOperation? instance = Create(receiver); return new DynamicMemberReferenceOperation(instance, memberName, typeArguments, containingType, _semanticModel, syntaxNode, type, isImplicit); } private IDynamicInvocationOperation CreateBoundDynamicCollectionElementInitializerOperation(BoundDynamicCollectionElementInitializer boundCollectionElementInitializer) { IOperation operation = CreateBoundDynamicInvocationExpressionReceiver(boundCollectionElementInitializer.Expression); ImmutableArray<IOperation> arguments = CreateFromArray<BoundExpression, IOperation>(boundCollectionElementInitializer.Arguments); SyntaxNode syntax = boundCollectionElementInitializer.Syntax; ITypeSymbol? type = boundCollectionElementInitializer.GetPublicTypeSymbol(); bool isImplicit = boundCollectionElementInitializer.WasCompilerGenerated; return new DynamicInvocationOperation(operation, arguments, argumentNames: ImmutableArray<string>.Empty, argumentRefKinds: ImmutableArray<RefKind>.Empty, _semanticModel, syntax, type, isImplicit); } private IOperation CreateUnboundLambdaOperation(UnboundLambda unboundLambda) { // We want to ensure that we never see the UnboundLambda node, and that we don't end up having two different IOperation // nodes for the lambda expression. So, we ask the semantic model for the IOperation node for the unbound lambda syntax. // We are counting on the fact that will do the error recovery and actually create the BoundLambda node appropriate for // this syntax node. BoundLambda boundLambda = unboundLambda.BindForErrorRecovery(); return Create(boundLambda); } private IAnonymousFunctionOperation CreateBoundLambdaOperation(BoundLambda boundLambda) { IMethodSymbol symbol = boundLambda.Symbol.GetPublicSymbol(); IBlockOperation body = (IBlockOperation)Create(boundLambda.Body); SyntaxNode syntax = boundLambda.Syntax; bool isImplicit = boundLambda.WasCompilerGenerated; return new AnonymousFunctionOperation(symbol, body, _semanticModel, syntax, isImplicit); } private ILocalFunctionOperation CreateBoundLocalFunctionStatementOperation(BoundLocalFunctionStatement boundLocalFunctionStatement) { IBlockOperation? body = (IBlockOperation?)Create(boundLocalFunctionStatement.Body); IBlockOperation? ignoredBody = boundLocalFunctionStatement is { BlockBody: { }, ExpressionBody: { } exprBody } ? (IBlockOperation?)Create(exprBody) : null; IMethodSymbol symbol = boundLocalFunctionStatement.Symbol.GetPublicSymbol(); SyntaxNode syntax = boundLocalFunctionStatement.Syntax; bool isImplicit = boundLocalFunctionStatement.WasCompilerGenerated; return new LocalFunctionOperation(symbol, body, ignoredBody, _semanticModel, syntax, isImplicit); } private IOperation CreateBoundConversionOperation(BoundConversion boundConversion, bool forceOperandImplicitLiteral = false) { Debug.Assert(!forceOperandImplicitLiteral || boundConversion.Operand is BoundLiteral); bool isImplicit = boundConversion.WasCompilerGenerated || !boundConversion.ExplicitCastInCode || forceOperandImplicitLiteral; BoundExpression boundOperand = boundConversion.Operand; if (boundConversion.ConversionKind == ConversionKind.InterpolatedStringHandler) { // https://github.com/dotnet/roslyn/issues/54505 Support interpolation handlers in conversions Debug.Assert(!forceOperandImplicitLiteral); Debug.Assert(boundOperand is BoundInterpolatedString { InterpolationData: not null } or BoundBinaryOperator { InterpolatedStringHandlerData: not null }); var interpolatedString = Create(boundOperand); return new NoneOperation(ImmutableArray.Create(interpolatedString), _semanticModel, boundConversion.Syntax, boundConversion.GetPublicTypeSymbol(), boundConversion.ConstantValue, isImplicit); } if (boundConversion.ConversionKind == CSharp.ConversionKind.MethodGroup) { SyntaxNode syntax = boundConversion.Syntax; ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); Debug.Assert(!forceOperandImplicitLiteral); if (boundConversion.Type is FunctionPointerTypeSymbol) { Debug.Assert(boundConversion.SymbolOpt is object); return new AddressOfOperation( CreateBoundMethodGroupSingleMethodOperation((BoundMethodGroup)boundConversion.Operand, boundConversion.SymbolOpt, suppressVirtualCalls: false), _semanticModel, syntax, type, boundConversion.WasCompilerGenerated); } // We don't check HasErrors on the conversion here because if we actually have a MethodGroup conversion, // overload resolution succeeded. The resulting method could be invalid for other reasons, but we don't // hide the resolved method. IOperation target = CreateDelegateTargetOperation(boundConversion); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { SyntaxNode syntax = boundConversion.Syntax; if (syntax.IsMissing) { // If the underlying syntax IsMissing, then that means we're in case where the compiler generated a piece of syntax to fill in for // an error, such as this case: // // int i = ; // // Semantic model has a special case here that we match: if the underlying syntax is missing, don't create a conversion expression, // and instead directly return the operand, which will be a BoundBadExpression. When we generate a node for the BoundBadExpression, // the resulting IOperation will also have a null Type. Debug.Assert(boundOperand.Kind == BoundKind.BadExpression || ((boundOperand as BoundLambda)?.Body.Statements.SingleOrDefault() as BoundReturnStatement)?. ExpressionOpt?.Kind == BoundKind.BadExpression); Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } BoundConversion correctedConversionNode = boundConversion; Conversion conversion = boundConversion.Conversion; if (boundOperand.Syntax == boundConversion.Syntax) { if (boundOperand.Kind == BoundKind.ConvertedTupleLiteral && TypeSymbol.Equals(boundOperand.Type, boundConversion.Type, TypeCompareKind.ConsiderEverything2)) { // Erase this conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion Debug.Assert(!forceOperandImplicitLiteral); return Create(boundOperand); } else { // Make this conversion implicit isImplicit = true; } } if (boundConversion.ExplicitCastInCode && conversion.IsIdentity && boundOperand.Kind == BoundKind.Conversion) { var nestedConversion = (BoundConversion)boundOperand; BoundExpression nestedOperand = nestedConversion.Operand; if (nestedConversion.Syntax == nestedOperand.Syntax && nestedConversion.ExplicitCastInCode && nestedOperand.Kind == BoundKind.ConvertedTupleLiteral && !TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything2)) { // Let's erase the nested conversion, this is an artificial conversion added on top of BoundConvertedTupleLiteral // in Binder.CreateTupleLiteralConversion. // We need to use conversion information from the nested conversion because that is where the real conversion // information is stored. conversion = nestedConversion.Conversion; correctedConversionNode = nestedConversion; } } ITypeSymbol? type = boundConversion.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConversion.ConstantValue; // If this is a lambda or method group conversion to a delegate type, we return a delegate creation instead of a conversion if ((boundOperand.Kind == BoundKind.Lambda || boundOperand.Kind == BoundKind.UnboundLambda || boundOperand.Kind == BoundKind.MethodGroup) && boundConversion.Type.IsDelegateType()) { IOperation target = CreateDelegateTargetOperation(correctedConversionNode); return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } else { bool isTryCast = false; // Checked conversions only matter if the conversion is a Numeric conversion. Don't have true unless the conversion is actually numeric. bool isChecked = conversion.IsNumeric && boundConversion.Checked; IOperation operand = forceOperandImplicitLiteral ? CreateBoundLiteralOperation((BoundLiteral)correctedConversionNode.Operand, @implicit: true) : Create(correctedConversionNode.Operand); return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue, isImplicit); } } } private IConversionOperation CreateBoundAsOperatorOperation(BoundAsOperator boundAsOperator) { IOperation operand = Create(boundAsOperator.Operand); SyntaxNode syntax = boundAsOperator.Syntax; Conversion conversion = boundAsOperator.Conversion; bool isTryCast = true; bool isChecked = false; ITypeSymbol? type = boundAsOperator.GetPublicTypeSymbol(); bool isImplicit = boundAsOperator.WasCompilerGenerated; return new ConversionOperation(operand, conversion, isTryCast, isChecked, _semanticModel, syntax, type, constantValue: null, isImplicit); } private IDelegateCreationOperation CreateBoundDelegateCreationExpressionOperation(BoundDelegateCreationExpression boundDelegateCreationExpression) { IOperation target = CreateDelegateTargetOperation(boundDelegateCreationExpression); SyntaxNode syntax = boundDelegateCreationExpression.Syntax; ITypeSymbol? type = boundDelegateCreationExpression.GetPublicTypeSymbol(); bool isImplicit = boundDelegateCreationExpression.WasCompilerGenerated; return new DelegateCreationOperation(target, _semanticModel, syntax, type, isImplicit); } private IMethodReferenceOperation CreateBoundMethodGroupSingleMethodOperation(BoundMethodGroup boundMethodGroup, MethodSymbol methodSymbol, bool suppressVirtualCalls) { bool isVirtual = (methodSymbol.IsAbstract || methodSymbol.IsOverride || methodSymbol.IsVirtual) && !suppressVirtualCalls; IOperation? instance = CreateReceiverOperation(boundMethodGroup.ReceiverOpt, methodSymbol); SyntaxNode bindingSyntax = boundMethodGroup.Syntax; ITypeSymbol? bindingType = null; bool isImplicit = boundMethodGroup.WasCompilerGenerated; return new MethodReferenceOperation(methodSymbol.GetPublicSymbol(), isVirtual, instance, _semanticModel, bindingSyntax, bindingType, boundMethodGroup.WasCompilerGenerated); } private IIsTypeOperation CreateBoundIsOperatorOperation(BoundIsOperator boundIsOperator) { IOperation value = Create(boundIsOperator.Operand); ITypeSymbol? typeOperand = boundIsOperator.TargetType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundIsOperator.Syntax; ITypeSymbol? type = boundIsOperator.GetPublicTypeSymbol(); bool isNegated = false; bool isImplicit = boundIsOperator.WasCompilerGenerated; return new IsTypeOperation(value, typeOperand, isNegated, _semanticModel, syntax, type, isImplicit); } private ISizeOfOperation CreateBoundSizeOfOperatorOperation(BoundSizeOfOperator boundSizeOfOperator) { ITypeSymbol? typeOperand = boundSizeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundSizeOfOperator.Syntax; ITypeSymbol? type = boundSizeOfOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundSizeOfOperator.ConstantValue; bool isImplicit = boundSizeOfOperator.WasCompilerGenerated; return new SizeOfOperation(typeOperand, _semanticModel, syntax, type, constantValue, isImplicit); } private ITypeOfOperation CreateBoundTypeOfOperatorOperation(BoundTypeOfOperator boundTypeOfOperator) { ITypeSymbol? typeOperand = boundTypeOfOperator.SourceType.GetPublicTypeSymbol(); Debug.Assert(typeOperand is not null); SyntaxNode syntax = boundTypeOfOperator.Syntax; ITypeSymbol? type = boundTypeOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundTypeOfOperator.WasCompilerGenerated; return new TypeOfOperation(typeOperand, _semanticModel, syntax, type, isImplicit); } private IArrayCreationOperation CreateBoundArrayCreationOperation(BoundArrayCreation boundArrayCreation) { ImmutableArray<IOperation> dimensionSizes = CreateFromArray<BoundExpression, IOperation>(boundArrayCreation.Bounds); IArrayInitializerOperation? arrayInitializer = (IArrayInitializerOperation?)Create(boundArrayCreation.InitializerOpt); SyntaxNode syntax = boundArrayCreation.Syntax; ITypeSymbol? type = boundArrayCreation.GetPublicTypeSymbol(); bool isImplicit = boundArrayCreation.WasCompilerGenerated || (boundArrayCreation.InitializerOpt?.Syntax == syntax && !boundArrayCreation.InitializerOpt.WasCompilerGenerated); return new ArrayCreationOperation(dimensionSizes, arrayInitializer, _semanticModel, syntax, type, isImplicit); } private IArrayInitializerOperation CreateBoundArrayInitializationOperation(BoundArrayInitialization boundArrayInitialization) { ImmutableArray<IOperation> elementValues = CreateFromArray<BoundExpression, IOperation>(boundArrayInitialization.Initializers); SyntaxNode syntax = boundArrayInitialization.Syntax; bool isImplicit = boundArrayInitialization.WasCompilerGenerated; return new ArrayInitializerOperation(elementValues, _semanticModel, syntax, isImplicit); } private IDefaultValueOperation CreateBoundDefaultLiteralOperation(BoundDefaultLiteral boundDefaultLiteral) { SyntaxNode syntax = boundDefaultLiteral.Syntax; ConstantValue? constantValue = boundDefaultLiteral.ConstantValue; bool isImplicit = boundDefaultLiteral.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type: null, constantValue, isImplicit); } private IDefaultValueOperation CreateBoundDefaultExpressionOperation(BoundDefaultExpression boundDefaultExpression) { SyntaxNode syntax = boundDefaultExpression.Syntax; ITypeSymbol? type = boundDefaultExpression.GetPublicTypeSymbol(); ConstantValue? constantValue = boundDefaultExpression.ConstantValue; bool isImplicit = boundDefaultExpression.WasCompilerGenerated; return new DefaultValueOperation(_semanticModel, syntax, type, constantValue, isImplicit); } private IInstanceReferenceOperation CreateBoundBaseReferenceOperation(BoundBaseReference boundBaseReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundBaseReference.Syntax; ITypeSymbol? type = boundBaseReference.GetPublicTypeSymbol(); bool isImplicit = boundBaseReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundThisReferenceOperation(BoundThisReference boundThisReference) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ContainingTypeInstance; SyntaxNode syntax = boundThisReference.Syntax; ITypeSymbol? type = boundThisReference.GetPublicTypeSymbol(); bool isImplicit = boundThisReference.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundAssignmentOperatorOrMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { return IsMemberInitializer(boundAssignmentOperator) ? (IOperation)CreateBoundMemberInitializerOperation(boundAssignmentOperator) : CreateBoundAssignmentOperatorOperation(boundAssignmentOperator); } private static bool IsMemberInitializer(BoundAssignmentOperator boundAssignmentOperator) => boundAssignmentOperator.Right?.Kind == BoundKind.ObjectInitializerExpression || boundAssignmentOperator.Right?.Kind == BoundKind.CollectionInitializerExpression; private ISimpleAssignmentOperation CreateBoundAssignmentOperatorOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(!IsMemberInitializer(boundAssignmentOperator)); IOperation target = Create(boundAssignmentOperator.Left); IOperation value = Create(boundAssignmentOperator.Right); bool isRef = boundAssignmentOperator.IsRef; SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundAssignmentOperator.ConstantValue; bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicit); } private IMemberInitializerOperation CreateBoundMemberInitializerOperation(BoundAssignmentOperator boundAssignmentOperator) { Debug.Assert(IsMemberInitializer(boundAssignmentOperator)); IOperation initializedMember = CreateMemberInitializerInitializedMember(boundAssignmentOperator.Left); IObjectOrCollectionInitializerOperation initializer = (IObjectOrCollectionInitializerOperation)Create(boundAssignmentOperator.Right); SyntaxNode syntax = boundAssignmentOperator.Syntax; ITypeSymbol? type = boundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundAssignmentOperator.WasCompilerGenerated; return new MemberInitializerOperation(initializedMember, initializer, _semanticModel, syntax, type, isImplicit); } private ICompoundAssignmentOperation CreateBoundCompoundAssignmentOperatorOperation(BoundCompoundAssignmentOperator boundCompoundAssignmentOperator) { IOperation target = Create(boundCompoundAssignmentOperator.Left); IOperation value = Create(boundCompoundAssignmentOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundCompoundAssignmentOperator.Operator.Kind); Conversion inConversion = boundCompoundAssignmentOperator.LeftConversion; Conversion outConversion = boundCompoundAssignmentOperator.FinalConversion; bool isLifted = boundCompoundAssignmentOperator.Operator.Kind.IsLifted(); bool isChecked = boundCompoundAssignmentOperator.Operator.Kind.IsChecked(); IMethodSymbol operatorMethod = boundCompoundAssignmentOperator.Operator.Method.GetPublicSymbol(); SyntaxNode syntax = boundCompoundAssignmentOperator.Syntax; ITypeSymbol? type = boundCompoundAssignmentOperator.GetPublicTypeSymbol(); bool isImplicit = boundCompoundAssignmentOperator.WasCompilerGenerated; return new CompoundAssignmentOperation(inConversion, outConversion, operatorKind, isLifted, isChecked, operatorMethod, target, value, _semanticModel, syntax, type, isImplicit); } private IIncrementOrDecrementOperation CreateBoundIncrementOperatorOperation(BoundIncrementOperator boundIncrementOperator) { OperationKind operationKind = Helper.IsDecrement(boundIncrementOperator.OperatorKind) ? OperationKind.Decrement : OperationKind.Increment; bool isPostfix = Helper.IsPostfixIncrementOrDecrement(boundIncrementOperator.OperatorKind); bool isLifted = boundIncrementOperator.OperatorKind.IsLifted(); bool isChecked = boundIncrementOperator.OperatorKind.IsChecked(); IOperation target = Create(boundIncrementOperator.Operand); IMethodSymbol? operatorMethod = boundIncrementOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundIncrementOperator.Syntax; ITypeSymbol? type = boundIncrementOperator.GetPublicTypeSymbol(); bool isImplicit = boundIncrementOperator.WasCompilerGenerated; return new IncrementOrDecrementOperation(isPostfix, isLifted, isChecked, target, operatorMethod, operationKind, _semanticModel, syntax, type, isImplicit); } private IInvalidOperation CreateBoundBadExpressionOperation(BoundBadExpression boundBadExpression) { SyntaxNode syntax = boundBadExpression.Syntax; // We match semantic model here: if the expression IsMissing, we have a null type, rather than the ErrorType of the bound node. ITypeSymbol? type = syntax.IsMissing ? null : boundBadExpression.GetPublicTypeSymbol(); // if child has syntax node point to same syntax node as bad expression, then this invalid expression is implicit bool isImplicit = boundBadExpression.WasCompilerGenerated || boundBadExpression.ChildBoundNodes.Any(e => e?.Syntax == boundBadExpression.Syntax); var children = CreateFromArray<BoundExpression, IOperation>(boundBadExpression.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type, constantValue: null, isImplicit); } private ITypeParameterObjectCreationOperation CreateBoundNewTOperation(BoundNewT boundNewT) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(boundNewT.InitializerExpressionOpt); SyntaxNode syntax = boundNewT.Syntax; ITypeSymbol? type = boundNewT.GetPublicTypeSymbol(); bool isImplicit = boundNewT.WasCompilerGenerated; return new TypeParameterObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private INoPiaObjectCreationOperation CreateNoPiaObjectCreationExpressionOperation(BoundNoPiaObjectCreationExpression creation) { IObjectOrCollectionInitializerOperation? initializer = (IObjectOrCollectionInitializerOperation?)Create(creation.InitializerExpressionOpt); SyntaxNode syntax = creation.Syntax; ITypeSymbol? type = creation.GetPublicTypeSymbol(); bool isImplicit = creation.WasCompilerGenerated; return new NoPiaObjectCreationOperation(initializer, _semanticModel, syntax, type, isImplicit); } private IUnaryOperation CreateBoundUnaryOperatorOperation(BoundUnaryOperator boundUnaryOperator) { UnaryOperatorKind unaryOperatorKind = Helper.DeriveUnaryOperatorKind(boundUnaryOperator.OperatorKind); IOperation operand = Create(boundUnaryOperator.Operand); IMethodSymbol? operatorMethod = boundUnaryOperator.MethodOpt.GetPublicSymbol(); SyntaxNode syntax = boundUnaryOperator.Syntax; ITypeSymbol? type = boundUnaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundUnaryOperator.ConstantValue; bool isLifted = boundUnaryOperator.OperatorKind.IsLifted(); bool isChecked = boundUnaryOperator.OperatorKind.IsChecked(); bool isImplicit = boundUnaryOperator.WasCompilerGenerated; return new UnaryOperation(unaryOperatorKind, operand, isLifted, isChecked, operatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundBinaryOperatorBase(BoundBinaryOperatorBase boundBinaryOperatorBase) { if (boundBinaryOperatorBase is BoundBinaryOperator { InterpolatedStringHandlerData: not null } binary) { return CreateBoundInterpolatedStringBinaryOperator(binary); } // Binary operators can be nested _many_ levels deep, and cause a stack overflow if we manually recurse. // To solve this, we use a manual stack for the left side. var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = boundBinaryOperatorBase; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null and not BoundBinaryOperator { InterpolatedStringHandlerData: not null }); Debug.Assert(stack.Count > 0); IOperation? left = null; while (stack.TryPop(out currentBinary)) { left ??= Create(currentBinary.Left); IOperation right = Create(currentBinary.Right); left = currentBinary switch { BoundBinaryOperator binaryOp => CreateBoundBinaryOperatorOperation(binaryOp, left, right), BoundUserDefinedConditionalLogicalOperator logicalOp => createBoundUserDefinedConditionalLogicalOperator(logicalOp, left, right), { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; } Debug.Assert(left is not null && stack.Count == 0); stack.Free(); return left; IBinaryOperation createBoundUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol operatorMethod = boundBinaryOperator.LogicalOperator.GetPublicSymbol(); IMethodSymbol unaryOperatorMethod = boundBinaryOperator.OperatorKind.Operator() == CSharp.BinaryOperatorKind.And ? boundBinaryOperator.FalseOperator.GetPublicSymbol() : boundBinaryOperator.TrueOperator.GetPublicSymbol(); SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } } private IBinaryOperation CreateBoundBinaryOperatorOperation(BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind); IMethodSymbol? operatorMethod = boundBinaryOperator.Method.GetPublicSymbol(); IMethodSymbol? unaryOperatorMethod = null; // For dynamic logical operator MethodOpt is actually the unary true/false operator if (boundBinaryOperator.Type.IsDynamic() && (operatorKind == BinaryOperatorKind.ConditionalAnd || operatorKind == BinaryOperatorKind.ConditionalOr) && operatorMethod?.Parameters.Length == 1) { unaryOperatorMethod = operatorMethod; operatorMethod = null; } SyntaxNode syntax = boundBinaryOperator.Syntax; ITypeSymbol? type = boundBinaryOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundBinaryOperator.ConstantValue; bool isLifted = boundBinaryOperator.OperatorKind.IsLifted(); bool isChecked = boundBinaryOperator.OperatorKind.IsChecked(); bool isCompareText = false; bool isImplicit = boundBinaryOperator.WasCompilerGenerated; return new BinaryOperation(operatorKind, left, right, isLifted, isChecked, isCompareText, operatorMethod, unaryOperatorMethod, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundInterpolatedStringBinaryOperator(BoundBinaryOperator boundBinaryOperator) { Debug.Assert(boundBinaryOperator.InterpolatedStringHandlerData is not null); Func<BoundInterpolatedString, int, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createInterpolatedString = createInterpolatedStringOperand; Func<BoundBinaryOperator, IOperation, IOperation, (CSharpOperationFactory, InterpolatedStringHandlerData), IOperation> createBinaryOperator = createBoundBinaryOperatorOperation; return boundBinaryOperator.RewriteInterpolatedStringAddition((this, boundBinaryOperator.InterpolatedStringHandlerData.GetValueOrDefault()), createInterpolatedString, createBinaryOperator); static IInterpolatedStringOperation createInterpolatedStringOperand( BoundInterpolatedString boundInterpolatedString, int i, (CSharpOperationFactory @this, InterpolatedStringHandlerData Data) arg) => [email protected](boundInterpolatedString, arg.Data.PositionInfo[i]); static IBinaryOperation createBoundBinaryOperatorOperation( BoundBinaryOperator boundBinaryOperator, IOperation left, IOperation right, (CSharpOperationFactory @this, InterpolatedStringHandlerData _) arg) => [email protected](boundBinaryOperator, left, right); } private ITupleBinaryOperation CreateBoundTupleBinaryOperatorOperation(BoundTupleBinaryOperator boundTupleBinaryOperator) { IOperation left = Create(boundTupleBinaryOperator.Left); IOperation right = Create(boundTupleBinaryOperator.Right); BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundTupleBinaryOperator.OperatorKind); SyntaxNode syntax = boundTupleBinaryOperator.Syntax; ITypeSymbol? type = boundTupleBinaryOperator.GetPublicTypeSymbol(); bool isImplicit = boundTupleBinaryOperator.WasCompilerGenerated; return new TupleBinaryOperation(operatorKind, left, right, _semanticModel, syntax, type, isImplicit); } private IConditionalOperation CreateBoundConditionalOperatorOperation(BoundConditionalOperator boundConditionalOperator) { IOperation condition = Create(boundConditionalOperator.Condition); IOperation whenTrue = Create(boundConditionalOperator.Consequence); IOperation whenFalse = Create(boundConditionalOperator.Alternative); bool isRef = boundConditionalOperator.IsRef; SyntaxNode syntax = boundConditionalOperator.Syntax; ITypeSymbol? type = boundConditionalOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundConditionalOperator.ConstantValue; bool isImplicit = boundConditionalOperator.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private ICoalesceOperation CreateBoundNullCoalescingOperatorOperation(BoundNullCoalescingOperator boundNullCoalescingOperator) { IOperation value = Create(boundNullCoalescingOperator.LeftOperand); IOperation whenNull = Create(boundNullCoalescingOperator.RightOperand); SyntaxNode syntax = boundNullCoalescingOperator.Syntax; ITypeSymbol? type = boundNullCoalescingOperator.GetPublicTypeSymbol(); ConstantValue? constantValue = boundNullCoalescingOperator.ConstantValue; bool isImplicit = boundNullCoalescingOperator.WasCompilerGenerated; Conversion valueConversion = boundNullCoalescingOperator.LeftConversion; if (valueConversion.Exists && !valueConversion.IsIdentity && boundNullCoalescingOperator.Type.Equals(boundNullCoalescingOperator.LeftOperand.Type?.StrippedType(), TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { valueConversion = Conversion.Identity; } return new CoalesceOperation(value, whenNull, valueConversion, _semanticModel, syntax, type, constantValue, isImplicit); } private IOperation CreateBoundNullCoalescingAssignmentOperatorOperation(BoundNullCoalescingAssignmentOperator boundNode) { IOperation target = Create(boundNode.LeftOperand); IOperation value = Create(boundNode.RightOperand); SyntaxNode syntax = boundNode.Syntax; ITypeSymbol? type = boundNode.GetPublicTypeSymbol(); bool isImplicit = boundNode.WasCompilerGenerated; return new CoalesceAssignmentOperation(target, value, _semanticModel, syntax, type, isImplicit); } private IAwaitOperation CreateBoundAwaitExpressionOperation(BoundAwaitExpression boundAwaitExpression) { IOperation awaitedValue = Create(boundAwaitExpression.Expression); SyntaxNode syntax = boundAwaitExpression.Syntax; ITypeSymbol? type = boundAwaitExpression.GetPublicTypeSymbol(); bool isImplicit = boundAwaitExpression.WasCompilerGenerated; return new AwaitOperation(awaitedValue, _semanticModel, syntax, type, isImplicit); } private IArrayElementReferenceOperation CreateBoundArrayAccessOperation(BoundArrayAccess boundArrayAccess) { IOperation arrayReference = Create(boundArrayAccess.Expression); ImmutableArray<IOperation> indices = CreateFromArray<BoundExpression, IOperation>(boundArrayAccess.Indices); SyntaxNode syntax = boundArrayAccess.Syntax; ITypeSymbol? type = boundArrayAccess.GetPublicTypeSymbol(); bool isImplicit = boundArrayAccess.WasCompilerGenerated; return new ArrayElementReferenceOperation(arrayReference, indices, _semanticModel, syntax, type, isImplicit); } private INameOfOperation CreateBoundNameOfOperatorOperation(BoundNameOfOperator boundNameOfOperator) { IOperation argument = Create(boundNameOfOperator.Argument); SyntaxNode syntax = boundNameOfOperator.Syntax; ITypeSymbol? type = boundNameOfOperator.GetPublicTypeSymbol(); ConstantValue constantValue = boundNameOfOperator.ConstantValue; bool isImplicit = boundNameOfOperator.WasCompilerGenerated; return new NameOfOperation(argument, _semanticModel, syntax, type, constantValue, isImplicit); } private IThrowOperation CreateBoundThrowExpressionOperation(BoundThrowExpression boundThrowExpression) { IOperation expression = Create(boundThrowExpression.Expression); SyntaxNode syntax = boundThrowExpression.Syntax; ITypeSymbol? type = boundThrowExpression.GetPublicTypeSymbol(); bool isImplicit = boundThrowExpression.WasCompilerGenerated; return new ThrowOperation(expression, _semanticModel, syntax, type, isImplicit); } private IAddressOfOperation CreateBoundAddressOfOperatorOperation(BoundAddressOfOperator boundAddressOfOperator) { IOperation reference = Create(boundAddressOfOperator.Operand); SyntaxNode syntax = boundAddressOfOperator.Syntax; ITypeSymbol? type = boundAddressOfOperator.GetPublicTypeSymbol(); bool isImplicit = boundAddressOfOperator.WasCompilerGenerated; return new AddressOfOperation(reference, _semanticModel, syntax, type, isImplicit); } private IInstanceReferenceOperation CreateBoundImplicitReceiverOperation(BoundImplicitReceiver boundImplicitReceiver) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = boundImplicitReceiver.Syntax; ITypeSymbol? type = boundImplicitReceiver.GetPublicTypeSymbol(); bool isImplicit = boundImplicitReceiver.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessOperation CreateBoundConditionalAccessOperation(BoundConditionalAccess boundConditionalAccess) { IOperation operation = Create(boundConditionalAccess.Receiver); IOperation whenNotNull = Create(boundConditionalAccess.AccessExpression); SyntaxNode syntax = boundConditionalAccess.Syntax; ITypeSymbol? type = boundConditionalAccess.GetPublicTypeSymbol(); bool isImplicit = boundConditionalAccess.WasCompilerGenerated; return new ConditionalAccessOperation(operation, whenNotNull, _semanticModel, syntax, type, isImplicit); } private IConditionalAccessInstanceOperation CreateBoundConditionalReceiverOperation(BoundConditionalReceiver boundConditionalReceiver) { SyntaxNode syntax = boundConditionalReceiver.Syntax; ITypeSymbol? type = boundConditionalReceiver.GetPublicTypeSymbol(); bool isImplicit = boundConditionalReceiver.WasCompilerGenerated; return new ConditionalAccessInstanceOperation(_semanticModel, syntax, type, isImplicit); } private IFieldInitializerOperation CreateBoundFieldEqualsValueOperation(BoundFieldEqualsValue boundFieldEqualsValue) { ImmutableArray<IFieldSymbol> initializedFields = ImmutableArray.Create<IFieldSymbol>(boundFieldEqualsValue.Field.GetPublicSymbol()); IOperation value = Create(boundFieldEqualsValue.Value); SyntaxNode syntax = boundFieldEqualsValue.Syntax; bool isImplicit = boundFieldEqualsValue.WasCompilerGenerated; return new FieldInitializerOperation(initializedFields, boundFieldEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IPropertyInitializerOperation CreateBoundPropertyEqualsValueOperation(BoundPropertyEqualsValue boundPropertyEqualsValue) { ImmutableArray<IPropertySymbol> initializedProperties = ImmutableArray.Create<IPropertySymbol>(boundPropertyEqualsValue.Property.GetPublicSymbol()); IOperation value = Create(boundPropertyEqualsValue.Value); SyntaxNode syntax = boundPropertyEqualsValue.Syntax; bool isImplicit = boundPropertyEqualsValue.WasCompilerGenerated; return new PropertyInitializerOperation(initializedProperties, boundPropertyEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IParameterInitializerOperation CreateBoundParameterEqualsValueOperation(BoundParameterEqualsValue boundParameterEqualsValue) { IParameterSymbol parameter = boundParameterEqualsValue.Parameter.GetPublicSymbol(); IOperation value = Create(boundParameterEqualsValue.Value); SyntaxNode syntax = boundParameterEqualsValue.Syntax; bool isImplicit = boundParameterEqualsValue.WasCompilerGenerated; return new ParameterInitializerOperation(parameter, boundParameterEqualsValue.Locals.GetPublicSymbols(), value, _semanticModel, syntax, isImplicit); } private IBlockOperation CreateBoundBlockOperation(BoundBlock boundBlock) { ImmutableArray<IOperation> operations = CreateFromArray<BoundStatement, IOperation>(boundBlock.Statements); ImmutableArray<ILocalSymbol> locals = boundBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundBlock.Syntax; bool isImplicit = boundBlock.WasCompilerGenerated; return new BlockOperation(operations, locals, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundContinueStatementOperation(BoundContinueStatement boundContinueStatement) { ILabelSymbol target = boundContinueStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Continue; SyntaxNode syntax = boundContinueStatement.Syntax; bool isImplicit = boundContinueStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundBreakStatementOperation(BoundBreakStatement boundBreakStatement) { ILabelSymbol target = boundBreakStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.Break; SyntaxNode syntax = boundBreakStatement.Syntax; bool isImplicit = boundBreakStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldBreakStatementOperation(BoundYieldBreakStatement boundYieldBreakStatement) { IOperation? returnedValue = null; SyntaxNode syntax = boundYieldBreakStatement.Syntax; bool isImplicit = boundYieldBreakStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldBreak, _semanticModel, syntax, isImplicit); } private IBranchOperation CreateBoundGotoStatementOperation(BoundGotoStatement boundGotoStatement) { ILabelSymbol target = boundGotoStatement.Label.GetPublicSymbol(); BranchKind branchKind = BranchKind.GoTo; SyntaxNode syntax = boundGotoStatement.Syntax; bool isImplicit = boundGotoStatement.WasCompilerGenerated; return new BranchOperation(target, branchKind, _semanticModel, syntax, isImplicit); } private IEmptyOperation CreateBoundNoOpStatementOperation(BoundNoOpStatement boundNoOpStatement) { SyntaxNode syntax = boundNoOpStatement.Syntax; bool isImplicit = boundNoOpStatement.WasCompilerGenerated; return new EmptyOperation(_semanticModel, syntax, isImplicit); } private IConditionalOperation CreateBoundIfStatementOperation(BoundIfStatement boundIfStatement) { IOperation condition = Create(boundIfStatement.Condition); IOperation whenTrue = Create(boundIfStatement.Consequence); IOperation? whenFalse = Create(boundIfStatement.AlternativeOpt); bool isRef = false; SyntaxNode syntax = boundIfStatement.Syntax; ITypeSymbol? type = null; ConstantValue? constantValue = null; bool isImplicit = boundIfStatement.WasCompilerGenerated; return new ConditionalOperation(condition, whenTrue, whenFalse, isRef, _semanticModel, syntax, type, constantValue, isImplicit); } private IWhileLoopOperation CreateBoundWhileStatementOperation(BoundWhileStatement boundWhileStatement) { IOperation condition = Create(boundWhileStatement.Condition); IOperation body = Create(boundWhileStatement.Body); ImmutableArray<ILocalSymbol> locals = boundWhileStatement.Locals.GetPublicSymbols(); ILabelSymbol continueLabel = boundWhileStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundWhileStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = true; bool conditionIsUntil = false; SyntaxNode syntax = boundWhileStatement.Syntax; bool isImplicit = boundWhileStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IWhileLoopOperation CreateBoundDoStatementOperation(BoundDoStatement boundDoStatement) { IOperation condition = Create(boundDoStatement.Condition); IOperation body = Create(boundDoStatement.Body); ILabelSymbol continueLabel = boundDoStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundDoStatement.BreakLabel.GetPublicSymbol(); bool conditionIsTop = false; bool conditionIsUntil = false; ImmutableArray<ILocalSymbol> locals = boundDoStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundDoStatement.Syntax; bool isImplicit = boundDoStatement.WasCompilerGenerated; return new WhileLoopOperation(condition, conditionIsTop, conditionIsUntil, ignoredCondition: null, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private IForLoopOperation CreateBoundForStatementOperation(BoundForStatement boundForStatement) { ImmutableArray<IOperation> before = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Initializer)); IOperation? condition = Create(boundForStatement.Condition); ImmutableArray<IOperation> atLoopBottom = CreateFromArray<BoundStatement, IOperation>(ToStatements(boundForStatement.Increment)); IOperation body = Create(boundForStatement.Body); ImmutableArray<ILocalSymbol> locals = boundForStatement.OuterLocals.GetPublicSymbols(); ImmutableArray<ILocalSymbol> conditionLocals = boundForStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol continueLabel = boundForStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForStatement.Syntax; bool isImplicit = boundForStatement.WasCompilerGenerated; return new ForLoopOperation(before, conditionLocals, condition, atLoopBottom, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } internal ForEachLoopOperationInfo? GetForEachLoopOperatorInfo(BoundForEachStatement boundForEachStatement) { ForEachEnumeratorInfo? enumeratorInfoOpt = boundForEachStatement.EnumeratorInfoOpt; ForEachLoopOperationInfo? info; if (enumeratorInfoOpt != null) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var compilation = (CSharpCompilation)_semanticModel.Compilation; var iDisposable = enumeratorInfoOpt.IsAsync ? compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable) : compilation.GetSpecialType(SpecialType.System_IDisposable); info = new ForEachLoopOperationInfo(enumeratorInfoOpt.ElementType.GetPublicSymbol(), enumeratorInfoOpt.GetEnumeratorInfo.Method.GetPublicSymbol(), ((PropertySymbol)enumeratorInfoOpt.CurrentPropertyGetter.AssociatedSymbol).GetPublicSymbol(), enumeratorInfoOpt.MoveNextInfo.Method.GetPublicSymbol(), isAsynchronous: enumeratorInfoOpt.IsAsync, needsDispose: enumeratorInfoOpt.NeedsDisposal, knownToImplementIDisposable: enumeratorInfoOpt.NeedsDisposal ? compilation.Conversions. ClassifyImplicitConversionFromType(enumeratorInfoOpt.GetEnumeratorInfo.Method.ReturnType, iDisposable, ref discardedUseSiteInfo).IsImplicit : false, enumeratorInfoOpt.PatternDisposeInfo?.Method.GetPublicSymbol(), enumeratorInfoOpt.CurrentConversion, boundForEachStatement.ElementConversion, getEnumeratorArguments: enumeratorInfoOpt.GetEnumeratorInfo is { Method: { IsExtensionMethod: true } } getEnumeratorInfo ? Operation.SetParentOperation( DeriveArguments( getEnumeratorInfo.Method, getEnumeratorInfo.Arguments, argumentsToParametersOpt: default, getEnumeratorInfo.DefaultArguments, getEnumeratorInfo.Expanded, boundForEachStatement.Expression.Syntax, invokedAsExtensionMethod: true), null) : default, disposeArguments: enumeratorInfoOpt.PatternDisposeInfo is object ? CreateDisposeArguments(enumeratorInfoOpt.PatternDisposeInfo, boundForEachStatement.Syntax) : default); } else { info = null; } return info; } internal IOperation CreateBoundForEachStatementLoopControlVariable(BoundForEachStatement boundForEachStatement) { if (boundForEachStatement.DeconstructionOpt != null) { return Create(boundForEachStatement.DeconstructionOpt.DeconstructionAssignment.Left); } else if (boundForEachStatement.IterationErrorExpressionOpt != null) { return Create(boundForEachStatement.IterationErrorExpressionOpt); } else { Debug.Assert(boundForEachStatement.IterationVariables.Length == 1); var local = boundForEachStatement.IterationVariables[0]; // We use iteration variable type syntax as the underlying syntax node as there is no variable declarator syntax in the syntax tree. var declaratorSyntax = boundForEachStatement.IterationVariableType.Syntax; return new VariableDeclaratorOperation(local.GetPublicSymbol(), initializer: null, ignoredArguments: ImmutableArray<IOperation>.Empty, semanticModel: _semanticModel, syntax: declaratorSyntax, isImplicit: false); } } private IForEachLoopOperation CreateBoundForEachStatementOperation(BoundForEachStatement boundForEachStatement) { IOperation loopControlVariable = CreateBoundForEachStatementLoopControlVariable(boundForEachStatement); IOperation collection = Create(boundForEachStatement.Expression); var nextVariables = ImmutableArray<IOperation>.Empty; IOperation body = Create(boundForEachStatement.Body); ForEachLoopOperationInfo? info = GetForEachLoopOperatorInfo(boundForEachStatement); ImmutableArray<ILocalSymbol> locals = boundForEachStatement.IterationVariables.GetPublicSymbols(); ILabelSymbol continueLabel = boundForEachStatement.ContinueLabel.GetPublicSymbol(); ILabelSymbol exitLabel = boundForEachStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundForEachStatement.Syntax; bool isImplicit = boundForEachStatement.WasCompilerGenerated; bool isAsynchronous = boundForEachStatement.AwaitOpt != null; return new ForEachLoopOperation(loopControlVariable, collection, nextVariables, info, isAsynchronous, body, locals, continueLabel, exitLabel, _semanticModel, syntax, isImplicit); } private ITryOperation CreateBoundTryStatementOperation(BoundTryStatement boundTryStatement) { var body = (IBlockOperation)Create(boundTryStatement.TryBlock); ImmutableArray<ICatchClauseOperation> catches = CreateFromArray<BoundCatchBlock, ICatchClauseOperation>(boundTryStatement.CatchBlocks); var @finally = (IBlockOperation?)Create(boundTryStatement.FinallyBlockOpt); SyntaxNode syntax = boundTryStatement.Syntax; bool isImplicit = boundTryStatement.WasCompilerGenerated; return new TryOperation(body, catches, @finally, exitLabel: null, _semanticModel, syntax, isImplicit); } private ICatchClauseOperation CreateBoundCatchBlockOperation(BoundCatchBlock boundCatchBlock) { IOperation? exceptionDeclarationOrExpression = CreateVariableDeclarator((BoundLocal?)boundCatchBlock.ExceptionSourceOpt); // The exception filter prologue is introduced during lowering, so should be null here. Debug.Assert(boundCatchBlock.ExceptionFilterPrologueOpt is null); IOperation? filter = Create(boundCatchBlock.ExceptionFilterOpt); IBlockOperation handler = (IBlockOperation)Create(boundCatchBlock.Body); ITypeSymbol exceptionType = boundCatchBlock.ExceptionTypeOpt.GetPublicSymbol() ?? _semanticModel.Compilation.ObjectType; ImmutableArray<ILocalSymbol> locals = boundCatchBlock.Locals.GetPublicSymbols(); SyntaxNode syntax = boundCatchBlock.Syntax; bool isImplicit = boundCatchBlock.WasCompilerGenerated; return new CatchClauseOperation(exceptionDeclarationOrExpression, exceptionType, locals, filter, handler, _semanticModel, syntax, isImplicit); } private IFixedOperation CreateBoundFixedStatementOperation(BoundFixedStatement boundFixedStatement) { IVariableDeclarationGroupOperation variables = (IVariableDeclarationGroupOperation)Create(boundFixedStatement.Declarations); IOperation body = Create(boundFixedStatement.Body); ImmutableArray<ILocalSymbol> locals = boundFixedStatement.Locals.GetPublicSymbols(); SyntaxNode syntax = boundFixedStatement.Syntax; bool isImplicit = boundFixedStatement.WasCompilerGenerated; return new FixedOperation(locals, variables, body, _semanticModel, syntax, isImplicit); } private IUsingOperation CreateBoundUsingStatementOperation(BoundUsingStatement boundUsingStatement) { Debug.Assert((boundUsingStatement.DeclarationsOpt == null) != (boundUsingStatement.ExpressionOpt == null)); Debug.Assert(boundUsingStatement.ExpressionOpt is object || boundUsingStatement.Locals.Length > 0); IOperation resources = Create(boundUsingStatement.DeclarationsOpt ?? (BoundNode)boundUsingStatement.ExpressionOpt!); IOperation body = Create(boundUsingStatement.Body); ImmutableArray<ILocalSymbol> locals = boundUsingStatement.Locals.GetPublicSymbols(); bool isAsynchronous = boundUsingStatement.AwaitOpt != null; DisposeOperationInfo disposeOperationInfo = boundUsingStatement.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: boundUsingStatement.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(boundUsingStatement.PatternDisposeInfoOpt, boundUsingStatement.Syntax)) : default; SyntaxNode syntax = boundUsingStatement.Syntax; bool isImplicit = boundUsingStatement.WasCompilerGenerated; return new UsingOperation(resources, body, locals, isAsynchronous, disposeOperationInfo, _semanticModel, syntax, isImplicit); } private IThrowOperation CreateBoundThrowStatementOperation(BoundThrowStatement boundThrowStatement) { IOperation? thrownObject = Create(boundThrowStatement.ExpressionOpt); SyntaxNode syntax = boundThrowStatement.Syntax; ITypeSymbol? statementType = null; bool isImplicit = boundThrowStatement.WasCompilerGenerated; return new ThrowOperation(thrownObject, _semanticModel, syntax, statementType, isImplicit); } private IReturnOperation CreateBoundReturnStatementOperation(BoundReturnStatement boundReturnStatement) { IOperation? returnedValue = Create(boundReturnStatement.ExpressionOpt); SyntaxNode syntax = boundReturnStatement.Syntax; bool isImplicit = boundReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.Return, _semanticModel, syntax, isImplicit); } private IReturnOperation CreateBoundYieldReturnStatementOperation(BoundYieldReturnStatement boundYieldReturnStatement) { IOperation returnedValue = Create(boundYieldReturnStatement.Expression); SyntaxNode syntax = boundYieldReturnStatement.Syntax; bool isImplicit = boundYieldReturnStatement.WasCompilerGenerated; return new ReturnOperation(returnedValue, OperationKind.YieldReturn, _semanticModel, syntax, isImplicit); } private ILockOperation CreateBoundLockStatementOperation(BoundLockStatement boundLockStatement) { // If there is no Enter2 method, then there will be no lock taken reference bool legacyMode = _semanticModel.Compilation.CommonGetWellKnownTypeMember(WellKnownMember.System_Threading_Monitor__Enter2) == null; ILocalSymbol? lockTakenSymbol = legacyMode ? null : new SynthesizedLocal((_semanticModel.GetEnclosingSymbol(boundLockStatement.Syntax.SpanStart) as IMethodSymbol).GetSymbol(), TypeWithAnnotations.Create(((CSharpCompilation)_semanticModel.Compilation).GetSpecialType(SpecialType.System_Boolean)), SynthesizedLocalKind.LockTaken, syntaxOpt: boundLockStatement.Argument.Syntax).GetPublicSymbol(); IOperation lockedValue = Create(boundLockStatement.Argument); IOperation body = Create(boundLockStatement.Body); SyntaxNode syntax = boundLockStatement.Syntax; bool isImplicit = boundLockStatement.WasCompilerGenerated; return new LockOperation(lockedValue, body, lockTakenSymbol, _semanticModel, syntax, isImplicit); } private IInvalidOperation CreateBoundBadStatementOperation(BoundBadStatement boundBadStatement) { SyntaxNode syntax = boundBadStatement.Syntax; // if child has syntax node point to same syntax node as bad statement, then this invalid statement is implicit bool isImplicit = boundBadStatement.WasCompilerGenerated || boundBadStatement.ChildBoundNodes.Any(e => e?.Syntax == boundBadStatement.Syntax); var children = CreateFromArray<BoundNode, IOperation>(boundBadStatement.ChildBoundNodes); return new InvalidOperation(children, _semanticModel, syntax, type: null, constantValue: null, isImplicit); } private IOperation CreateBoundLocalDeclarationOperation(BoundLocalDeclaration boundLocalDeclaration) { var node = boundLocalDeclaration.Syntax; var kind = node.Kind(); SyntaxNode varStatement; SyntaxNode varDeclaration; switch (kind) { case SyntaxKind.LocalDeclarationStatement: { var statement = (LocalDeclarationStatementSyntax)node; // this happen for simple int i = 0; // var statement points to LocalDeclarationStatementSyntax varStatement = statement; varDeclaration = statement.Declaration; break; } case SyntaxKind.VariableDeclarator: { // this happen for 'for loop' initializer // We generate a DeclarationGroup for this scenario to maintain tree shape consistency across IOperation. // var statement points to VariableDeclarationSyntax Debug.Assert(node.Parent != null); varStatement = node.Parent; varDeclaration = node.Parent; break; } default: { Debug.Fail($"Unexpected syntax: {kind}"); // otherwise, they points to whatever bound nodes are pointing to. varStatement = varDeclaration = node; break; } } bool multiVariableImplicit = boundLocalDeclaration.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundLocalDeclaration, varDeclaration); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundLocalDeclaration, varDeclaration); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, varDeclaration, multiVariableImplicit); // In the case of a for loop, varStatement and varDeclaration will be the same syntax node. // We can only have one explicit operation, so make sure this node is implicit in that scenario. bool isImplicit = (varStatement == varDeclaration) || boundLocalDeclaration.WasCompilerGenerated; return new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, varStatement, isImplicit); } private IOperation CreateBoundMultipleLocalDeclarationsBaseOperation(BoundMultipleLocalDeclarationsBase boundMultipleLocalDeclarations) { // The syntax for the boundMultipleLocalDeclarations can either be a LocalDeclarationStatement or a VariableDeclaration, depending on the context // (using/fixed statements vs variable declaration) // We generate a DeclarationGroup for these scenarios (using/fixed) to maintain tree shape consistency across IOperation. SyntaxNode declarationGroupSyntax = boundMultipleLocalDeclarations.Syntax; SyntaxNode declarationSyntax = declarationGroupSyntax.IsKind(SyntaxKind.LocalDeclarationStatement) ? ((LocalDeclarationStatementSyntax)declarationGroupSyntax).Declaration : declarationGroupSyntax; bool declarationIsImplicit = boundMultipleLocalDeclarations.WasCompilerGenerated; ImmutableArray<IVariableDeclaratorOperation> declarators = CreateVariableDeclarator(boundMultipleLocalDeclarations, declarationSyntax); ImmutableArray<IOperation> ignoredDimensions = CreateIgnoredDimensions(boundMultipleLocalDeclarations, declarationSyntax); IVariableDeclarationOperation multiVariableDeclaration = new VariableDeclarationOperation(declarators, initializer: null, ignoredDimensions, _semanticModel, declarationSyntax, declarationIsImplicit); // If the syntax was the same, we're in a fixed statement or using statement. We make the Group operation implicit in this scenario, as the // syntax itself is a VariableDeclaration. We do this for using declarations as well, but since that doesn't have a separate parent bound // node, we need to check the current node for that explicitly. bool isImplicit = declarationGroupSyntax == declarationSyntax || boundMultipleLocalDeclarations.WasCompilerGenerated || boundMultipleLocalDeclarations is BoundUsingLocalDeclarations; var variableDeclaration = new VariableDeclarationGroupOperation(ImmutableArray.Create(multiVariableDeclaration), _semanticModel, declarationGroupSyntax, isImplicit); if (boundMultipleLocalDeclarations is BoundUsingLocalDeclarations usingDecl) { return new UsingDeclarationOperation( variableDeclaration, isAsynchronous: usingDecl.AwaitOpt is object, disposeInfo: usingDecl.PatternDisposeInfoOpt is object ? new DisposeOperationInfo( disposeMethod: usingDecl.PatternDisposeInfoOpt.Method.GetPublicSymbol(), disposeArguments: CreateDisposeArguments(usingDecl.PatternDisposeInfoOpt, usingDecl.Syntax)) : default, _semanticModel, declarationGroupSyntax, isImplicit: boundMultipleLocalDeclarations.WasCompilerGenerated); } return variableDeclaration; } private ILabeledOperation CreateBoundLabelStatementOperation(BoundLabelStatement boundLabelStatement) { ILabelSymbol label = boundLabelStatement.Label.GetPublicSymbol(); SyntaxNode syntax = boundLabelStatement.Syntax; bool isImplicit = boundLabelStatement.WasCompilerGenerated; return new LabeledOperation(label, operation: null, _semanticModel, syntax, isImplicit); } private ILabeledOperation CreateBoundLabeledStatementOperation(BoundLabeledStatement boundLabeledStatement) { ILabelSymbol label = boundLabeledStatement.Label.GetPublicSymbol(); IOperation labeledStatement = Create(boundLabeledStatement.Body); SyntaxNode syntax = boundLabeledStatement.Syntax; bool isImplicit = boundLabeledStatement.WasCompilerGenerated; return new LabeledOperation(label, labeledStatement, _semanticModel, syntax, isImplicit); } private IExpressionStatementOperation CreateBoundExpressionStatementOperation(BoundExpressionStatement boundExpressionStatement) { // lambda body can point to expression directly and binder can insert expression statement there. and end up statement pointing to // expression syntax node since there is no statement syntax node to point to. this will mark such one as implicit since it doesn't // actually exist in code bool isImplicit = boundExpressionStatement.WasCompilerGenerated || boundExpressionStatement.Syntax == boundExpressionStatement.Expression.Syntax; SyntaxNode syntax = boundExpressionStatement.Syntax; // If we're creating the tree for a speculatively-bound constructor initializer, there can be a bound sequence as the child node here // that corresponds to the lifetime of any declared variables. IOperation expression = Create(boundExpressionStatement.Expression); if (boundExpressionStatement.Expression is BoundSequence sequence) { Debug.Assert(boundExpressionStatement.Syntax == sequence.Value.Syntax); isImplicit = true; } return new ExpressionStatementOperation(expression, _semanticModel, syntax, isImplicit); } internal IOperation CreateBoundTupleOperation(BoundTupleExpression boundTupleExpression, bool createDeclaration = true) { SyntaxNode syntax = boundTupleExpression.Syntax; bool isImplicit = boundTupleExpression.WasCompilerGenerated; ITypeSymbol? type = boundTupleExpression.GetPublicTypeSymbol(); if (syntax is DeclarationExpressionSyntax declarationExpressionSyntax) { syntax = declarationExpressionSyntax.Designation; if (createDeclaration) { var tupleOperation = CreateBoundTupleOperation(boundTupleExpression, createDeclaration: false); return new DeclarationExpressionOperation(tupleOperation, _semanticModel, declarationExpressionSyntax, type, isImplicit: false); } } TypeSymbol? naturalType = boundTupleExpression switch { BoundTupleLiteral { Type: var t } => t, BoundConvertedTupleLiteral { SourceTuple: { Type: var t } } => t, BoundConvertedTupleLiteral => null, { Kind: var kind } => throw ExceptionUtilities.UnexpectedValue(kind) }; ImmutableArray<IOperation> elements = CreateFromArray<BoundExpression, IOperation>(boundTupleExpression.Arguments); return new TupleOperation(elements, naturalType.GetPublicSymbol(), _semanticModel, syntax, type, isImplicit); } private IInterpolatedStringOperation CreateBoundInterpolatedStringExpressionOperation(BoundInterpolatedString boundInterpolatedString, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo = null) { Debug.Assert(positionInfo == null || boundInterpolatedString.InterpolationData == null); ImmutableArray<IInterpolatedStringContentOperation> parts = CreateBoundInterpolatedStringContentOperation(boundInterpolatedString.Parts, positionInfo ?? boundInterpolatedString.InterpolationData?.PositionInfo[0]); SyntaxNode syntax = boundInterpolatedString.Syntax; ITypeSymbol? type = boundInterpolatedString.GetPublicTypeSymbol(); ConstantValue? constantValue = boundInterpolatedString.ConstantValue; bool isImplicit = boundInterpolatedString.WasCompilerGenerated; return new InterpolatedStringOperation(parts, _semanticModel, syntax, type, constantValue, isImplicit); } internal ImmutableArray<IInterpolatedStringContentOperation> CreateBoundInterpolatedStringContentOperation(ImmutableArray<BoundExpression> parts, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>? positionInfo) { return positionInfo is { } info ? createHandlerInterpolatedStringContent(info) : createNonHandlerInterpolatedStringContent(); ImmutableArray<IInterpolatedStringContentOperation> createNonHandlerInterpolatedStringContent() { var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); foreach (var part in parts) { if (part.Kind == BoundKind.StringInsert) { builder.Add((IInterpolatedStringContentOperation)Create(part)); } else { builder.Add(CreateBoundInterpolatedStringTextOperation((BoundLiteral)part)); } } return builder.ToImmutableAndFree(); } ImmutableArray<IInterpolatedStringContentOperation> createHandlerInterpolatedStringContent(ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)> positionInfo) { // For interpolated string handlers, we want to deconstruct the `AppendLiteral`/`AppendFormatted` calls into // their relevant components. // https://github.com/dotnet/roslyn/issues/54505 we need to handle interpolated strings used as handler conversions. Debug.Assert(parts.Length == positionInfo.Length); var builder = ArrayBuilder<IInterpolatedStringContentOperation>.GetInstance(parts.Length); for (int i = 0; i < parts.Length; i++) { var part = parts[i]; var currentPosition = positionInfo[i]; BoundExpression value; BoundExpression? alignment; BoundExpression? format; switch (part) { case BoundCall call: (value, alignment, format) = getCallInfo(call.Arguments, call.ArgumentNamesOpt, currentPosition); break; case BoundDynamicInvocation dynamicInvocation: (value, alignment, format) = getCallInfo(dynamicInvocation.Arguments, dynamicInvocation.ArgumentNamesOpt, currentPosition); break; case BoundBadExpression bad: Debug.Assert(bad.ChildBoundNodes.Length == 2 + // initial value + receiver is added to the end (currentPosition.HasAlignment ? 1 : 0) + (currentPosition.HasFormat ? 1 : 0)); value = bad.ChildBoundNodes[0]; if (currentPosition.IsLiteral) { alignment = format = null; } else { alignment = currentPosition.HasAlignment ? bad.ChildBoundNodes[1] : null; format = currentPosition.HasFormat ? bad.ChildBoundNodes[^2] : null; } break; default: throw ExceptionUtilities.UnexpectedValue(part.Kind); } // We are intentionally not checking the part for implicitness here. The part is a generated AppendLiteral or AppendFormatted call, // and will always be marked as CompilerGenerated. However, our existing behavior for non-builder interpolated strings does not mark // the BoundLiteral or BoundStringInsert components as compiler generated. This generates a non-implicit IInterpolatedStringTextOperation // with an implicit literal underneath, and a non-implicit IInterpolationOperation with non-implicit underlying components. bool isImplicit = false; if (currentPosition.IsLiteral) { Debug.Assert(alignment is null); Debug.Assert(format is null); IOperation valueOperation = value switch { BoundLiteral l => CreateBoundLiteralOperation(l, @implicit: true), BoundConversion { Operand: BoundLiteral } c => CreateBoundConversionOperation(c, forceOperandImplicitLiteral: true), _ => throw ExceptionUtilities.UnexpectedValue(value.Kind), }; Debug.Assert(valueOperation.IsImplicit); builder.Add(new InterpolatedStringTextOperation(valueOperation, _semanticModel, part.Syntax, isImplicit)); } else { IOperation valueOperation = Create(value); IOperation? alignmentOperation = Create(alignment); IOperation? formatOperation = Create(format); Debug.Assert(valueOperation.Syntax != part.Syntax); builder.Add(new InterpolationOperation(valueOperation, alignmentOperation, formatOperation, _semanticModel, part.Syntax, isImplicit)); } } return builder.ToImmutableAndFree(); static (BoundExpression Value, BoundExpression? Alignment, BoundExpression? Format) getCallInfo(ImmutableArray<BoundExpression> arguments, ImmutableArray<string> argumentNamesOpt, (bool IsLiteral, bool HasAlignment, bool HasFormat) currentPosition) { BoundExpression value = arguments[0]; if (currentPosition.IsLiteral || argumentNamesOpt.IsDefault) { // There was no alignment/format component, as binding will qualify those parameters by name return (value, null, null); } else { var alignmentIndex = argumentNamesOpt.IndexOf("alignment"); BoundExpression? alignment = alignmentIndex == -1 ? null : arguments[alignmentIndex]; var formatIndex = argumentNamesOpt.IndexOf("format"); BoundExpression? format = formatIndex == -1 ? null : arguments[formatIndex]; return (value, alignment, format); } } } } private IInterpolationOperation CreateBoundInterpolationOperation(BoundStringInsert boundStringInsert) { IOperation expression = Create(boundStringInsert.Value); IOperation? alignment = Create(boundStringInsert.Alignment); IOperation? formatString = Create(boundStringInsert.Format); SyntaxNode syntax = boundStringInsert.Syntax; bool isImplicit = boundStringInsert.WasCompilerGenerated; return new InterpolationOperation(expression, alignment, formatString, _semanticModel, syntax, isImplicit); } private IInterpolatedStringTextOperation CreateBoundInterpolatedStringTextOperation(BoundLiteral boundNode) { IOperation text = CreateBoundLiteralOperation(boundNode, @implicit: true); SyntaxNode syntax = boundNode.Syntax; bool isImplicit = boundNode.WasCompilerGenerated; return new InterpolatedStringTextOperation(text, _semanticModel, syntax, isImplicit); } private IConstantPatternOperation CreateBoundConstantPatternOperation(BoundConstantPattern boundConstantPattern) { IOperation value = Create(boundConstantPattern.Value); SyntaxNode syntax = boundConstantPattern.Syntax; bool isImplicit = boundConstantPattern.WasCompilerGenerated; TypeSymbol inputType = boundConstantPattern.InputType; TypeSymbol narrowedType = boundConstantPattern.NarrowedType; return new ConstantPatternOperation(value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IOperation CreateBoundRelationalPatternOperation(BoundRelationalPattern boundRelationalPattern) { BinaryOperatorKind operatorKind = Helper.DeriveBinaryOperatorKind(boundRelationalPattern.Relation); IOperation value = Create(boundRelationalPattern.Value); SyntaxNode syntax = boundRelationalPattern.Syntax; bool isImplicit = boundRelationalPattern.WasCompilerGenerated; TypeSymbol inputType = boundRelationalPattern.InputType; TypeSymbol narrowedType = boundRelationalPattern.NarrowedType; return new RelationalPatternOperation(operatorKind, value, inputType.GetPublicSymbol(), narrowedType.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } private IDeclarationPatternOperation CreateBoundDeclarationPatternOperation(BoundDeclarationPattern boundDeclarationPattern) { ISymbol? variable = boundDeclarationPattern.Variable.GetPublicSymbol(); if (variable == null && boundDeclarationPattern.VariableAccess?.Kind == BoundKind.DiscardExpression) { variable = ((BoundDiscardExpression)boundDeclarationPattern.VariableAccess).ExpressionSymbol.GetPublicSymbol(); } ITypeSymbol inputType = boundDeclarationPattern.InputType.GetPublicSymbol(); ITypeSymbol narrowedType = boundDeclarationPattern.NarrowedType.GetPublicSymbol(); bool acceptsNull = boundDeclarationPattern.IsVar; ITypeSymbol? matchedType = acceptsNull ? null : boundDeclarationPattern.DeclaredType.GetPublicTypeSymbol(); SyntaxNode syntax = boundDeclarationPattern.Syntax; bool isImplicit = boundDeclarationPattern.WasCompilerGenerated; return new DeclarationPatternOperation(matchedType, acceptsNull, variable, inputType, narrowedType, _semanticModel, syntax, isImplicit); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundRecursivePattern boundRecursivePattern) { ITypeSymbol matchedType = (boundRecursivePattern.DeclaredType?.Type ?? boundRecursivePattern.InputType.StrippedType()).GetPublicSymbol(); ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundRecursivePattern.Deconstruction is { IsDefault: false } deconstructions ? deconstructions.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; ImmutableArray<IPropertySubpatternOperation> propertySubpatterns = boundRecursivePattern.Properties is { IsDefault: false } properties ? properties.SelectAsArray((p, arg) => arg.Fac.CreatePropertySubpattern(p, arg.MatchedType), (Fac: this, MatchedType: matchedType)) : ImmutableArray<IPropertySubpatternOperation>.Empty; return new RecursivePatternOperation( matchedType, boundRecursivePattern.DeconstructMethod.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns, boundRecursivePattern.Variable.GetPublicSymbol(), boundRecursivePattern.InputType.GetPublicSymbol(), boundRecursivePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundRecursivePattern.Syntax, isImplicit: boundRecursivePattern.WasCompilerGenerated); } private IRecursivePatternOperation CreateBoundRecursivePatternOperation(BoundITuplePattern boundITuplePattern) { ImmutableArray<IPatternOperation> deconstructionSubpatterns = boundITuplePattern.Subpatterns is { IsDefault: false } subpatterns ? subpatterns.SelectAsArray((p, fac) => (IPatternOperation)fac.Create(p.Pattern), this) : ImmutableArray<IPatternOperation>.Empty; return new RecursivePatternOperation( boundITuplePattern.InputType.StrippedType().GetPublicSymbol(), boundITuplePattern.GetLengthMethod.ContainingType.GetPublicSymbol(), deconstructionSubpatterns, propertySubpatterns: ImmutableArray<IPropertySubpatternOperation>.Empty, declaredSymbol: null, boundITuplePattern.InputType.GetPublicSymbol(), boundITuplePattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundITuplePattern.Syntax, isImplicit: boundITuplePattern.WasCompilerGenerated); } private IOperation CreateBoundTypePatternOperation(BoundTypePattern boundTypePattern) { return new TypePatternOperation( matchedType: boundTypePattern.NarrowedType.GetPublicSymbol(), inputType: boundTypePattern.InputType.GetPublicSymbol(), narrowedType: boundTypePattern.NarrowedType.GetPublicSymbol(), semanticModel: _semanticModel, syntax: boundTypePattern.Syntax, isImplicit: boundTypePattern.WasCompilerGenerated); } private IOperation CreateBoundNegatedPatternOperation(BoundNegatedPattern boundNegatedPattern) { return new NegatedPatternOperation( (IPatternOperation)Create(boundNegatedPattern.Negated), boundNegatedPattern.InputType.GetPublicSymbol(), boundNegatedPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundNegatedPattern.Syntax, isImplicit: boundNegatedPattern.WasCompilerGenerated); } private IOperation CreateBoundBinaryPatternOperation(BoundBinaryPattern boundBinaryPattern) { return new BinaryPatternOperation( boundBinaryPattern.Disjunction ? BinaryOperatorKind.Or : BinaryOperatorKind.And, (IPatternOperation)Create(boundBinaryPattern.Left), (IPatternOperation)Create(boundBinaryPattern.Right), boundBinaryPattern.InputType.GetPublicSymbol(), boundBinaryPattern.NarrowedType.GetPublicSymbol(), _semanticModel, boundBinaryPattern.Syntax, isImplicit: boundBinaryPattern.WasCompilerGenerated); } private ISwitchOperation CreateBoundSwitchStatementOperation(BoundSwitchStatement boundSwitchStatement) { IOperation value = Create(boundSwitchStatement.Expression); ImmutableArray<ISwitchCaseOperation> cases = CreateFromArray<BoundSwitchSection, ISwitchCaseOperation>(boundSwitchStatement.SwitchSections); ImmutableArray<ILocalSymbol> locals = boundSwitchStatement.InnerLocals.GetPublicSymbols(); ILabelSymbol exitLabel = boundSwitchStatement.BreakLabel.GetPublicSymbol(); SyntaxNode syntax = boundSwitchStatement.Syntax; bool isImplicit = boundSwitchStatement.WasCompilerGenerated; return new SwitchOperation(locals, value, cases, exitLabel, _semanticModel, syntax, isImplicit); } private ISwitchCaseOperation CreateBoundSwitchSectionOperation(BoundSwitchSection boundSwitchSection) { ImmutableArray<ICaseClauseOperation> clauses = CreateFromArray<BoundSwitchLabel, ICaseClauseOperation>(boundSwitchSection.SwitchLabels); ImmutableArray<IOperation> body = CreateFromArray<BoundStatement, IOperation>(boundSwitchSection.Statements); ImmutableArray<ILocalSymbol> locals = boundSwitchSection.Locals.GetPublicSymbols(); return new SwitchCaseOperation(clauses, body, locals, condition: null, _semanticModel, boundSwitchSection.Syntax, isImplicit: boundSwitchSection.WasCompilerGenerated); } private ISwitchExpressionOperation CreateBoundSwitchExpressionOperation(BoundConvertedSwitchExpression boundSwitchExpression) { IOperation value = Create(boundSwitchExpression.Expression); ImmutableArray<ISwitchExpressionArmOperation> arms = CreateFromArray<BoundSwitchExpressionArm, ISwitchExpressionArmOperation>(boundSwitchExpression.SwitchArms); bool isExhaustive; if (boundSwitchExpression.DefaultLabel != null) { Debug.Assert(boundSwitchExpression.DefaultLabel is GeneratedLabelSymbol); isExhaustive = false; } else { isExhaustive = true; } return new SwitchExpressionOperation( value, arms, isExhaustive, _semanticModel, boundSwitchExpression.Syntax, boundSwitchExpression.GetPublicTypeSymbol(), boundSwitchExpression.WasCompilerGenerated); } private ISwitchExpressionArmOperation CreateBoundSwitchExpressionArmOperation(BoundSwitchExpressionArm boundSwitchExpressionArm) { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchExpressionArm.Pattern); IOperation? guard = Create(boundSwitchExpressionArm.WhenClause); IOperation value = Create(boundSwitchExpressionArm.Value); return new SwitchExpressionArmOperation( pattern, guard, value, boundSwitchExpressionArm.Locals.GetPublicSymbols(), _semanticModel, boundSwitchExpressionArm.Syntax, boundSwitchExpressionArm.WasCompilerGenerated); } private ICaseClauseOperation CreateBoundSwitchLabelOperation(BoundSwitchLabel boundSwitchLabel) { SyntaxNode syntax = boundSwitchLabel.Syntax; bool isImplicit = boundSwitchLabel.WasCompilerGenerated; LabelSymbol label = boundSwitchLabel.Label; if (boundSwitchLabel.Syntax.Kind() == SyntaxKind.DefaultSwitchLabel) { Debug.Assert(boundSwitchLabel.Pattern.Kind == BoundKind.DiscardPattern); return new DefaultCaseClauseOperation(label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else if (boundSwitchLabel.WhenClause == null && boundSwitchLabel.Pattern.Kind == BoundKind.ConstantPattern && boundSwitchLabel.Pattern is BoundConstantPattern cp && cp.InputType.IsValidV6SwitchGoverningType()) { return new SingleValueCaseClauseOperation(Create(cp.Value), label.GetPublicSymbol(), _semanticModel, syntax, isImplicit); } else { IPatternOperation pattern = (IPatternOperation)Create(boundSwitchLabel.Pattern); IOperation? guard = Create(boundSwitchLabel.WhenClause); return new PatternCaseClauseOperation(label.GetPublicSymbol(), pattern, guard, _semanticModel, syntax, isImplicit); } } private IIsPatternOperation CreateBoundIsPatternExpressionOperation(BoundIsPatternExpression boundIsPatternExpression) { IOperation value = Create(boundIsPatternExpression.Expression); IPatternOperation pattern = (IPatternOperation)Create(boundIsPatternExpression.Pattern); SyntaxNode syntax = boundIsPatternExpression.Syntax; ITypeSymbol? type = boundIsPatternExpression.GetPublicTypeSymbol(); bool isImplicit = boundIsPatternExpression.WasCompilerGenerated; return new IsPatternOperation(value, pattern, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundQueryClauseOperation(BoundQueryClause boundQueryClause) { if (boundQueryClause.Syntax.Kind() != SyntaxKind.QueryExpression) { // Currently we have no IOperation APIs for different query clauses or continuation. return Create(boundQueryClause.Value); } IOperation operation = Create(boundQueryClause.Value); SyntaxNode syntax = boundQueryClause.Syntax; ITypeSymbol? type = boundQueryClause.GetPublicTypeSymbol(); bool isImplicit = boundQueryClause.WasCompilerGenerated; return new TranslatedQueryOperation(operation, _semanticModel, syntax, type, isImplicit); } private IOperation CreateBoundRangeVariableOperation(BoundRangeVariable boundRangeVariable) { // We do not have operation nodes for the bound range variables, just it's value. return Create(boundRangeVariable.Value); } private IOperation CreateBoundDiscardExpressionOperation(BoundDiscardExpression boundNode) { return new DiscardOperation( ((DiscardSymbol)boundNode.ExpressionSymbol).GetPublicSymbol(), _semanticModel, boundNode.Syntax, boundNode.GetPublicTypeSymbol(), isImplicit: boundNode.WasCompilerGenerated); } private IOperation CreateFromEndIndexExpressionOperation(BoundFromEndIndexExpression boundIndex) { return new UnaryOperation( UnaryOperatorKind.Hat, Create(boundIndex.Operand), isLifted: boundIndex.Type.IsNullableType(), isChecked: false, operatorMethod: null, _semanticModel, boundIndex.Syntax, boundIndex.GetPublicTypeSymbol(), constantValue: null, isImplicit: boundIndex.WasCompilerGenerated); } private IOperation CreateRangeExpressionOperation(BoundRangeExpression boundRange) { IOperation? left = Create(boundRange.LeftOperandOpt); IOperation? right = Create(boundRange.RightOperandOpt); return new RangeOperation( left, right, isLifted: boundRange.Type.IsNullableType(), boundRange.MethodOpt.GetPublicSymbol(), _semanticModel, boundRange.Syntax, boundRange.GetPublicTypeSymbol(), isImplicit: boundRange.WasCompilerGenerated); } private IOperation CreateBoundDiscardPatternOperation(BoundDiscardPattern boundNode) { return new DiscardPatternOperation( inputType: boundNode.InputType.GetPublicSymbol(), narrowedType: boundNode.NarrowedType.GetPublicSymbol(), _semanticModel, boundNode.Syntax, isImplicit: boundNode.WasCompilerGenerated); } internal IPropertySubpatternOperation CreatePropertySubpattern(BoundPropertySubpattern subpattern, ITypeSymbol matchedType) { // We treat `c is { ... .Prop: <pattern> }` as `c is { ...: { Prop: <pattern> } }` SyntaxNode subpatternSyntax = subpattern.Syntax; BoundPropertySubpatternMember? member = subpattern.Member; IPatternOperation pattern = (IPatternOperation)Create(subpattern.Pattern); if (member is null) { var reference = OperationFactory.CreateInvalidOperation(_semanticModel, subpatternSyntax, ImmutableArray<IOperation>.Empty, isImplicit: true); return new PropertySubpatternOperation(reference, pattern, _semanticModel, subpatternSyntax, isImplicit: false); } // Create an operation for last property access: // `{ SingleProp: <pattern operation> }` // or // `.LastProp: <pattern operation>` portion (treated as `{ LastProp: <pattern operation> }`) var nameSyntax = member.Syntax; var inputType = getInputType(member, matchedType); IPropertySubpatternOperation? result = createPropertySubpattern(member.Symbol, pattern, inputType, nameSyntax, isSingle: member.Receiver is null); while (member.Receiver is not null) { member = member.Receiver; nameSyntax = member.Syntax; ITypeSymbol previousType = inputType; inputType = getInputType(member, matchedType); // Create an operation for a preceding property access: // { PrecedingProp: <previous pattern operation> } IPatternOperation nestedPattern = new RecursivePatternOperation( matchedType: previousType, deconstructSymbol: null, deconstructionSubpatterns: ImmutableArray<IPatternOperation>.Empty, propertySubpatterns: ImmutableArray.Create(result), declaredSymbol: null, previousType, narrowedType: previousType, semanticModel: _semanticModel, nameSyntax, isImplicit: true); result = createPropertySubpattern(member.Symbol, nestedPattern, inputType, nameSyntax, isSingle: false); } return result; IPropertySubpatternOperation createPropertySubpattern(Symbol? symbol, IPatternOperation pattern, ITypeSymbol receiverType, SyntaxNode nameSyntax, bool isSingle) { Debug.Assert(nameSyntax is not null); IOperation reference; switch (symbol) { case FieldSymbol field: { var constantValue = field.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false); reference = new FieldReferenceOperation(field.GetPublicSymbol(), isDeclaration: false, createReceiver(), _semanticModel, nameSyntax, type: field.Type.GetPublicSymbol(), constantValue, isImplicit: false); break; } case PropertySymbol property: { reference = new PropertyReferenceOperation(property.GetPublicSymbol(), ImmutableArray<IArgumentOperation>.Empty, createReceiver(), _semanticModel, nameSyntax, type: property.Type.GetPublicSymbol(), isImplicit: false); break; } default: { // We should expose the symbol in this case somehow: // https://github.com/dotnet/roslyn/issues/33175 reference = OperationFactory.CreateInvalidOperation(_semanticModel, nameSyntax, ImmutableArray<IOperation>.Empty, isImplicit: false); break; } } var syntaxForPropertySubpattern = isSingle ? subpatternSyntax : nameSyntax; return new PropertySubpatternOperation(reference, pattern, _semanticModel, syntaxForPropertySubpattern, isImplicit: !isSingle); IOperation? createReceiver() => symbol?.IsStatic == false ? new InstanceReferenceOperation(InstanceReferenceKind.PatternInput, _semanticModel, nameSyntax!, receiverType, isImplicit: true) : null; } static ITypeSymbol getInputType(BoundPropertySubpatternMember member, ITypeSymbol matchedType) => member.Receiver?.Type.StrippedType().GetPublicSymbol() ?? matchedType; } private IInstanceReferenceOperation CreateCollectionValuePlaceholderOperation(BoundObjectOrCollectionValuePlaceholder placeholder) { InstanceReferenceKind referenceKind = InstanceReferenceKind.ImplicitReceiver; SyntaxNode syntax = placeholder.Syntax; ITypeSymbol? type = placeholder.GetPublicTypeSymbol(); bool isImplicit = placeholder.WasCompilerGenerated; return new InstanceReferenceOperation(referenceKind, _semanticModel, syntax, type, isImplicit); } private ImmutableArray<IArgumentOperation> CreateDisposeArguments(MethodArgumentInfo patternDisposeInfo, SyntaxNode syntax) { // can't be an extension method for dispose Debug.Assert(!patternDisposeInfo.Method.IsStatic); if (patternDisposeInfo.Method.ParameterCount == 0) { return ImmutableArray<IArgumentOperation>.Empty; } Debug.Assert(!patternDisposeInfo.Expanded || patternDisposeInfo.Method.GetParameters().Last().OriginalDefinition.Type.IsSZArray()); var args = DeriveArguments( patternDisposeInfo.Method, patternDisposeInfo.Arguments, patternDisposeInfo.ArgsToParamsOpt, patternDisposeInfo.DefaultArguments, patternDisposeInfo.Expanded, syntax, invokedAsExtensionMethod: false); return Operation.SetParentOperation(args, null); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/LanguageServices/SyntaxFactsService/ISyntaxKindsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Provides a uniform view of SyntaxKinds over C# and VB for constructs they have /// in common. /// </summary> internal partial interface ISyntaxKindsService : ISyntaxKinds, ILanguageService { } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.LanguageServices { /// <summary> /// Provides a uniform view of SyntaxKinds over C# and VB for constructs they have /// in common. /// </summary> internal partial interface ISyntaxKindsService : ISyntaxKinds, ILanguageService { } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/Core/Impl/SolutionExplorer/AnalyzersFolderItem/AnalyzersFolderItemSourceProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { using Workspace = Microsoft.CodeAnalysis.Workspace; [Export(typeof(IAttachedCollectionSourceProvider))] [Name(nameof(AnalyzersFolderItemSourceProvider))] [Order(Before = HierarchyItemsProviderNames.Contains)] [AppliesToProject("(CSharp | VB) & !CPS")] // in the CPS case, the Analyzers folder is created by the project system internal class AnalyzersFolderItemSourceProvider : AttachedCollectionSourceProvider<IVsHierarchyItem> { private readonly IAnalyzersCommandHandler _commandHandler; private IHierarchyItemToProjectIdMap? _projectMap; private readonly Workspace _workspace; [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] [ImportingConstructor] public AnalyzersFolderItemSourceProvider( VisualStudioWorkspace workspace, [Import(typeof(AnalyzersCommandHandler))] IAnalyzersCommandHandler commandHandler) { _workspace = workspace; _commandHandler = commandHandler; } protected override IAttachedCollectionSource? CreateCollectionSource(IVsHierarchyItem item, string relationshipName) { if (item != null && item.HierarchyIdentity != null && item.HierarchyIdentity.NestedHierarchy != null && relationshipName == KnownRelationships.Contains) { var hierarchy = item.HierarchyIdentity.NestedHierarchy; var itemId = item.HierarchyIdentity.NestedItemID; var projectTreeCapabilities = GetProjectTreeCapabilities(hierarchy, itemId); if (projectTreeCapabilities.Any(c => c.Equals("References"))) { var hierarchyMapper = TryGetProjectMap(); if (hierarchyMapper != null && hierarchyMapper.TryGetProjectId(item.Parent, targetFrameworkMoniker: null, projectId: out var projectId)) { return new AnalyzersFolderItemSource(_workspace, projectId, item, _commandHandler); } return null; } } return null; } private static ImmutableArray<string> GetProjectTreeCapabilities(IVsHierarchy hierarchy, uint itemId) { if (hierarchy.GetProperty(itemId, (int)__VSHPROPID7.VSHPROPID_ProjectTreeCapabilities, out var capabilitiesObj) == VSConstants.S_OK) { var capabilitiesString = (string)capabilitiesObj; return ImmutableArray.Create(capabilitiesString.Split(' ')); } else { return ImmutableArray<string>.Empty; } } private IHierarchyItemToProjectIdMap? TryGetProjectMap() { if (_projectMap == null) { _projectMap = _workspace.Services.GetService<IHierarchyItemToProjectIdMap>(); } return _projectMap; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { using Workspace = Microsoft.CodeAnalysis.Workspace; [Export(typeof(IAttachedCollectionSourceProvider))] [Name(nameof(AnalyzersFolderItemSourceProvider))] [Order(Before = HierarchyItemsProviderNames.Contains)] [AppliesToProject("(CSharp | VB) & !CPS")] // in the CPS case, the Analyzers folder is created by the project system internal class AnalyzersFolderItemSourceProvider : AttachedCollectionSourceProvider<IVsHierarchyItem> { private readonly IAnalyzersCommandHandler _commandHandler; private IHierarchyItemToProjectIdMap? _projectMap; private readonly Workspace _workspace; [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] [ImportingConstructor] public AnalyzersFolderItemSourceProvider( VisualStudioWorkspace workspace, [Import(typeof(AnalyzersCommandHandler))] IAnalyzersCommandHandler commandHandler) { _workspace = workspace; _commandHandler = commandHandler; } protected override IAttachedCollectionSource? CreateCollectionSource(IVsHierarchyItem item, string relationshipName) { if (item != null && item.HierarchyIdentity != null && item.HierarchyIdentity.NestedHierarchy != null && relationshipName == KnownRelationships.Contains) { var hierarchy = item.HierarchyIdentity.NestedHierarchy; var itemId = item.HierarchyIdentity.NestedItemID; var projectTreeCapabilities = GetProjectTreeCapabilities(hierarchy, itemId); if (projectTreeCapabilities.Any(c => c.Equals("References"))) { var hierarchyMapper = TryGetProjectMap(); if (hierarchyMapper != null && hierarchyMapper.TryGetProjectId(item.Parent, targetFrameworkMoniker: null, projectId: out var projectId)) { return new AnalyzersFolderItemSource(_workspace, projectId, item, _commandHandler); } return null; } } return null; } private static ImmutableArray<string> GetProjectTreeCapabilities(IVsHierarchy hierarchy, uint itemId) { if (hierarchy.GetProperty(itemId, (int)__VSHPROPID7.VSHPROPID_ProjectTreeCapabilities, out var capabilitiesObj) == VSConstants.S_OK) { var capabilitiesString = (string)capabilitiesObj; return ImmutableArray.Create(capabilitiesString.Split(' ')); } else { return ImmutableArray<string>.Empty; } } private IHierarchyItemToProjectIdMap? TryGetProjectMap() { if (_projectMap == null) { _projectMap = _workspace.Services.GetService<IHierarchyItemToProjectIdMap>(); } return _projectMap; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/Xaml/Impl/Features/Formatting/IXamlFormattingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting { internal interface IXamlFormattingService : ILanguageService { Task<IList<TextChange>> GetFormattingChangesAsync(TextDocument document, XamlFormattingOptions options, TextSpan? textSpan, CancellationToken cancellationToken); Task<IList<TextChange>> GetFormattingChangesAsync(TextDocument document, XamlFormattingOptions options, char typedChar, int position, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.VisualStudio.LanguageServices.Xaml.Features.Formatting { internal interface IXamlFormattingService : ILanguageService { Task<IList<TextChange>> GetFormattingChangesAsync(TextDocument document, XamlFormattingOptions options, TextSpan? textSpan, CancellationToken cancellationToken); Task<IList<TextChange>> GetFormattingChangesAsync(TextDocument document, XamlFormattingOptions options, char typedChar, int position, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/XmlCommentHighlighter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlCommentHighlighter Inherits AbstractKeywordHighlighter(Of XmlCommentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub addHighlights(xmlComment As XmlCommentSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) With xmlComment If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.LessThanExclamationMinusMinusToken.Span) highlights.Add(.MinusMinusGreaterThanToken.Span) End If End With End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting <ExportHighlighter(LanguageNames.VisualBasic)> Friend Class XmlCommentHighlighter Inherits AbstractKeywordHighlighter(Of XmlCommentSyntax) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overloads Overrides Sub addHighlights(xmlComment As XmlCommentSyntax, highlights As List(Of TextSpan), cancellationToken As CancellationToken) With xmlComment If Not .ContainsDiagnostics AndAlso Not .HasAncestor(Of DocumentationCommentTriviaSyntax)() Then highlights.Add(.LessThanExclamationMinusMinusToken.Span) highlights.Add(.MinusMinusGreaterThanToken.Span) End If End With End Sub End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/VisualBasic/Portable/Operations/VisualBasicOperationFactory_Methods.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.AnonymousTypeManager Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Operations Partial Friend NotInheritable Class VisualBasicOperationFactory Private Shared Function IsMidStatement(node As BoundNode) As Boolean If node.Kind = BoundKind.Conversion Then node = DirectCast(node, BoundConversion).Operand If node.Kind = BoundKind.UserDefinedConversion Then node = DirectCast(node, BoundUserDefinedConversion).Operand End If End If Return node.Kind = BoundKind.MidResult End Function Friend Function CreateCompoundAssignmentRightOperand(boundAssignment As BoundAssignmentOperator) As IOperation Dim binaryOperator As BoundExpression = Nothing Select Case boundAssignment.Right.Kind Case BoundKind.Conversion Dim inConversionNode = DirectCast(boundAssignment.Right, BoundConversion) binaryOperator = GetConversionOperand(inConversionNode) Case BoundKind.UserDefinedBinaryOperator, BoundKind.BinaryOperator binaryOperator = boundAssignment.Right Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select Dim operatorInfo As BinaryOperatorInfo Select Case binaryOperator.Kind Case BoundKind.BinaryOperator operatorInfo = GetBinaryOperatorInfo(DirectCast(binaryOperator, BoundBinaryOperator)) Return Create(operatorInfo.RightOperand) Case BoundKind.UserDefinedBinaryOperator Dim userDefinedOperator = DirectCast(binaryOperator, BoundUserDefinedBinaryOperator) operatorInfo = GetUserDefinedBinaryOperatorInfo(userDefinedOperator) Return GetUserDefinedBinaryOperatorChild(userDefinedOperator, operatorInfo.RightOperand) Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select End Function Private Function CreateCompoundAssignment(boundAssignment As BoundAssignmentOperator) As ICompoundAssignmentOperation Debug.Assert(boundAssignment.LeftOnTheRightOpt IsNot Nothing) Dim inConversion = New Conversion(Conversions.Identity) Dim outConversion As Conversion = inConversion Dim binaryOperator As BoundExpression = Nothing Select Case boundAssignment.Right.Kind Case BoundKind.Conversion Dim inConversionNode = DirectCast(boundAssignment.Right, BoundConversion) outConversion = CreateConversion(inConversionNode) binaryOperator = GetConversionOperand(inConversionNode) Case BoundKind.UserDefinedBinaryOperator, BoundKind.BinaryOperator binaryOperator = boundAssignment.Right Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select Dim operatorInfo As BinaryOperatorInfo Select Case binaryOperator.Kind Case BoundKind.BinaryOperator operatorInfo = GetBinaryOperatorInfo(DirectCast(binaryOperator, BoundBinaryOperator)) Case BoundKind.UserDefinedBinaryOperator Dim userDefinedOperator = DirectCast(binaryOperator, BoundUserDefinedBinaryOperator) operatorInfo = GetUserDefinedBinaryOperatorInfo(userDefinedOperator) Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select Dim leftOnTheRight As BoundExpression = operatorInfo.LeftOperand If leftOnTheRight.Kind = BoundKind.Conversion Then Dim outConversionNode = DirectCast(leftOnTheRight, BoundConversion) inConversion = CreateConversion(outConversionNode) leftOnTheRight = GetConversionOperand(outConversionNode) End If Debug.Assert(leftOnTheRight Is boundAssignment.LeftOnTheRightOpt) Dim target As IOperation = Create(boundAssignment.Left) Dim value As IOperation = CreateCompoundAssignmentRightOperand(boundAssignment) Dim syntax As SyntaxNode = boundAssignment.Syntax Dim type As ITypeSymbol = boundAssignment.Type Dim isImplicit As Boolean = boundAssignment.WasCompilerGenerated Return New CompoundAssignmentOperation(inConversion, outConversion, operatorInfo.OperatorKind, operatorInfo.IsLifted, operatorInfo.IsChecked, operatorInfo.OperatorMethod, target, value, _semanticModel, syntax, type, isImplicit) End Function Private Structure BinaryOperatorInfo Public Sub New(leftOperand As BoundExpression, rightOperand As BoundExpression, binaryOperatorKind As BinaryOperatorKind, operatorMethod As MethodSymbol, isLifted As Boolean, isChecked As Boolean, isCompareText As Boolean) Me.LeftOperand = leftOperand Me.RightOperand = rightOperand Me.OperatorKind = binaryOperatorKind Me.OperatorMethod = operatorMethod Me.IsLifted = isLifted Me.IsChecked = isChecked Me.IsCompareText = isCompareText End Sub Public ReadOnly LeftOperand As BoundExpression Public ReadOnly RightOperand As BoundExpression Public ReadOnly OperatorKind As BinaryOperatorKind Public ReadOnly OperatorMethod As MethodSymbol Public ReadOnly IsLifted As Boolean Public ReadOnly IsChecked As Boolean Public ReadOnly IsCompareText As Boolean End Structure Private Shared Function GetBinaryOperatorInfo(boundBinaryOperator As BoundBinaryOperator) As BinaryOperatorInfo Return New BinaryOperatorInfo( leftOperand:=boundBinaryOperator.Left, rightOperand:=boundBinaryOperator.Right, binaryOperatorKind:=Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind, boundBinaryOperator.Left), operatorMethod:=Nothing, isLifted:=(boundBinaryOperator.OperatorKind And VisualBasic.BinaryOperatorKind.Lifted) <> 0, isChecked:=boundBinaryOperator.Checked, isCompareText:=(boundBinaryOperator.OperatorKind And VisualBasic.BinaryOperatorKind.CompareText) <> 0) End Function Private Shared Function GetUserDefinedBinaryOperatorInfo(boundUserDefinedBinaryOperator As BoundUserDefinedBinaryOperator) As BinaryOperatorInfo Return New BinaryOperatorInfo( leftOperand:=GetUserDefinedBinaryOperatorChildBoundNode(boundUserDefinedBinaryOperator, 0), rightOperand:=GetUserDefinedBinaryOperatorChildBoundNode(boundUserDefinedBinaryOperator, 1), binaryOperatorKind:=Helper.DeriveBinaryOperatorKind(boundUserDefinedBinaryOperator.OperatorKind, leftOpt:=Nothing), operatorMethod:=If(boundUserDefinedBinaryOperator.UnderlyingExpression.Kind = BoundKind.Call, boundUserDefinedBinaryOperator.Call.Method, Nothing), isLifted:=(boundUserDefinedBinaryOperator.OperatorKind And VisualBasic.BinaryOperatorKind.Lifted) <> 0, isChecked:=boundUserDefinedBinaryOperator.Checked, isCompareText:=False) End Function Private Function GetUserDefinedBinaryOperatorChild([operator] As BoundUserDefinedBinaryOperator, child As BoundExpression) As IOperation If child IsNot Nothing Then Return Create(child) End If Dim isImplicit As Boolean = [operator].UnderlyingExpression.WasCompilerGenerated Return OperationFactory.CreateInvalidOperation(_semanticModel, [operator].UnderlyingExpression.Syntax, ImmutableArray(Of IOperation).Empty, isImplicit) End Function Private Shared Function GetUserDefinedBinaryOperatorChildBoundNode([operator] As BoundUserDefinedBinaryOperator, index As Integer) As BoundExpression If [operator].UnderlyingExpression.Kind = BoundKind.Call Then If index = 0 Then Return [operator].Left ElseIf index = 1 Then Return [operator].Right Else Throw ExceptionUtilities.UnexpectedValue(index) End If End If Return GetChildOfBadExpressionBoundNode([operator].UnderlyingExpression, index) End Function Friend Function DeriveArguments(boundNode As BoundNode) As ImmutableArray(Of IArgumentOperation) Select Case boundNode.Kind Case BoundKind.Call Dim boundCall = DirectCast(boundNode, BoundCall) Return DeriveArguments(boundCall.Arguments, boundCall.Method.Parameters, boundCall.DefaultArguments) Case BoundKind.ObjectCreationExpression Dim boundCreation = DirectCast(boundNode, BoundObjectCreationExpression) If boundCreation.Arguments.IsDefault Then Return ImmutableArray(Of IArgumentOperation).Empty End If Return If(boundCreation.ConstructorOpt Is Nothing, ImmutableArray(Of IArgumentOperation).Empty, DeriveArguments(boundCreation.Arguments, boundCreation.ConstructorOpt.Parameters, boundCreation.DefaultArguments)) Case BoundKind.PropertyAccess Dim boundProperty = DirectCast(boundNode, BoundPropertyAccess) Return If(boundProperty.Arguments.Length = 0, ImmutableArray(Of IArgumentOperation).Empty, DeriveArguments(boundProperty.Arguments, boundProperty.PropertySymbol.Parameters, boundProperty.DefaultArguments)) Case BoundKind.RaiseEventStatement Dim boundRaiseEvent = DirectCast(boundNode, BoundRaiseEventStatement) Return DeriveArguments(DirectCast(boundRaiseEvent.EventInvocation, BoundCall)) Case Else Throw ExceptionUtilities.UnexpectedValue(boundNode.Kind) End Select End Function Friend Function DeriveArguments(boundArguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of VisualBasic.Symbols.ParameterSymbol), ByRef defaultArguments As BitVector) As ImmutableArray(Of IArgumentOperation) Dim argumentsLength As Integer = boundArguments.Length Debug.Assert(argumentsLength = parameters.Length) Dim arguments As ArrayBuilder(Of IArgumentOperation) = ArrayBuilder(Of IArgumentOperation).GetInstance(argumentsLength) For index As Integer = 0 To argumentsLength - 1 Step 1 arguments.Add(DeriveArgument(index, boundArguments(index), parameters, defaultArguments(index))) Next Return arguments.ToImmutableAndFree() End Function Private Function DeriveArgument( index As Integer, argument As BoundExpression, parameters As ImmutableArray(Of VisualBasic.Symbols.ParameterSymbol), isDefault As Boolean ) As IArgumentOperation Dim isImplicit As Boolean = argument.WasCompilerGenerated AndAlso argument.Syntax.Kind <> SyntaxKind.OmittedArgument Select Case argument.Kind Case BoundKind.ByRefArgumentWithCopyBack Dim byRefArgument = DirectCast(argument, BoundByRefArgumentWithCopyBack) Dim parameter = parameters(index) Return CreateArgumentOperation( ArgumentKind.Explicit, parameter, byRefArgument.OriginalArgument, CreateConversion(byRefArgument.InConversion), CreateConversion(byRefArgument.OutConversion), isImplicit) Case Else Dim lastParameterIndex = parameters.Length - 1 Dim kind As ArgumentKind = ArgumentKind.Explicit If argument.WasCompilerGenerated Then If isDefault Then kind = ArgumentKind.DefaultValue ElseIf argument.Kind = BoundKind.ArrayCreation AndAlso DirectCast(argument, BoundArrayCreation).IsParamArrayArgument Then kind = ArgumentKind.ParamArray End If End If Return CreateArgumentOperation( kind, parameters(index), argument, New Conversion(Conversions.Identity), New Conversion(Conversions.Identity), isImplicit) End Select End Function Private Function CreateArgumentOperation( kind As ArgumentKind, parameter As IParameterSymbol, valueNode As BoundNode, inConversion As Conversion, outConversion As Conversion, isImplicit As Boolean) As IArgumentOperation ' put argument syntax to argument operation Dim syntax = If(valueNode.Syntax.Kind = SyntaxKind.OmittedArgument, valueNode.Syntax, TryCast(valueNode.Syntax?.Parent, ArgumentSyntax)) Dim value = Create(valueNode) If syntax Is Nothing Then syntax = value.Syntax isImplicit = True End If Return New ArgumentOperation( kind, parameter, value, inConversion, outConversion, _semanticModel, syntax, isImplicit) End Function Friend Function CreateReceiverOperation(node As BoundNode, symbol As ISymbol) As IOperation If node Is Nothing OrElse node.Kind = BoundKind.TypeExpression Then Return Nothing End If If symbol IsNot Nothing AndAlso node.WasCompilerGenerated AndAlso symbol.IsStatic AndAlso (node.Kind = BoundKind.MeReference OrElse node.Kind = BoundKind.WithLValueExpressionPlaceholder OrElse node.Kind = BoundKind.WithRValueExpressionPlaceholder) Then Return Nothing End If Return Create(node) End Function Private Shared Function ParameterIsParamArray(parameter As VisualBasic.Symbols.ParameterSymbol) As Boolean Return If(parameter.IsParamArray AndAlso parameter.Type.Kind = SymbolKind.ArrayType, DirectCast(parameter.Type, VisualBasic.Symbols.ArrayTypeSymbol).IsSZArray, False) End Function Private Function GetChildOfBadExpression(parent As BoundNode, index As Integer) As IOperation Dim child = Create(GetChildOfBadExpressionBoundNode(parent, index)) If child IsNot Nothing Then Return child End If Dim isImplicit As Boolean = parent.WasCompilerGenerated Return OperationFactory.CreateInvalidOperation(_semanticModel, parent.Syntax, ImmutableArray(Of IOperation).Empty, isImplicit) End Function Private Shared Function GetChildOfBadExpressionBoundNode(parent As BoundNode, index As Integer) As BoundExpression Dim badParent As BoundBadExpression = TryCast(parent, BoundBadExpression) If badParent?.ChildBoundNodes.Length > index Then Return badParent.ChildBoundNodes(index) End If Return Nothing End Function Private Function GetObjectCreationInitializers(expression As BoundObjectCreationExpression) As ImmutableArray(Of IOperation) Return If(expression.InitializerOpt IsNot Nothing, expression.InitializerOpt.Initializers.SelectAsArray(Function(n) Create(n)), ImmutableArray(Of IOperation).Empty) End Function Friend Function GetAnonymousTypeCreationInitializers(expression As BoundAnonymousTypeCreationExpression) As ImmutableArray(Of IOperation) ' For error cases and non-assignment initializers, the binder generates only the argument. Debug.Assert(expression.Arguments.Length >= expression.Declarations.Length) Dim properties = DirectCast(expression.Type, AnonymousTypePublicSymbol).Properties Debug.Assert(properties.Length = expression.Arguments.Length) Dim builder = ArrayBuilder(Of IOperation).GetInstance(expression.Arguments.Length) Dim currentDeclarationIndex = 0 For i As Integer = 0 To expression.Arguments.Length - 1 Dim value As IOperation = Create(expression.Arguments(i)) Dim target As IOperation Dim isImplicitAssignment As Boolean ' Find matching declaration for the current argument If currentDeclarationIndex >= expression.Declarations.Length OrElse i <> expression.Declarations(currentDeclarationIndex).PropertyIndex Then ' No matching declaration, synthesize a property reference with an implicit receiver to be assigned. Dim [property] As IPropertySymbol = properties(i) Dim instance As IInstanceReferenceOperation = CreateAnonymousTypePropertyAccessImplicitReceiverOperation([property], expression.Syntax) target = New PropertyReferenceOperation( [property], ImmutableArray(Of IArgumentOperation).Empty, instance, _semanticModel, value.Syntax, [property].Type, isImplicit:=True) isImplicitAssignment = True Else Debug.Assert(i = expression.Declarations(currentDeclarationIndex).PropertyIndex) target = CreateBoundAnonymousTypePropertyAccessOperation(expression.Declarations(currentDeclarationIndex)) currentDeclarationIndex = currentDeclarationIndex + 1 isImplicitAssignment = expression.WasCompilerGenerated End If Dim isRef As Boolean = False Dim syntax As SyntaxNode = If(value.Syntax?.Parent, expression.Syntax) Dim type As ITypeSymbol = target.Type Dim constantValue As ConstantValue = value.GetConstantValue() Dim assignment = New SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicitAssignment) builder.Add(assignment) Next i Debug.Assert(currentDeclarationIndex = expression.Declarations.Length) Return builder.ToImmutableAndFree() End Function Private Shared Function GetSingleValueCaseClauseValue(clause As BoundSingleValueCaseClause) As BoundExpression Return GetCaseClauseValue(clause.ValueOpt, clause.ConditionOpt) End Function Friend Shared Function GetCaseClauseValue(valueOpt As BoundExpression, conditionOpt As BoundExpression) As BoundExpression If valueOpt IsNot Nothing Then Return valueOpt End If Select Case conditionOpt.Kind Case BoundKind.BinaryOperator Dim binaryOp As BoundBinaryOperator = DirectCast(conditionOpt, BoundBinaryOperator) Return binaryOp.Right Case BoundKind.UserDefinedBinaryOperator Dim binaryOp As BoundUserDefinedBinaryOperator = DirectCast(conditionOpt, BoundUserDefinedBinaryOperator) Return GetUserDefinedBinaryOperatorChildBoundNode(binaryOp, 1) Case Else Throw ExceptionUtilities.UnexpectedValue(conditionOpt.Kind) End Select End Function Friend Function GetVariableDeclarationStatementVariables(declarations As ImmutableArray(Of BoundLocalDeclarationBase)) As ImmutableArray(Of IVariableDeclarationOperation) ' Group the declarations by their VariableDeclaratorSyntaxes. The issue we're compensating for here is that the ' the declarations that are BoundLocalDeclaration nodes have a ModifiedIdentifierSyntax as their syntax nodes, ' not a VariableDeclaratorSyntax. We want to group BoundLocalDeclarations by their parent VariableDeclaratorSyntax ' nodes, and deduplicate based on that. As an example: ' ' Dim x, y = 1 ' ' This is an error scenario, but if we just use the BoundLocalDeclaration.Syntax.Parent directly, without deduplicating, ' we'll end up with two IVariableDeclarators that have the same syntax node. So, we group by VariableDeclaratorSyntax ' to put x and y in the same IMultiVariableDeclaration Dim groupedDeclarations = declarations.GroupBy(Function(declaration) If declaration.Kind = BoundKind.LocalDeclaration AndAlso declaration.Syntax.IsKind(SyntaxKind.ModifiedIdentifier) Then Debug.Assert(declaration.Syntax.Parent.IsKind(SyntaxKind.VariableDeclarator)) Return declaration.Syntax.Parent Else Return declaration.Syntax End If End Function) Dim builder = ArrayBuilder(Of IVariableDeclarationOperation).GetInstance() For Each declarationGroup In groupedDeclarations Dim first = declarationGroup.First() Dim declarators As ImmutableArray(Of IVariableDeclaratorOperation) = Nothing Dim initializer As IVariableInitializerOperation = Nothing If first.Kind = BoundKind.LocalDeclaration Then declarators = declarationGroup.Cast(Of BoundLocalDeclaration).SelectAsArray(AddressOf GetVariableDeclarator) ' The initializer we use for this group is the initializer attached to the last declaration in this declarator, as that's ' where it will be parsed in an error case. ' Initializer is only created if it's not the array initializer for the variable. That initializer is the initializer ' of the VariableDeclarator child. Dim last = DirectCast(declarationGroup.Last(), BoundLocalDeclaration) If last.DeclarationInitializerOpt IsNot Nothing Then Debug.Assert(last.Syntax.IsKind(SyntaxKind.ModifiedIdentifier)) Dim declaratorSyntax = DirectCast(last.Syntax.Parent, VariableDeclaratorSyntax) Dim initializerSyntax As SyntaxNode = declaratorSyntax.Initializer ' As New clauses with a single variable are bound as BoundLocalDeclarations, so adjust appropriately Dim isImplicit As Boolean = False If last.InitializedByAsNew Then initializerSyntax = declaratorSyntax.AsClause ElseIf initializerSyntax Is Nothing Then ' There is no explicit syntax for the initializer, so we use the initializerValue's syntax and mark the operation as implicit. initializerSyntax = last.InitializerOpt.Syntax isImplicit = True End If Debug.Assert(last.InitializerOpt IsNot Nothing) Dim value = Create(last.InitializerOpt) initializer = New VariableInitializerOperation(locals:=ImmutableArray(Of ILocalSymbol).Empty, value, _semanticModel, initializerSyntax, isImplicit) End If Else Dim asNewDeclarations = DirectCast(first, BoundAsNewLocalDeclarations) declarators = asNewDeclarations.LocalDeclarations.SelectAsArray(AddressOf GetVariableDeclarator) Dim initializerSyntax As AsClauseSyntax = DirectCast(asNewDeclarations.Syntax, VariableDeclaratorSyntax).AsClause Dim initializerValue As IOperation = Create(asNewDeclarations.Initializer) Debug.Assert(asNewDeclarations.Initializer IsNot Nothing) Dim value = Create(asNewDeclarations.Initializer) initializer = New VariableInitializerOperation(locals:=ImmutableArray(Of ILocalSymbol).Empty, value, _semanticModel, initializerSyntax, isImplicit:=False) End If builder.Add(New VariableDeclarationOperation(declarators, initializer, ImmutableArray(Of IOperation).Empty, _semanticModel, declarationGroup.Key, isImplicit:=False)) Next Return builder.ToImmutableAndFree() End Function Private Function GetVariableDeclarator(boundLocalDeclaration As BoundLocalDeclaration) As IVariableDeclaratorOperation Dim initializer As IVariableInitializerOperation = Nothing If boundLocalDeclaration.IdentifierInitializerOpt IsNot Nothing Then Dim syntax = boundLocalDeclaration.Syntax Dim initializerValue As IOperation = Create(boundLocalDeclaration.IdentifierInitializerOpt) initializer = New VariableInitializerOperation(locals:=ImmutableArray(Of ILocalSymbol).Empty, initializerValue, _semanticModel, syntax, isImplicit:=True) End If Dim ignoredArguments = ImmutableArray(Of IOperation).Empty Return New VariableDeclaratorOperation(boundLocalDeclaration.LocalSymbol, initializer, ignoredArguments, _semanticModel, boundLocalDeclaration.Syntax, isImplicit:=boundLocalDeclaration.WasCompilerGenerated) End Function Private Function GetUsingStatementDeclaration(resourceList As ImmutableArray(Of BoundLocalDeclarationBase), syntax As SyntaxNode) As IVariableDeclarationGroupOperation Return New VariableDeclarationGroupOperation( GetVariableDeclarationStatementVariables(resourceList), _semanticModel, syntax, isImplicit:=False) ' Declaration is always explicit End Function Friend Function GetAddRemoveHandlerStatementExpression(statement As BoundAddRemoveHandlerStatement) As IOperation Dim eventReference As IOperation = Create(statement.EventAccess) Dim handlerValue As IOperation = Create(statement.Handler) Dim adds = statement.Kind = BoundKind.AddHandlerStatement Return New EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, statement.Syntax, type:=Nothing, isImplicit:=True) End Function #Region "Conversions" ''' <summary> ''' Creates the Lazy IOperation from a delegate creation operand or a bound conversion operand, handling when the conversion ''' is actually a delegate creation. ''' </summary> Private Function GetConversionInfo(boundConversion As BoundConversionOrCast ) As (Operation As IOperation, Conversion As Conversion, IsDelegateCreation As Boolean) Dim conversion = CreateConversion(boundConversion) Dim boundOperand = GetConversionOperand(boundConversion) If conversion.IsIdentity AndAlso boundConversion.ExplicitCastInCode Then Dim adjustedInfo = TryGetAdjustedConversionInfo(boundConversion, boundOperand) If adjustedInfo.Operation IsNot Nothing Then Return adjustedInfo End If End If If IsDelegateCreation(boundConversion.Syntax, boundOperand, boundConversion.Type) Then Return (CreateDelegateCreationConversionOperand(boundOperand), conversion, IsDelegateCreation:=True) Else Return (Create(boundOperand), conversion, IsDelegateCreation:=False) End If End Function Private Function TryGetAdjustedConversionInfo(topLevelConversion As BoundConversionOrCast, boundOperand As BoundExpression ) As (Operation As IOperation, Conversion As Conversion, IsDelegateCreation As Boolean) ' Dig through the bound tree to see if this is an artificial nested conversion. If so, let's erase the nested conversion. ' Artificial conversions are added on top of BoundConvertedTupleLiteral in Binder.ReclassifyTupleLiteral, or in ' ReclassifyUnboundLambdaExpression and the like. We need to use conversion information from the nested conversion ' because that is where the real conversion information is stored. If boundOperand.Kind = BoundKind.Parenthesized Then Dim adjustedInfo = TryGetAdjustedConversionInfo(topLevelConversion, DirectCast(boundOperand, BoundParenthesized).Expression) If adjustedInfo.Operation IsNot Nothing Then Return (Operation:=New ParenthesizedOperation(adjustedInfo.Operation, _semanticModel, boundOperand.Syntax, adjustedInfo.Operation.Type, boundOperand.ConstantValueOpt, boundOperand.WasCompilerGenerated), adjustedInfo.Conversion, adjustedInfo.IsDelegateCreation) End If ElseIf boundOperand.Kind = topLevelConversion.Kind Then Dim nestedConversion = DirectCast(boundOperand, BoundConversionOrCast) Dim nestedOperand As BoundExpression = GetConversionOperand(nestedConversion) If nestedConversion.Syntax Is nestedOperand.Syntax AndAlso Not TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything) AndAlso nestedConversion.ExplicitCastInCode AndAlso TypeSymbol.Equals(topLevelConversion.Type, nestedConversion.Type, TypeCompareKind.ConsiderEverything) Then Return GetConversionInfo(nestedConversion) End If ElseIf boundOperand.Syntax.IsKind(SyntaxKind.AddressOfExpression) AndAlso TypeSymbol.Equals(topLevelConversion.Type, boundOperand.Type, TypeCompareKind.ConsiderEverything) AndAlso IsDelegateCreation(topLevelConversion.Syntax, boundOperand, boundOperand.Type) Then Return (CreateDelegateCreationConversionOperand(boundOperand), Conversion:=Nothing, IsDelegateCreation:=True) End If Return Nothing End Function ''' <summary> ''' Gets the operand from a BoundConversion, compensating for if the conversion is a user-defined conversion ''' </summary> Private Shared Function GetConversionOperand(boundConversion As BoundConversionOrCast) As BoundExpression If (boundConversion.ConversionKind And ConversionKind.UserDefined) = ConversionKind.UserDefined Then Dim userDefinedConversion = DirectCast(boundConversion.Operand, BoundUserDefinedConversion) Return userDefinedConversion.Operand Else Return boundConversion.Operand End If End Function Private Function CreateDelegateCreationConversionOperand(operand As BoundExpression) As IOperation If operand.Kind = BoundKind.DelegateCreationExpression Then ' If the child is a BoundDelegateCreationExpression, we don't want to generate a nested IDelegateCreationExpression. ' So, the operand for the conversion will be the child of the BoundDelegateCreationExpression. ' We see this in this syntax: Dim x = New Action(AddressOf M2) ' This should be semantically equivalent to: Dim x = AddressOf M2 ' However, if we didn't fix this up, we would have nested IDelegateCreationExpressions here for the former case. Return CreateBoundDelegateCreationExpressionChildOperation(DirectCast(operand, BoundDelegateCreationExpression)) Else Return Create(operand) End If End Function Private Shared Function CreateConversion(expression As BoundExpression) As Conversion If expression.Kind = BoundKind.Conversion Then Dim conversion = DirectCast(expression, BoundConversion) Dim conversionKind = conversion.ConversionKind Dim method As MethodSymbol = Nothing If conversionKind.HasFlag(VisualBasic.ConversionKind.UserDefined) AndAlso conversion.Operand.Kind = BoundKind.UserDefinedConversion Then method = DirectCast(conversion.Operand, BoundUserDefinedConversion).Call.Method End If Return New Conversion(KeyValuePairUtil.Create(conversionKind, method)) ElseIf expression.Kind = BoundKind.TryCast OrElse expression.Kind = BoundKind.DirectCast Then Return New Conversion(KeyValuePairUtil.Create(Of ConversionKind, MethodSymbol)(DirectCast(expression, BoundConversionOrCast).ConversionKind, Nothing)) End If Return New Conversion(Conversions.Identity) End Function Private Shared Function IsDelegateCreation(conversionSyntax As SyntaxNode, operand As BoundNode, targetType As TypeSymbol) As Boolean If Not targetType.IsDelegateType() Then Return False End If ' Any of the explicit cast types, as well as New DelegateType(AddressOf Method) ' Additionally, AddressOf, if the child AddressOf is the same SyntaxNode (ie, an implicit delegate creation) ' In the case of AddressOf, the operand can be a BoundDelegateCreationExpression, a BoundAddressOfOperator, or ' a BoundBadExpression. For simplicity, we just do a syntax check to make sure it's an AddressOfExpression so ' we don't have to compare against all 3 BoundKinds Dim validAddressOfConversionSyntax = operand.Syntax.Kind() = SyntaxKind.AddressOfExpression AndAlso (conversionSyntax.Kind() = SyntaxKind.CTypeExpression OrElse conversionSyntax.Kind() = SyntaxKind.DirectCastExpression OrElse conversionSyntax.Kind() = SyntaxKind.TryCastExpression OrElse conversionSyntax.Kind() = SyntaxKind.ObjectCreationExpression OrElse (conversionSyntax.Kind() = SyntaxKind.AddressOfExpression AndAlso conversionSyntax Is operand.Syntax)) Dim validLambdaConversionNode = operand.Kind = BoundKind.Lambda OrElse operand.Kind = BoundKind.QueryLambda OrElse operand.Kind = BoundKind.UnboundLambda Return validAddressOfConversionSyntax OrElse validLambdaConversionNode End Function #End Region Friend Class Helper Friend Shared Function DeriveUnaryOperatorKind(operatorKind As VisualBasic.UnaryOperatorKind) As UnaryOperatorKind Select Case operatorKind And VisualBasic.UnaryOperatorKind.OpMask Case VisualBasic.UnaryOperatorKind.Plus Return UnaryOperatorKind.Plus Case VisualBasic.UnaryOperatorKind.Minus Return UnaryOperatorKind.Minus Case VisualBasic.UnaryOperatorKind.Not Return UnaryOperatorKind.Not Case VisualBasic.UnaryOperatorKind.IsTrue Return UnaryOperatorKind.True Case VisualBasic.UnaryOperatorKind.IsFalse Return UnaryOperatorKind.False Case Else Return UnaryOperatorKind.None End Select End Function Friend Shared Function DeriveBinaryOperatorKind(operatorKind As VisualBasic.BinaryOperatorKind, leftOpt As BoundExpression) As BinaryOperatorKind Select Case operatorKind And VisualBasic.BinaryOperatorKind.OpMask Case VisualBasic.BinaryOperatorKind.Add Return BinaryOperatorKind.Add Case VisualBasic.BinaryOperatorKind.Subtract Return BinaryOperatorKind.Subtract Case VisualBasic.BinaryOperatorKind.Multiply Return BinaryOperatorKind.Multiply Case VisualBasic.BinaryOperatorKind.Divide Return BinaryOperatorKind.Divide Case VisualBasic.BinaryOperatorKind.IntegerDivide Return BinaryOperatorKind.IntegerDivide Case VisualBasic.BinaryOperatorKind.Modulo Return BinaryOperatorKind.Remainder Case VisualBasic.BinaryOperatorKind.And Return BinaryOperatorKind.And Case VisualBasic.BinaryOperatorKind.Or Return BinaryOperatorKind.Or Case VisualBasic.BinaryOperatorKind.Xor Return BinaryOperatorKind.ExclusiveOr Case VisualBasic.BinaryOperatorKind.AndAlso Return BinaryOperatorKind.ConditionalAnd Case VisualBasic.BinaryOperatorKind.OrElse Return BinaryOperatorKind.ConditionalOr Case VisualBasic.BinaryOperatorKind.LeftShift Return BinaryOperatorKind.LeftShift Case VisualBasic.BinaryOperatorKind.RightShift Return BinaryOperatorKind.RightShift Case VisualBasic.BinaryOperatorKind.LessThan Return BinaryOperatorKind.LessThan Case VisualBasic.BinaryOperatorKind.LessThanOrEqual Return BinaryOperatorKind.LessThanOrEqual Case VisualBasic.BinaryOperatorKind.Equals Return If(leftOpt?.Type?.SpecialType = SpecialType.System_Object, BinaryOperatorKind.ObjectValueEquals, BinaryOperatorKind.Equals) Case VisualBasic.BinaryOperatorKind.NotEquals Return If(leftOpt?.Type?.SpecialType = SpecialType.System_Object, BinaryOperatorKind.ObjectValueNotEquals, BinaryOperatorKind.NotEquals) Case VisualBasic.BinaryOperatorKind.Is Return BinaryOperatorKind.Equals Case VisualBasic.BinaryOperatorKind.IsNot Return BinaryOperatorKind.NotEquals Case VisualBasic.BinaryOperatorKind.GreaterThanOrEqual Return BinaryOperatorKind.GreaterThanOrEqual Case VisualBasic.BinaryOperatorKind.GreaterThan Return BinaryOperatorKind.GreaterThan Case VisualBasic.BinaryOperatorKind.Power Return BinaryOperatorKind.Power Case VisualBasic.BinaryOperatorKind.Like Return BinaryOperatorKind.Like Case VisualBasic.BinaryOperatorKind.Concatenate Return BinaryOperatorKind.Concatenate Case Else Return BinaryOperatorKind.None End Select End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.AnonymousTypeManager Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Operations Partial Friend NotInheritable Class VisualBasicOperationFactory Private Shared Function IsMidStatement(node As BoundNode) As Boolean If node.Kind = BoundKind.Conversion Then node = DirectCast(node, BoundConversion).Operand If node.Kind = BoundKind.UserDefinedConversion Then node = DirectCast(node, BoundUserDefinedConversion).Operand End If End If Return node.Kind = BoundKind.MidResult End Function Friend Function CreateCompoundAssignmentRightOperand(boundAssignment As BoundAssignmentOperator) As IOperation Dim binaryOperator As BoundExpression = Nothing Select Case boundAssignment.Right.Kind Case BoundKind.Conversion Dim inConversionNode = DirectCast(boundAssignment.Right, BoundConversion) binaryOperator = GetConversionOperand(inConversionNode) Case BoundKind.UserDefinedBinaryOperator, BoundKind.BinaryOperator binaryOperator = boundAssignment.Right Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select Dim operatorInfo As BinaryOperatorInfo Select Case binaryOperator.Kind Case BoundKind.BinaryOperator operatorInfo = GetBinaryOperatorInfo(DirectCast(binaryOperator, BoundBinaryOperator)) Return Create(operatorInfo.RightOperand) Case BoundKind.UserDefinedBinaryOperator Dim userDefinedOperator = DirectCast(binaryOperator, BoundUserDefinedBinaryOperator) operatorInfo = GetUserDefinedBinaryOperatorInfo(userDefinedOperator) Return GetUserDefinedBinaryOperatorChild(userDefinedOperator, operatorInfo.RightOperand) Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select End Function Private Function CreateCompoundAssignment(boundAssignment As BoundAssignmentOperator) As ICompoundAssignmentOperation Debug.Assert(boundAssignment.LeftOnTheRightOpt IsNot Nothing) Dim inConversion = New Conversion(Conversions.Identity) Dim outConversion As Conversion = inConversion Dim binaryOperator As BoundExpression = Nothing Select Case boundAssignment.Right.Kind Case BoundKind.Conversion Dim inConversionNode = DirectCast(boundAssignment.Right, BoundConversion) outConversion = CreateConversion(inConversionNode) binaryOperator = GetConversionOperand(inConversionNode) Case BoundKind.UserDefinedBinaryOperator, BoundKind.BinaryOperator binaryOperator = boundAssignment.Right Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select Dim operatorInfo As BinaryOperatorInfo Select Case binaryOperator.Kind Case BoundKind.BinaryOperator operatorInfo = GetBinaryOperatorInfo(DirectCast(binaryOperator, BoundBinaryOperator)) Case BoundKind.UserDefinedBinaryOperator Dim userDefinedOperator = DirectCast(binaryOperator, BoundUserDefinedBinaryOperator) operatorInfo = GetUserDefinedBinaryOperatorInfo(userDefinedOperator) Case Else Throw ExceptionUtilities.UnexpectedValue(boundAssignment.Kind) End Select Dim leftOnTheRight As BoundExpression = operatorInfo.LeftOperand If leftOnTheRight.Kind = BoundKind.Conversion Then Dim outConversionNode = DirectCast(leftOnTheRight, BoundConversion) inConversion = CreateConversion(outConversionNode) leftOnTheRight = GetConversionOperand(outConversionNode) End If Debug.Assert(leftOnTheRight Is boundAssignment.LeftOnTheRightOpt) Dim target As IOperation = Create(boundAssignment.Left) Dim value As IOperation = CreateCompoundAssignmentRightOperand(boundAssignment) Dim syntax As SyntaxNode = boundAssignment.Syntax Dim type As ITypeSymbol = boundAssignment.Type Dim isImplicit As Boolean = boundAssignment.WasCompilerGenerated Return New CompoundAssignmentOperation(inConversion, outConversion, operatorInfo.OperatorKind, operatorInfo.IsLifted, operatorInfo.IsChecked, operatorInfo.OperatorMethod, target, value, _semanticModel, syntax, type, isImplicit) End Function Private Structure BinaryOperatorInfo Public Sub New(leftOperand As BoundExpression, rightOperand As BoundExpression, binaryOperatorKind As BinaryOperatorKind, operatorMethod As MethodSymbol, isLifted As Boolean, isChecked As Boolean, isCompareText As Boolean) Me.LeftOperand = leftOperand Me.RightOperand = rightOperand Me.OperatorKind = binaryOperatorKind Me.OperatorMethod = operatorMethod Me.IsLifted = isLifted Me.IsChecked = isChecked Me.IsCompareText = isCompareText End Sub Public ReadOnly LeftOperand As BoundExpression Public ReadOnly RightOperand As BoundExpression Public ReadOnly OperatorKind As BinaryOperatorKind Public ReadOnly OperatorMethod As MethodSymbol Public ReadOnly IsLifted As Boolean Public ReadOnly IsChecked As Boolean Public ReadOnly IsCompareText As Boolean End Structure Private Shared Function GetBinaryOperatorInfo(boundBinaryOperator As BoundBinaryOperator) As BinaryOperatorInfo Return New BinaryOperatorInfo( leftOperand:=boundBinaryOperator.Left, rightOperand:=boundBinaryOperator.Right, binaryOperatorKind:=Helper.DeriveBinaryOperatorKind(boundBinaryOperator.OperatorKind, boundBinaryOperator.Left), operatorMethod:=Nothing, isLifted:=(boundBinaryOperator.OperatorKind And VisualBasic.BinaryOperatorKind.Lifted) <> 0, isChecked:=boundBinaryOperator.Checked, isCompareText:=(boundBinaryOperator.OperatorKind And VisualBasic.BinaryOperatorKind.CompareText) <> 0) End Function Private Shared Function GetUserDefinedBinaryOperatorInfo(boundUserDefinedBinaryOperator As BoundUserDefinedBinaryOperator) As BinaryOperatorInfo Return New BinaryOperatorInfo( leftOperand:=GetUserDefinedBinaryOperatorChildBoundNode(boundUserDefinedBinaryOperator, 0), rightOperand:=GetUserDefinedBinaryOperatorChildBoundNode(boundUserDefinedBinaryOperator, 1), binaryOperatorKind:=Helper.DeriveBinaryOperatorKind(boundUserDefinedBinaryOperator.OperatorKind, leftOpt:=Nothing), operatorMethod:=If(boundUserDefinedBinaryOperator.UnderlyingExpression.Kind = BoundKind.Call, boundUserDefinedBinaryOperator.Call.Method, Nothing), isLifted:=(boundUserDefinedBinaryOperator.OperatorKind And VisualBasic.BinaryOperatorKind.Lifted) <> 0, isChecked:=boundUserDefinedBinaryOperator.Checked, isCompareText:=False) End Function Private Function GetUserDefinedBinaryOperatorChild([operator] As BoundUserDefinedBinaryOperator, child As BoundExpression) As IOperation If child IsNot Nothing Then Return Create(child) End If Dim isImplicit As Boolean = [operator].UnderlyingExpression.WasCompilerGenerated Return OperationFactory.CreateInvalidOperation(_semanticModel, [operator].UnderlyingExpression.Syntax, ImmutableArray(Of IOperation).Empty, isImplicit) End Function Private Shared Function GetUserDefinedBinaryOperatorChildBoundNode([operator] As BoundUserDefinedBinaryOperator, index As Integer) As BoundExpression If [operator].UnderlyingExpression.Kind = BoundKind.Call Then If index = 0 Then Return [operator].Left ElseIf index = 1 Then Return [operator].Right Else Throw ExceptionUtilities.UnexpectedValue(index) End If End If Return GetChildOfBadExpressionBoundNode([operator].UnderlyingExpression, index) End Function Friend Function DeriveArguments(boundNode As BoundNode) As ImmutableArray(Of IArgumentOperation) Select Case boundNode.Kind Case BoundKind.Call Dim boundCall = DirectCast(boundNode, BoundCall) Return DeriveArguments(boundCall.Arguments, boundCall.Method.Parameters, boundCall.DefaultArguments) Case BoundKind.ObjectCreationExpression Dim boundCreation = DirectCast(boundNode, BoundObjectCreationExpression) If boundCreation.Arguments.IsDefault Then Return ImmutableArray(Of IArgumentOperation).Empty End If Return If(boundCreation.ConstructorOpt Is Nothing, ImmutableArray(Of IArgumentOperation).Empty, DeriveArguments(boundCreation.Arguments, boundCreation.ConstructorOpt.Parameters, boundCreation.DefaultArguments)) Case BoundKind.PropertyAccess Dim boundProperty = DirectCast(boundNode, BoundPropertyAccess) Return If(boundProperty.Arguments.Length = 0, ImmutableArray(Of IArgumentOperation).Empty, DeriveArguments(boundProperty.Arguments, boundProperty.PropertySymbol.Parameters, boundProperty.DefaultArguments)) Case BoundKind.RaiseEventStatement Dim boundRaiseEvent = DirectCast(boundNode, BoundRaiseEventStatement) Return DeriveArguments(DirectCast(boundRaiseEvent.EventInvocation, BoundCall)) Case Else Throw ExceptionUtilities.UnexpectedValue(boundNode.Kind) End Select End Function Friend Function DeriveArguments(boundArguments As ImmutableArray(Of BoundExpression), parameters As ImmutableArray(Of VisualBasic.Symbols.ParameterSymbol), ByRef defaultArguments As BitVector) As ImmutableArray(Of IArgumentOperation) Dim argumentsLength As Integer = boundArguments.Length Debug.Assert(argumentsLength = parameters.Length) Dim arguments As ArrayBuilder(Of IArgumentOperation) = ArrayBuilder(Of IArgumentOperation).GetInstance(argumentsLength) For index As Integer = 0 To argumentsLength - 1 Step 1 arguments.Add(DeriveArgument(index, boundArguments(index), parameters, defaultArguments(index))) Next Return arguments.ToImmutableAndFree() End Function Private Function DeriveArgument( index As Integer, argument As BoundExpression, parameters As ImmutableArray(Of VisualBasic.Symbols.ParameterSymbol), isDefault As Boolean ) As IArgumentOperation Dim isImplicit As Boolean = argument.WasCompilerGenerated AndAlso argument.Syntax.Kind <> SyntaxKind.OmittedArgument Select Case argument.Kind Case BoundKind.ByRefArgumentWithCopyBack Dim byRefArgument = DirectCast(argument, BoundByRefArgumentWithCopyBack) Dim parameter = parameters(index) Return CreateArgumentOperation( ArgumentKind.Explicit, parameter, byRefArgument.OriginalArgument, CreateConversion(byRefArgument.InConversion), CreateConversion(byRefArgument.OutConversion), isImplicit) Case Else Dim lastParameterIndex = parameters.Length - 1 Dim kind As ArgumentKind = ArgumentKind.Explicit If argument.WasCompilerGenerated Then If isDefault Then kind = ArgumentKind.DefaultValue ElseIf argument.Kind = BoundKind.ArrayCreation AndAlso DirectCast(argument, BoundArrayCreation).IsParamArrayArgument Then kind = ArgumentKind.ParamArray End If End If Return CreateArgumentOperation( kind, parameters(index), argument, New Conversion(Conversions.Identity), New Conversion(Conversions.Identity), isImplicit) End Select End Function Private Function CreateArgumentOperation( kind As ArgumentKind, parameter As IParameterSymbol, valueNode As BoundNode, inConversion As Conversion, outConversion As Conversion, isImplicit As Boolean) As IArgumentOperation ' put argument syntax to argument operation Dim syntax = If(valueNode.Syntax.Kind = SyntaxKind.OmittedArgument, valueNode.Syntax, TryCast(valueNode.Syntax?.Parent, ArgumentSyntax)) Dim value = Create(valueNode) If syntax Is Nothing Then syntax = value.Syntax isImplicit = True End If Return New ArgumentOperation( kind, parameter, value, inConversion, outConversion, _semanticModel, syntax, isImplicit) End Function Friend Function CreateReceiverOperation(node As BoundNode, symbol As ISymbol) As IOperation If node Is Nothing OrElse node.Kind = BoundKind.TypeExpression Then Return Nothing End If If symbol IsNot Nothing AndAlso node.WasCompilerGenerated AndAlso symbol.IsStatic AndAlso (node.Kind = BoundKind.MeReference OrElse node.Kind = BoundKind.WithLValueExpressionPlaceholder OrElse node.Kind = BoundKind.WithRValueExpressionPlaceholder) Then Return Nothing End If Return Create(node) End Function Private Shared Function ParameterIsParamArray(parameter As VisualBasic.Symbols.ParameterSymbol) As Boolean Return If(parameter.IsParamArray AndAlso parameter.Type.Kind = SymbolKind.ArrayType, DirectCast(parameter.Type, VisualBasic.Symbols.ArrayTypeSymbol).IsSZArray, False) End Function Private Function GetChildOfBadExpression(parent As BoundNode, index As Integer) As IOperation Dim child = Create(GetChildOfBadExpressionBoundNode(parent, index)) If child IsNot Nothing Then Return child End If Dim isImplicit As Boolean = parent.WasCompilerGenerated Return OperationFactory.CreateInvalidOperation(_semanticModel, parent.Syntax, ImmutableArray(Of IOperation).Empty, isImplicit) End Function Private Shared Function GetChildOfBadExpressionBoundNode(parent As BoundNode, index As Integer) As BoundExpression Dim badParent As BoundBadExpression = TryCast(parent, BoundBadExpression) If badParent?.ChildBoundNodes.Length > index Then Return badParent.ChildBoundNodes(index) End If Return Nothing End Function Private Function GetObjectCreationInitializers(expression As BoundObjectCreationExpression) As ImmutableArray(Of IOperation) Return If(expression.InitializerOpt IsNot Nothing, expression.InitializerOpt.Initializers.SelectAsArray(Function(n) Create(n)), ImmutableArray(Of IOperation).Empty) End Function Friend Function GetAnonymousTypeCreationInitializers(expression As BoundAnonymousTypeCreationExpression) As ImmutableArray(Of IOperation) ' For error cases and non-assignment initializers, the binder generates only the argument. Debug.Assert(expression.Arguments.Length >= expression.Declarations.Length) Dim properties = DirectCast(expression.Type, AnonymousTypePublicSymbol).Properties Debug.Assert(properties.Length = expression.Arguments.Length) Dim builder = ArrayBuilder(Of IOperation).GetInstance(expression.Arguments.Length) Dim currentDeclarationIndex = 0 For i As Integer = 0 To expression.Arguments.Length - 1 Dim value As IOperation = Create(expression.Arguments(i)) Dim target As IOperation Dim isImplicitAssignment As Boolean ' Find matching declaration for the current argument If currentDeclarationIndex >= expression.Declarations.Length OrElse i <> expression.Declarations(currentDeclarationIndex).PropertyIndex Then ' No matching declaration, synthesize a property reference with an implicit receiver to be assigned. Dim [property] As IPropertySymbol = properties(i) Dim instance As IInstanceReferenceOperation = CreateAnonymousTypePropertyAccessImplicitReceiverOperation([property], expression.Syntax) target = New PropertyReferenceOperation( [property], ImmutableArray(Of IArgumentOperation).Empty, instance, _semanticModel, value.Syntax, [property].Type, isImplicit:=True) isImplicitAssignment = True Else Debug.Assert(i = expression.Declarations(currentDeclarationIndex).PropertyIndex) target = CreateBoundAnonymousTypePropertyAccessOperation(expression.Declarations(currentDeclarationIndex)) currentDeclarationIndex = currentDeclarationIndex + 1 isImplicitAssignment = expression.WasCompilerGenerated End If Dim isRef As Boolean = False Dim syntax As SyntaxNode = If(value.Syntax?.Parent, expression.Syntax) Dim type As ITypeSymbol = target.Type Dim constantValue As ConstantValue = value.GetConstantValue() Dim assignment = New SimpleAssignmentOperation(isRef, target, value, _semanticModel, syntax, type, constantValue, isImplicitAssignment) builder.Add(assignment) Next i Debug.Assert(currentDeclarationIndex = expression.Declarations.Length) Return builder.ToImmutableAndFree() End Function Private Shared Function GetSingleValueCaseClauseValue(clause As BoundSingleValueCaseClause) As BoundExpression Return GetCaseClauseValue(clause.ValueOpt, clause.ConditionOpt) End Function Friend Shared Function GetCaseClauseValue(valueOpt As BoundExpression, conditionOpt As BoundExpression) As BoundExpression If valueOpt IsNot Nothing Then Return valueOpt End If Select Case conditionOpt.Kind Case BoundKind.BinaryOperator Dim binaryOp As BoundBinaryOperator = DirectCast(conditionOpt, BoundBinaryOperator) Return binaryOp.Right Case BoundKind.UserDefinedBinaryOperator Dim binaryOp As BoundUserDefinedBinaryOperator = DirectCast(conditionOpt, BoundUserDefinedBinaryOperator) Return GetUserDefinedBinaryOperatorChildBoundNode(binaryOp, 1) Case Else Throw ExceptionUtilities.UnexpectedValue(conditionOpt.Kind) End Select End Function Friend Function GetVariableDeclarationStatementVariables(declarations As ImmutableArray(Of BoundLocalDeclarationBase)) As ImmutableArray(Of IVariableDeclarationOperation) ' Group the declarations by their VariableDeclaratorSyntaxes. The issue we're compensating for here is that the ' the declarations that are BoundLocalDeclaration nodes have a ModifiedIdentifierSyntax as their syntax nodes, ' not a VariableDeclaratorSyntax. We want to group BoundLocalDeclarations by their parent VariableDeclaratorSyntax ' nodes, and deduplicate based on that. As an example: ' ' Dim x, y = 1 ' ' This is an error scenario, but if we just use the BoundLocalDeclaration.Syntax.Parent directly, without deduplicating, ' we'll end up with two IVariableDeclarators that have the same syntax node. So, we group by VariableDeclaratorSyntax ' to put x and y in the same IMultiVariableDeclaration Dim groupedDeclarations = declarations.GroupBy(Function(declaration) If declaration.Kind = BoundKind.LocalDeclaration AndAlso declaration.Syntax.IsKind(SyntaxKind.ModifiedIdentifier) Then Debug.Assert(declaration.Syntax.Parent.IsKind(SyntaxKind.VariableDeclarator)) Return declaration.Syntax.Parent Else Return declaration.Syntax End If End Function) Dim builder = ArrayBuilder(Of IVariableDeclarationOperation).GetInstance() For Each declarationGroup In groupedDeclarations Dim first = declarationGroup.First() Dim declarators As ImmutableArray(Of IVariableDeclaratorOperation) = Nothing Dim initializer As IVariableInitializerOperation = Nothing If first.Kind = BoundKind.LocalDeclaration Then declarators = declarationGroup.Cast(Of BoundLocalDeclaration).SelectAsArray(AddressOf GetVariableDeclarator) ' The initializer we use for this group is the initializer attached to the last declaration in this declarator, as that's ' where it will be parsed in an error case. ' Initializer is only created if it's not the array initializer for the variable. That initializer is the initializer ' of the VariableDeclarator child. Dim last = DirectCast(declarationGroup.Last(), BoundLocalDeclaration) If last.DeclarationInitializerOpt IsNot Nothing Then Debug.Assert(last.Syntax.IsKind(SyntaxKind.ModifiedIdentifier)) Dim declaratorSyntax = DirectCast(last.Syntax.Parent, VariableDeclaratorSyntax) Dim initializerSyntax As SyntaxNode = declaratorSyntax.Initializer ' As New clauses with a single variable are bound as BoundLocalDeclarations, so adjust appropriately Dim isImplicit As Boolean = False If last.InitializedByAsNew Then initializerSyntax = declaratorSyntax.AsClause ElseIf initializerSyntax Is Nothing Then ' There is no explicit syntax for the initializer, so we use the initializerValue's syntax and mark the operation as implicit. initializerSyntax = last.InitializerOpt.Syntax isImplicit = True End If Debug.Assert(last.InitializerOpt IsNot Nothing) Dim value = Create(last.InitializerOpt) initializer = New VariableInitializerOperation(locals:=ImmutableArray(Of ILocalSymbol).Empty, value, _semanticModel, initializerSyntax, isImplicit) End If Else Dim asNewDeclarations = DirectCast(first, BoundAsNewLocalDeclarations) declarators = asNewDeclarations.LocalDeclarations.SelectAsArray(AddressOf GetVariableDeclarator) Dim initializerSyntax As AsClauseSyntax = DirectCast(asNewDeclarations.Syntax, VariableDeclaratorSyntax).AsClause Dim initializerValue As IOperation = Create(asNewDeclarations.Initializer) Debug.Assert(asNewDeclarations.Initializer IsNot Nothing) Dim value = Create(asNewDeclarations.Initializer) initializer = New VariableInitializerOperation(locals:=ImmutableArray(Of ILocalSymbol).Empty, value, _semanticModel, initializerSyntax, isImplicit:=False) End If builder.Add(New VariableDeclarationOperation(declarators, initializer, ImmutableArray(Of IOperation).Empty, _semanticModel, declarationGroup.Key, isImplicit:=False)) Next Return builder.ToImmutableAndFree() End Function Private Function GetVariableDeclarator(boundLocalDeclaration As BoundLocalDeclaration) As IVariableDeclaratorOperation Dim initializer As IVariableInitializerOperation = Nothing If boundLocalDeclaration.IdentifierInitializerOpt IsNot Nothing Then Dim syntax = boundLocalDeclaration.Syntax Dim initializerValue As IOperation = Create(boundLocalDeclaration.IdentifierInitializerOpt) initializer = New VariableInitializerOperation(locals:=ImmutableArray(Of ILocalSymbol).Empty, initializerValue, _semanticModel, syntax, isImplicit:=True) End If Dim ignoredArguments = ImmutableArray(Of IOperation).Empty Return New VariableDeclaratorOperation(boundLocalDeclaration.LocalSymbol, initializer, ignoredArguments, _semanticModel, boundLocalDeclaration.Syntax, isImplicit:=boundLocalDeclaration.WasCompilerGenerated) End Function Private Function GetUsingStatementDeclaration(resourceList As ImmutableArray(Of BoundLocalDeclarationBase), syntax As SyntaxNode) As IVariableDeclarationGroupOperation Return New VariableDeclarationGroupOperation( GetVariableDeclarationStatementVariables(resourceList), _semanticModel, syntax, isImplicit:=False) ' Declaration is always explicit End Function Friend Function GetAddRemoveHandlerStatementExpression(statement As BoundAddRemoveHandlerStatement) As IOperation Dim eventReference As IOperation = Create(statement.EventAccess) Dim handlerValue As IOperation = Create(statement.Handler) Dim adds = statement.Kind = BoundKind.AddHandlerStatement Return New EventAssignmentOperation(eventReference, handlerValue, adds, _semanticModel, statement.Syntax, type:=Nothing, isImplicit:=True) End Function #Region "Conversions" ''' <summary> ''' Creates the Lazy IOperation from a delegate creation operand or a bound conversion operand, handling when the conversion ''' is actually a delegate creation. ''' </summary> Private Function GetConversionInfo(boundConversion As BoundConversionOrCast ) As (Operation As IOperation, Conversion As Conversion, IsDelegateCreation As Boolean) Dim conversion = CreateConversion(boundConversion) Dim boundOperand = GetConversionOperand(boundConversion) If conversion.IsIdentity AndAlso boundConversion.ExplicitCastInCode Then Dim adjustedInfo = TryGetAdjustedConversionInfo(boundConversion, boundOperand) If adjustedInfo.Operation IsNot Nothing Then Return adjustedInfo End If End If If IsDelegateCreation(boundConversion.Syntax, boundOperand, boundConversion.Type) Then Return (CreateDelegateCreationConversionOperand(boundOperand), conversion, IsDelegateCreation:=True) Else Return (Create(boundOperand), conversion, IsDelegateCreation:=False) End If End Function Private Function TryGetAdjustedConversionInfo(topLevelConversion As BoundConversionOrCast, boundOperand As BoundExpression ) As (Operation As IOperation, Conversion As Conversion, IsDelegateCreation As Boolean) ' Dig through the bound tree to see if this is an artificial nested conversion. If so, let's erase the nested conversion. ' Artificial conversions are added on top of BoundConvertedTupleLiteral in Binder.ReclassifyTupleLiteral, or in ' ReclassifyUnboundLambdaExpression and the like. We need to use conversion information from the nested conversion ' because that is where the real conversion information is stored. If boundOperand.Kind = BoundKind.Parenthesized Then Dim adjustedInfo = TryGetAdjustedConversionInfo(topLevelConversion, DirectCast(boundOperand, BoundParenthesized).Expression) If adjustedInfo.Operation IsNot Nothing Then Return (Operation:=New ParenthesizedOperation(adjustedInfo.Operation, _semanticModel, boundOperand.Syntax, adjustedInfo.Operation.Type, boundOperand.ConstantValueOpt, boundOperand.WasCompilerGenerated), adjustedInfo.Conversion, adjustedInfo.IsDelegateCreation) End If ElseIf boundOperand.Kind = topLevelConversion.Kind Then Dim nestedConversion = DirectCast(boundOperand, BoundConversionOrCast) Dim nestedOperand As BoundExpression = GetConversionOperand(nestedConversion) If nestedConversion.Syntax Is nestedOperand.Syntax AndAlso Not TypeSymbol.Equals(nestedConversion.Type, nestedOperand.Type, TypeCompareKind.ConsiderEverything) AndAlso nestedConversion.ExplicitCastInCode AndAlso TypeSymbol.Equals(topLevelConversion.Type, nestedConversion.Type, TypeCompareKind.ConsiderEverything) Then Return GetConversionInfo(nestedConversion) End If ElseIf boundOperand.Syntax.IsKind(SyntaxKind.AddressOfExpression) AndAlso TypeSymbol.Equals(topLevelConversion.Type, boundOperand.Type, TypeCompareKind.ConsiderEverything) AndAlso IsDelegateCreation(topLevelConversion.Syntax, boundOperand, boundOperand.Type) Then Return (CreateDelegateCreationConversionOperand(boundOperand), Conversion:=Nothing, IsDelegateCreation:=True) End If Return Nothing End Function ''' <summary> ''' Gets the operand from a BoundConversion, compensating for if the conversion is a user-defined conversion ''' </summary> Private Shared Function GetConversionOperand(boundConversion As BoundConversionOrCast) As BoundExpression If (boundConversion.ConversionKind And ConversionKind.UserDefined) = ConversionKind.UserDefined Then Dim userDefinedConversion = DirectCast(boundConversion.Operand, BoundUserDefinedConversion) Return userDefinedConversion.Operand Else Return boundConversion.Operand End If End Function Private Function CreateDelegateCreationConversionOperand(operand As BoundExpression) As IOperation If operand.Kind = BoundKind.DelegateCreationExpression Then ' If the child is a BoundDelegateCreationExpression, we don't want to generate a nested IDelegateCreationExpression. ' So, the operand for the conversion will be the child of the BoundDelegateCreationExpression. ' We see this in this syntax: Dim x = New Action(AddressOf M2) ' This should be semantically equivalent to: Dim x = AddressOf M2 ' However, if we didn't fix this up, we would have nested IDelegateCreationExpressions here for the former case. Return CreateBoundDelegateCreationExpressionChildOperation(DirectCast(operand, BoundDelegateCreationExpression)) Else Return Create(operand) End If End Function Private Shared Function CreateConversion(expression As BoundExpression) As Conversion If expression.Kind = BoundKind.Conversion Then Dim conversion = DirectCast(expression, BoundConversion) Dim conversionKind = conversion.ConversionKind Dim method As MethodSymbol = Nothing If conversionKind.HasFlag(VisualBasic.ConversionKind.UserDefined) AndAlso conversion.Operand.Kind = BoundKind.UserDefinedConversion Then method = DirectCast(conversion.Operand, BoundUserDefinedConversion).Call.Method End If Return New Conversion(KeyValuePairUtil.Create(conversionKind, method)) ElseIf expression.Kind = BoundKind.TryCast OrElse expression.Kind = BoundKind.DirectCast Then Return New Conversion(KeyValuePairUtil.Create(Of ConversionKind, MethodSymbol)(DirectCast(expression, BoundConversionOrCast).ConversionKind, Nothing)) End If Return New Conversion(Conversions.Identity) End Function Private Shared Function IsDelegateCreation(conversionSyntax As SyntaxNode, operand As BoundNode, targetType As TypeSymbol) As Boolean If Not targetType.IsDelegateType() Then Return False End If ' Any of the explicit cast types, as well as New DelegateType(AddressOf Method) ' Additionally, AddressOf, if the child AddressOf is the same SyntaxNode (ie, an implicit delegate creation) ' In the case of AddressOf, the operand can be a BoundDelegateCreationExpression, a BoundAddressOfOperator, or ' a BoundBadExpression. For simplicity, we just do a syntax check to make sure it's an AddressOfExpression so ' we don't have to compare against all 3 BoundKinds Dim validAddressOfConversionSyntax = operand.Syntax.Kind() = SyntaxKind.AddressOfExpression AndAlso (conversionSyntax.Kind() = SyntaxKind.CTypeExpression OrElse conversionSyntax.Kind() = SyntaxKind.DirectCastExpression OrElse conversionSyntax.Kind() = SyntaxKind.TryCastExpression OrElse conversionSyntax.Kind() = SyntaxKind.ObjectCreationExpression OrElse (conversionSyntax.Kind() = SyntaxKind.AddressOfExpression AndAlso conversionSyntax Is operand.Syntax)) Dim validLambdaConversionNode = operand.Kind = BoundKind.Lambda OrElse operand.Kind = BoundKind.QueryLambda OrElse operand.Kind = BoundKind.UnboundLambda Return validAddressOfConversionSyntax OrElse validLambdaConversionNode End Function #End Region Friend Class Helper Friend Shared Function DeriveUnaryOperatorKind(operatorKind As VisualBasic.UnaryOperatorKind) As UnaryOperatorKind Select Case operatorKind And VisualBasic.UnaryOperatorKind.OpMask Case VisualBasic.UnaryOperatorKind.Plus Return UnaryOperatorKind.Plus Case VisualBasic.UnaryOperatorKind.Minus Return UnaryOperatorKind.Minus Case VisualBasic.UnaryOperatorKind.Not Return UnaryOperatorKind.Not Case VisualBasic.UnaryOperatorKind.IsTrue Return UnaryOperatorKind.True Case VisualBasic.UnaryOperatorKind.IsFalse Return UnaryOperatorKind.False Case Else Return UnaryOperatorKind.None End Select End Function Friend Shared Function DeriveBinaryOperatorKind(operatorKind As VisualBasic.BinaryOperatorKind, leftOpt As BoundExpression) As BinaryOperatorKind Select Case operatorKind And VisualBasic.BinaryOperatorKind.OpMask Case VisualBasic.BinaryOperatorKind.Add Return BinaryOperatorKind.Add Case VisualBasic.BinaryOperatorKind.Subtract Return BinaryOperatorKind.Subtract Case VisualBasic.BinaryOperatorKind.Multiply Return BinaryOperatorKind.Multiply Case VisualBasic.BinaryOperatorKind.Divide Return BinaryOperatorKind.Divide Case VisualBasic.BinaryOperatorKind.IntegerDivide Return BinaryOperatorKind.IntegerDivide Case VisualBasic.BinaryOperatorKind.Modulo Return BinaryOperatorKind.Remainder Case VisualBasic.BinaryOperatorKind.And Return BinaryOperatorKind.And Case VisualBasic.BinaryOperatorKind.Or Return BinaryOperatorKind.Or Case VisualBasic.BinaryOperatorKind.Xor Return BinaryOperatorKind.ExclusiveOr Case VisualBasic.BinaryOperatorKind.AndAlso Return BinaryOperatorKind.ConditionalAnd Case VisualBasic.BinaryOperatorKind.OrElse Return BinaryOperatorKind.ConditionalOr Case VisualBasic.BinaryOperatorKind.LeftShift Return BinaryOperatorKind.LeftShift Case VisualBasic.BinaryOperatorKind.RightShift Return BinaryOperatorKind.RightShift Case VisualBasic.BinaryOperatorKind.LessThan Return BinaryOperatorKind.LessThan Case VisualBasic.BinaryOperatorKind.LessThanOrEqual Return BinaryOperatorKind.LessThanOrEqual Case VisualBasic.BinaryOperatorKind.Equals Return If(leftOpt?.Type?.SpecialType = SpecialType.System_Object, BinaryOperatorKind.ObjectValueEquals, BinaryOperatorKind.Equals) Case VisualBasic.BinaryOperatorKind.NotEquals Return If(leftOpt?.Type?.SpecialType = SpecialType.System_Object, BinaryOperatorKind.ObjectValueNotEquals, BinaryOperatorKind.NotEquals) Case VisualBasic.BinaryOperatorKind.Is Return BinaryOperatorKind.Equals Case VisualBasic.BinaryOperatorKind.IsNot Return BinaryOperatorKind.NotEquals Case VisualBasic.BinaryOperatorKind.GreaterThanOrEqual Return BinaryOperatorKind.GreaterThanOrEqual Case VisualBasic.BinaryOperatorKind.GreaterThan Return BinaryOperatorKind.GreaterThan Case VisualBasic.BinaryOperatorKind.Power Return BinaryOperatorKind.Power Case VisualBasic.BinaryOperatorKind.Like Return BinaryOperatorKind.Like Case VisualBasic.BinaryOperatorKind.Concatenate Return BinaryOperatorKind.Concatenate Case Else Return BinaryOperatorKind.None End Select End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ConstructorInitializerSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal sealed class ConstructorInitializerSymbolReferenceFinder : AbstractReferenceFinder<IMethodSymbol> { protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.Constructor; protected override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindDocumentsAsync(project, documents, async (d, c) => { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(d, c).ConfigureAwait(false); if (index.ContainsBaseConstructorInitializer) { return true; } if (index.ProbablyContainsIdentifier(symbol.ContainingType.Name)) { if (index.ContainsThisConstructorInitializer) { return true; } else if (project.Language == LanguageNames.VisualBasic && index.ProbablyContainsIdentifier("New")) { // "New" can be explicitly accessed in xml doc comments to reference a constructor. return true; } } return false; }, cancellationToken); } protected sealed override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol methodSymbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeName = methodSymbol.ContainingType.Name; var tokens = await document.GetConstructorInitializerTokensAsync(semanticModel, cancellationToken).ConfigureAwait(false); if (semanticModel.Language == LanguageNames.VisualBasic) { tokens = tokens.Concat(await GetIdentifierOrGlobalNamespaceTokensWithTextAsync( document, semanticModel, "New", cancellationToken).ConfigureAwait(false)).Distinct(); } return await FindReferencesInTokensAsync( methodSymbol, document, semanticModel, tokens, TokensMatch, cancellationToken).ConfigureAwait(false); // local functions bool TokensMatch(SyntaxToken t) { if (syntaxFactsService.IsBaseConstructorInitializer(t)) { var containingType = semanticModel.GetEnclosingNamedType(t.SpanStart, cancellationToken); return containingType != null && containingType.BaseType != null && containingType.BaseType.Name == typeName; } else if (syntaxFactsService.IsThisConstructorInitializer(t)) { var containingType = semanticModel.GetEnclosingNamedType(t.SpanStart, cancellationToken); return containingType != null && containingType.Name == typeName; } else if (semanticModel.Language == LanguageNames.VisualBasic && t.IsPartOfStructuredTrivia()) { return true; } return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal sealed class ConstructorInitializerSymbolReferenceFinder : AbstractReferenceFinder<IMethodSymbol> { protected override bool CanFind(IMethodSymbol symbol) => symbol.MethodKind == MethodKind.Constructor; protected override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IMethodSymbol symbol, HashSet<string>? globalAliases, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { return FindDocumentsAsync(project, documents, async (d, c) => { var index = await SyntaxTreeIndex.GetRequiredIndexAsync(d, c).ConfigureAwait(false); if (index.ContainsBaseConstructorInitializer) { return true; } if (index.ProbablyContainsIdentifier(symbol.ContainingType.Name)) { if (index.ContainsThisConstructorInitializer) { return true; } else if (project.Language == LanguageNames.VisualBasic && index.ProbablyContainsIdentifier("New")) { // "New" can be explicitly accessed in xml doc comments to reference a constructor. return true; } } return false; }, cancellationToken); } protected sealed override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IMethodSymbol methodSymbol, HashSet<string>? globalAliases, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var syntaxFactsService = document.GetRequiredLanguageService<ISyntaxFactsService>(); var typeName = methodSymbol.ContainingType.Name; var tokens = await document.GetConstructorInitializerTokensAsync(semanticModel, cancellationToken).ConfigureAwait(false); if (semanticModel.Language == LanguageNames.VisualBasic) { tokens = tokens.Concat(await GetIdentifierOrGlobalNamespaceTokensWithTextAsync( document, semanticModel, "New", cancellationToken).ConfigureAwait(false)).Distinct(); } return await FindReferencesInTokensAsync( methodSymbol, document, semanticModel, tokens, TokensMatch, cancellationToken).ConfigureAwait(false); // local functions bool TokensMatch(SyntaxToken t) { if (syntaxFactsService.IsBaseConstructorInitializer(t)) { var containingType = semanticModel.GetEnclosingNamedType(t.SpanStart, cancellationToken); return containingType != null && containingType.BaseType != null && containingType.BaseType.Name == typeName; } else if (syntaxFactsService.IsThisConstructorInitializer(t)) { var containingType = semanticModel.GetEnclosingNamedType(t.SpanStart, cancellationToken); return containingType != null && containingType.Name == typeName; } else if (semanticModel.Language == LanguageNames.VisualBasic && t.IsPartOfStructuredTrivia()) { return true; } return false; } } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/CodeAnalysisTest/Text/StringTextTest_BigEndianUnicode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Text; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class StringTextTest_BigEndianUnicode : StringTextTest_Default { protected override SourceText Create(string source) { byte[] buffer = GetBytes(Encoding.BigEndianUnicode, source); using (var stream = new MemoryStream(buffer, 0, buffer.Length, writable: false, publiclyVisible: true)) { return EncodedStringText.Create(stream); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Text; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class StringTextTest_BigEndianUnicode : StringTextTest_Default { protected override SourceText Create(string source) { byte[] buffer = GetBytes(Encoding.BigEndianUnicode, source); using (var stream = new MemoryStream(buffer, 0, buffer.Length, writable: false, publiclyVisible: true)) { return EncodedStringText.Create(stream); } } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/MSBuildTaskTests/TestUtilities/DotNetSdkVersionAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { /// <summary> /// Attribute added to the test assembly during build. /// Captures the version of dotnet SDK the build is targeting. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class DotNetSdkVersionAttribute : Attribute { public string Version { get; } public DotNetSdkVersionAttribute(string version) { Version = version; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { /// <summary> /// Attribute added to the test assembly during build. /// Captures the version of dotnet SDK the build is targeting. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class DotNetSdkVersionAttribute : Attribute { public string Version { get; } public DotNetSdkVersionAttribute(string version) { Version = version; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicProject.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Runtime.InteropServices Imports System.Runtime.InteropServices.ComTypes Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Partial Friend NotInheritable Class VisualBasicProject Inherits AbstractLegacyProject Implements IVbCompilerProject Private ReadOnly _compilerHost As IVbCompilerHost Private _runtimeLibraries As ImmutableArray(Of String) = ImmutableArray(Of String).Empty ''' <summary> ''' To support the old contract of VB runtimes, we must ourselves add additional references beyond what the ''' project system tells us. If the project system _also_ tells us about those, we put the in here so we can ''' record that and make removal later work properly. ''' </summary> Private ReadOnly _explicitlyAddedRuntimeLibraries As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Friend Sub New(projectSystemName As String, compilerHost As IVbCompilerHost, hierarchy As IVsHierarchy, isIntellisenseProject As Boolean, serviceProvider As IServiceProvider, threadingContext As IThreadingContext) MyBase.New(projectSystemName, hierarchy, LanguageNames.VisualBasic, isIntellisenseProject, serviceProvider, threadingContext, "VB") _compilerHost = compilerHost Dim componentModel = DirectCast(serviceProvider.GetService(GetType(SComponentModel)), IComponentModel) ProjectCodeModel = componentModel.GetService(Of IProjectCodeModelFactory).CreateProjectCodeModel(VisualStudioProject.Id, New VisualBasicCodeModelInstanceFactory(Me)) VisualStudioProjectOptionsProcessor = New OptionsProcessor(VisualStudioProject, Workspace.Services) End Sub Private Shadows Property VisualStudioProjectOptionsProcessor As OptionsProcessor Get Return DirectCast(MyBase.VisualStudioProjectOptionsProcessor, OptionsProcessor) End Get Set(value As OptionsProcessor) MyBase.VisualStudioProjectOptionsProcessor = value End Set End Property Public Sub AddApplicationObjectVariable(wszClassName As String, wszMemberName As String) Implements IVbCompilerProject.AddApplicationObjectVariable Throw New NotImplementedException() End Sub Public Sub AddBuffer(wszBuffer As String, dwLen As Integer, wszMkr As String, itemid As UInteger, fAdvise As Boolean, fShowErrorsInTaskList As Boolean) Implements IVbCompilerProject.AddBuffer Throw New NotImplementedException() End Sub Public Function AddEmbeddedMetaDataReference(wszFileName As String) As Integer Implements IVbCompilerProject.AddEmbeddedMetaDataReference VisualStudioProject.AddMetadataReference(wszFileName, New MetadataReferenceProperties(embedInteropTypes:=True)) Return VSConstants.S_OK End Function Public Overloads Function AddMetaDataReference(wszFileName As String, bAssembly As Boolean) As Integer Implements IVbCompilerProject.AddMetaDataReference ' If this is a reference already added due to it being a standard reference, just record the add If _runtimeLibraries.Contains(wszFileName, StringComparer.OrdinalIgnoreCase) Then _explicitlyAddedRuntimeLibraries.Add(wszFileName) Return VSConstants.S_OK Else VisualStudioProject.AddMetadataReference(wszFileName, MetadataReferenceProperties.Assembly) Return VSConstants.S_OK End If End Function Public Sub AddEmbeddedProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddEmbeddedProjectReference Dim referencedProject = TryCast(pReferencedCompilerProject, VisualBasicProject) If referencedProject Is Nothing Then ' Hmm, we got a project which isn't from ourselves. That's somewhat odd, and we really can't do anything ' with it. Throw New ArgumentException("Unknown type of IVbCompilerProject.", NameOf(pReferencedCompilerProject)) End If VisualStudioProject.AddProjectReference(New ProjectReference(referencedProject.VisualStudioProject.Id, embedInteropTypes:=True)) End Sub Public Shadows Sub AddFile(wszFileName As String, itemid As UInteger, fAddDuringOpen As Boolean) Implements IVbCompilerProject.AddFile MyBase.AddFile(wszFileName, SourceCodeKind.Regular) End Sub Public Sub AddImport(wszImport As String) Implements IVbCompilerProject.AddImport VisualStudioProjectOptionsProcessor.AddImport(wszImport) End Sub Public Shadows Sub AddProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddProjectReference Dim referencedProject = TryCast(pReferencedCompilerProject, VisualBasicProject) If referencedProject Is Nothing Then ' Hmm, we got a project which isn't from ourselves. That's somewhat odd, and we really can't do anything ' with it. Throw New ArgumentException("Unknown type of IVbCompilerProject.", NameOf(pReferencedCompilerProject)) End If VisualStudioProject.AddProjectReference(New ProjectReference(referencedProject.VisualStudioProject.Id)) End Sub Public Sub AddResourceReference(wszFileName As String, wszName As String, fPublic As Boolean, fEmbed As Boolean) Implements IVbCompilerProject.AddResourceReference ' TODO: implement End Sub #Region "Build Status Callbacks" ' AdviseBuildStatusCallback and UnadviseBuildStatusCallback do not accurately implement the ' contract that they imply (i.e. multiple listeners). This matches how they are implemented ' in the old VB code base: only one listener is allowed. This is a bit evil, but necessary ' since this needs to play nice with the old native project system. Private _buildStatusCallback As IVbBuildStatusCallback Public Function AdviseBuildStatusCallback(pIVbBuildStatusCallback As IVbBuildStatusCallback) As UInteger Implements IVbCompilerProject.AdviseBuildStatusCallback Try Debug.Assert(_buildStatusCallback Is Nothing, "IVbBuildStatusCallback already set") _buildStatusCallback = pIVbBuildStatusCallback If pIVbBuildStatusCallback IsNot Nothing Then ' While Roslyn doesn't have the concept of a "bound" project, this call signals to the ' project System that it can start the debugger hosting process. ' Work Item#777487 tracks the removal of this concept in Dev14 pIVbBuildStatusCallback.ProjectBound() End If Return VSConstants.S_OK Catch e As Exception When FatalError.ReportAndPropagate(e) Throw ExceptionUtilities.Unreachable End Try End Function Public Sub UnadviseBuildStatusCallback(dwCookie As UInteger) Implements IVbCompilerProject.UnadviseBuildStatusCallback Debug.Assert(dwCookie = 0, "Bad cookie") _buildStatusCallback = Nothing End Sub #End Region Public Function CreateCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef ppCodeModel As EnvDTE.CodeModel) As Integer Implements IVbCompilerProject.CreateCodeModel ppCodeModel = ProjectCodeModel.GetOrCreateRootCodeModel(pProject) Return VSConstants.S_OK End Function Public Function CreateFileCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef ppFileCodeModel As EnvDTE.FileCodeModel) As Integer Implements IVbCompilerProject.CreateFileCodeModel ppFileCodeModel = Nothing If pProjectItem IsNot Nothing Then Dim fileName = pProjectItem.FileNames(1) If Not String.IsNullOrWhiteSpace(fileName) Then ppFileCodeModel = ProjectCodeModel.GetOrCreateFileCodeModel(fileName, pProjectItem) Return VSConstants.S_OK End If End If Return VSConstants.E_INVALIDARG End Function Public Sub DeleteAllImports() Implements IVbCompilerProject.DeleteAllImports VisualStudioProjectOptionsProcessor.DeleteAllImports() End Sub Public Sub DeleteAllResourceReferences() Implements IVbCompilerProject.DeleteAllResourceReferences ' TODO: implement End Sub Public Sub DeleteImport(wszImport As String) Implements IVbCompilerProject.DeleteImport VisualStudioProjectOptionsProcessor.DeleteImport(wszImport) End Sub Public Function ENCRebuild(in_pProgram As Object, ByRef out_ppUpdate As Object) As Integer Implements IVbCompilerProject.ENCRebuild Throw New NotSupportedException() End Function Public Function GetDefaultReferences(cElements As Integer, ByRef rgbstrReferences() As String, ByVal cActualReferences As IntPtr) As Integer Implements IVbCompilerProject.GetDefaultReferences Throw New NotImplementedException() End Function Public Sub GetEntryPointsList(cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr) Implements IVbCompilerProject.GetEntryPointsList Dim project = Workspace.CurrentSolution.GetProject(VisualStudioProject.Id) Dim compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None) GetEntryPointsWorker(compilation, cItems, strList, pcActualItems, findFormsOnly:=False) End Sub Public Shared Sub GetEntryPointsWorker(compilation As Compilation, cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr, findFormsOnly As Boolean) ' If called with cItems = 0 and pcActualItems != NULL, GetEntryPointsList returns in pcActualItems the number of items available. Dim entryPoints = EntryPointFinder.FindEntryPoints(compilation.Assembly.GlobalNamespace, findFormsOnly:=findFormsOnly) If cItems = 0 AndAlso pcActualItems <> Nothing Then Marshal.WriteInt32(pcActualItems, entryPoints.Count()) Exit Sub End If ' When called with cItems != 0, GetEntryPointsList assumes that there is ' enough space in strList[] for that many items, and fills up the array with those items ' (up to maximum available). Returns in pcActualItems the actual number of items that ' were put in the array. Assumes that the caller ' takes care of array allocation and de-allocation. If cItems <> 0 Then Dim count = Math.Min(entryPoints.Count(), cItems) Dim names = entryPoints.Select(Function(p) p.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat _ .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted))) _ .ToArray() For i = 0 To count - 1 strList(i) = names(i) Next Marshal.WriteInt32(pcActualItems, count) End If End Sub Public Sub GetMethodFromLine(itemid As UInteger, iLine As Integer, ByRef pBstrProcName As String, ByRef pBstrClassName As String) Implements IVbCompilerProject.GetMethodFromLine Throw New NotImplementedException() End Sub Public Sub GetPEImage(ByRef ppImage As IntPtr) Implements IVbCompilerProject.GetPEImage Throw New NotImplementedException() End Sub Public Sub RemoveAllApplicationObjectVariables() Implements IVbCompilerProject.RemoveAllApplicationObjectVariables Throw New NotImplementedException() End Sub Public Sub RemoveAllReferences() Implements IVbCompilerProject.RemoveAllReferences Throw New NotImplementedException() End Sub Public Shadows Sub RemoveFile(wszFileName As String, itemid As UInteger) Implements IVbCompilerProject.RemoveFile MyBase.RemoveFile(wszFileName) End Sub Public Sub RemoveFileByName(wszPath As String) Implements IVbCompilerProject.RemoveFileByName Throw New NotImplementedException() End Sub Public Shadows Sub RemoveMetaDataReference(wszFileName As String) Implements IVbCompilerProject.RemoveMetaDataReference wszFileName = FileUtilities.NormalizeAbsolutePath(wszFileName) ' If this is a reference which was explicitly added and is also a runtime library, leave it If _explicitlyAddedRuntimeLibraries.Remove(wszFileName) Then Return End If VisualStudioProject.RemoveMetadataReference(wszFileName, VisualStudioProject.GetPropertiesForMetadataReference(wszFileName).Single()) End Sub Public Shadows Sub RemoveProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.RemoveProjectReference Dim referencedProject = TryCast(pReferencedCompilerProject, VisualBasicProject) If referencedProject Is Nothing Then ' Hmm, we got a project which isn't from ourselves. That's somewhat odd, and we really can't do anything ' with it. Throw New ArgumentException("Unknown type of IVbCompilerProject.", NameOf(pReferencedCompilerProject)) End If Dim projectReference = VisualStudioProject.GetProjectReferences().Single(Function(p) p.ProjectId = referencedProject.VisualStudioProject.Id) VisualStudioProject.RemoveProjectReference(projectReference) End Sub Public Sub RenameDefaultNamespace(bstrDefaultNamespace As String) Implements IVbCompilerProject.RenameDefaultNamespace ' TODO: implement End Sub Public Sub RenameFile(wszOldFileName As String, wszNewFileName As String, itemid As UInteger) Implements IVbCompilerProject.RenameFile ' We treat the rename as a removal of the old file and the addition of a new one. RemoveFile(wszOldFileName, itemid) AddFile(wszNewFileName, itemid, fAddDuringOpen:=False) End Sub Public Sub RenameProject(wszNewProjectName As String) Implements IVbCompilerProject.RenameProject ' TODO: implement End Sub Public Sub SetBackgroundCompilerPriorityLow() Implements IVbCompilerProject.SetBackgroundCompilerPriorityLow ' We don't have a background compiler in Roslyn to set the priority of. Throw New NotSupportedException() End Sub Public Sub SetBackgroundCompilerPriorityNormal() Implements IVbCompilerProject.SetBackgroundCompilerPriorityNormal ' We don't have a background compiler in Roslyn to set the priority of. Throw New NotSupportedException() End Sub Public Sub SetCompilerOptions(ByRef pCompilerOptions As VBCompilerOptions) Implements IVbCompilerProject.SetCompilerOptions Dim oldRuntimeLibraries = _runtimeLibraries VisualStudioProjectOptionsProcessor.SetNewRawOptions(pCompilerOptions) If Not String.IsNullOrEmpty(pCompilerOptions.wszExeName) Then VisualStudioProject.AssemblyName = Path.GetFileNameWithoutExtension(pCompilerOptions.wszExeName) ' Some legacy projects (e.g. Venus IntelliSense project) set '\' as the wszOutputPath. ' /src/venus/project/vb/vbprj/vbintelliproj.cpp ' Ignore paths that are not absolute. If Not String.IsNullOrEmpty(pCompilerOptions.wszOutputPath) Then If PathUtilities.IsAbsolute(pCompilerOptions.wszOutputPath) Then VisualStudioProject.CompilationOutputAssemblyFilePath = Path.Combine(pCompilerOptions.wszOutputPath, pCompilerOptions.wszExeName) Else VisualStudioProject.CompilationOutputAssemblyFilePath = Nothing End If End If End If RefreshBinOutputPath() _runtimeLibraries = VisualStudioProjectOptionsProcessor.GetRuntimeLibraries(_compilerHost) If Not _runtimeLibraries.SequenceEqual(oldRuntimeLibraries, StringComparer.Ordinal) Then Using batchScope = VisualStudioProject.CreateBatchScope() ' To keep things simple, we'll just remove everything and add everything back in For Each oldRuntimeLibrary In oldRuntimeLibraries ' If this one was added explicitly in addition to our computation, we don't have to remove it If _explicitlyAddedRuntimeLibraries.Contains(oldRuntimeLibrary) Then _explicitlyAddedRuntimeLibraries.Remove(oldRuntimeLibrary) Else VisualStudioProject.RemoveMetadataReference(oldRuntimeLibrary, MetadataReferenceProperties.Assembly) End If Next For Each newRuntimeLibrary In _runtimeLibraries newRuntimeLibrary = FileUtilities.NormalizeAbsolutePath(newRuntimeLibrary) ' If we already reference this, just skip it If VisualStudioProject.ContainsMetadataReference(newRuntimeLibrary, MetadataReferenceProperties.Assembly) Then _explicitlyAddedRuntimeLibraries.Add(newRuntimeLibrary) Else VisualStudioProject.AddMetadataReference(newRuntimeLibrary, MetadataReferenceProperties.Assembly) End If Next End Using End If End Sub Public Sub SetModuleAssemblyName(wszName As String) Implements IVbCompilerProject.SetModuleAssemblyName Throw New NotImplementedException() End Sub Public Sub SetStreamForPDB(pStreamPDB As IStream) Implements IVbCompilerProject.SetStreamForPDB Throw New NotImplementedException() End Sub Public Sub StartBuild(pVsOutputWindowPane As IVsOutputWindowPane, fRebuildAll As Boolean) Implements IVbCompilerProject.StartBuild ' We currently have nothing to do for this. End Sub Public Sub StopBuild() Implements IVbCompilerProject.StopBuild ' We currently have nothing to do for this. End Sub Public Sub StartDebugging() Implements IVbCompilerProject.StartDebugging ' We currently have nothing to do for this. End Sub Public Sub StopDebugging() Implements IVbCompilerProject.StopDebugging ' We currently have nothing to do for this. End Sub Public Sub StartEdit() Implements IVbCompilerProject.StartEdit ' Since Roslyn's creation this method has not been implemented, because we didn't have a good batching concept in the project system shim code. ' We now have that (with VisualStudioProject.CreateBatchScope), but unfortunately clients are not very well behaved. The native language service ' relies on the old behavior, which was calling VisualBasicProject.StartBackgroundCompiler/VisualBasicProject.StopBackgroundCompiler and this ' method here all increment the same global counter in the end: it was OK to call StopBackgroundCompiler to stop it but FinishEdit() to restart it. ' Rather than trying to make this all work again, we'll leave this unimplemented still until we have evidence that this will help, and time to do it. End Sub Public Sub FinishEdit() Implements IVbCompilerProject.FinishEdit ' See comment in StartEdit for why this isn't implemented. End Sub Public Sub SuspendPostedNotifications() Implements IVbCompilerProject.SuspendPostedNotifications Throw New NotSupportedException() End Sub Public Sub ResumePostedNotifications() Implements IVbCompilerProject.ResumePostedNotifications Throw New NotSupportedException() End Sub Public Sub WaitUntilBound() Implements IVbCompilerProject.WaitUntilBound ' We no longer have a concept in Roslyn equivalent to the native WaitUntilBound, since we don't have a ' background compiler in the same sense. Throw New NotSupportedException() End Sub Public Shadows Sub Disconnect() Implements IVbCompilerProject.Disconnect MyBase.Disconnect() End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Runtime.InteropServices Imports System.Runtime.InteropServices.ComTypes Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy Imports Microsoft.VisualStudio.LanguageServices.Implementation.TaskList Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Partial Friend NotInheritable Class VisualBasicProject Inherits AbstractLegacyProject Implements IVbCompilerProject Private ReadOnly _compilerHost As IVbCompilerHost Private _runtimeLibraries As ImmutableArray(Of String) = ImmutableArray(Of String).Empty ''' <summary> ''' To support the old contract of VB runtimes, we must ourselves add additional references beyond what the ''' project system tells us. If the project system _also_ tells us about those, we put the in here so we can ''' record that and make removal later work properly. ''' </summary> Private ReadOnly _explicitlyAddedRuntimeLibraries As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Friend Sub New(projectSystemName As String, compilerHost As IVbCompilerHost, hierarchy As IVsHierarchy, isIntellisenseProject As Boolean, serviceProvider As IServiceProvider, threadingContext As IThreadingContext) MyBase.New(projectSystemName, hierarchy, LanguageNames.VisualBasic, isIntellisenseProject, serviceProvider, threadingContext, "VB") _compilerHost = compilerHost Dim componentModel = DirectCast(serviceProvider.GetService(GetType(SComponentModel)), IComponentModel) ProjectCodeModel = componentModel.GetService(Of IProjectCodeModelFactory).CreateProjectCodeModel(VisualStudioProject.Id, New VisualBasicCodeModelInstanceFactory(Me)) VisualStudioProjectOptionsProcessor = New OptionsProcessor(VisualStudioProject, Workspace.Services) End Sub Private Shadows Property VisualStudioProjectOptionsProcessor As OptionsProcessor Get Return DirectCast(MyBase.VisualStudioProjectOptionsProcessor, OptionsProcessor) End Get Set(value As OptionsProcessor) MyBase.VisualStudioProjectOptionsProcessor = value End Set End Property Public Sub AddApplicationObjectVariable(wszClassName As String, wszMemberName As String) Implements IVbCompilerProject.AddApplicationObjectVariable Throw New NotImplementedException() End Sub Public Sub AddBuffer(wszBuffer As String, dwLen As Integer, wszMkr As String, itemid As UInteger, fAdvise As Boolean, fShowErrorsInTaskList As Boolean) Implements IVbCompilerProject.AddBuffer Throw New NotImplementedException() End Sub Public Function AddEmbeddedMetaDataReference(wszFileName As String) As Integer Implements IVbCompilerProject.AddEmbeddedMetaDataReference VisualStudioProject.AddMetadataReference(wszFileName, New MetadataReferenceProperties(embedInteropTypes:=True)) Return VSConstants.S_OK End Function Public Overloads Function AddMetaDataReference(wszFileName As String, bAssembly As Boolean) As Integer Implements IVbCompilerProject.AddMetaDataReference ' If this is a reference already added due to it being a standard reference, just record the add If _runtimeLibraries.Contains(wszFileName, StringComparer.OrdinalIgnoreCase) Then _explicitlyAddedRuntimeLibraries.Add(wszFileName) Return VSConstants.S_OK Else VisualStudioProject.AddMetadataReference(wszFileName, MetadataReferenceProperties.Assembly) Return VSConstants.S_OK End If End Function Public Sub AddEmbeddedProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddEmbeddedProjectReference Dim referencedProject = TryCast(pReferencedCompilerProject, VisualBasicProject) If referencedProject Is Nothing Then ' Hmm, we got a project which isn't from ourselves. That's somewhat odd, and we really can't do anything ' with it. Throw New ArgumentException("Unknown type of IVbCompilerProject.", NameOf(pReferencedCompilerProject)) End If VisualStudioProject.AddProjectReference(New ProjectReference(referencedProject.VisualStudioProject.Id, embedInteropTypes:=True)) End Sub Public Shadows Sub AddFile(wszFileName As String, itemid As UInteger, fAddDuringOpen As Boolean) Implements IVbCompilerProject.AddFile MyBase.AddFile(wszFileName, SourceCodeKind.Regular) End Sub Public Sub AddImport(wszImport As String) Implements IVbCompilerProject.AddImport VisualStudioProjectOptionsProcessor.AddImport(wszImport) End Sub Public Shadows Sub AddProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddProjectReference Dim referencedProject = TryCast(pReferencedCompilerProject, VisualBasicProject) If referencedProject Is Nothing Then ' Hmm, we got a project which isn't from ourselves. That's somewhat odd, and we really can't do anything ' with it. Throw New ArgumentException("Unknown type of IVbCompilerProject.", NameOf(pReferencedCompilerProject)) End If VisualStudioProject.AddProjectReference(New ProjectReference(referencedProject.VisualStudioProject.Id)) End Sub Public Sub AddResourceReference(wszFileName As String, wszName As String, fPublic As Boolean, fEmbed As Boolean) Implements IVbCompilerProject.AddResourceReference ' TODO: implement End Sub #Region "Build Status Callbacks" ' AdviseBuildStatusCallback and UnadviseBuildStatusCallback do not accurately implement the ' contract that they imply (i.e. multiple listeners). This matches how they are implemented ' in the old VB code base: only one listener is allowed. This is a bit evil, but necessary ' since this needs to play nice with the old native project system. Private _buildStatusCallback As IVbBuildStatusCallback Public Function AdviseBuildStatusCallback(pIVbBuildStatusCallback As IVbBuildStatusCallback) As UInteger Implements IVbCompilerProject.AdviseBuildStatusCallback Try Debug.Assert(_buildStatusCallback Is Nothing, "IVbBuildStatusCallback already set") _buildStatusCallback = pIVbBuildStatusCallback If pIVbBuildStatusCallback IsNot Nothing Then ' While Roslyn doesn't have the concept of a "bound" project, this call signals to the ' project System that it can start the debugger hosting process. ' Work Item#777487 tracks the removal of this concept in Dev14 pIVbBuildStatusCallback.ProjectBound() End If Return VSConstants.S_OK Catch e As Exception When FatalError.ReportAndPropagate(e) Throw ExceptionUtilities.Unreachable End Try End Function Public Sub UnadviseBuildStatusCallback(dwCookie As UInteger) Implements IVbCompilerProject.UnadviseBuildStatusCallback Debug.Assert(dwCookie = 0, "Bad cookie") _buildStatusCallback = Nothing End Sub #End Region Public Function CreateCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef ppCodeModel As EnvDTE.CodeModel) As Integer Implements IVbCompilerProject.CreateCodeModel ppCodeModel = ProjectCodeModel.GetOrCreateRootCodeModel(pProject) Return VSConstants.S_OK End Function Public Function CreateFileCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef ppFileCodeModel As EnvDTE.FileCodeModel) As Integer Implements IVbCompilerProject.CreateFileCodeModel ppFileCodeModel = Nothing If pProjectItem IsNot Nothing Then Dim fileName = pProjectItem.FileNames(1) If Not String.IsNullOrWhiteSpace(fileName) Then ppFileCodeModel = ProjectCodeModel.GetOrCreateFileCodeModel(fileName, pProjectItem) Return VSConstants.S_OK End If End If Return VSConstants.E_INVALIDARG End Function Public Sub DeleteAllImports() Implements IVbCompilerProject.DeleteAllImports VisualStudioProjectOptionsProcessor.DeleteAllImports() End Sub Public Sub DeleteAllResourceReferences() Implements IVbCompilerProject.DeleteAllResourceReferences ' TODO: implement End Sub Public Sub DeleteImport(wszImport As String) Implements IVbCompilerProject.DeleteImport VisualStudioProjectOptionsProcessor.DeleteImport(wszImport) End Sub Public Function ENCRebuild(in_pProgram As Object, ByRef out_ppUpdate As Object) As Integer Implements IVbCompilerProject.ENCRebuild Throw New NotSupportedException() End Function Public Function GetDefaultReferences(cElements As Integer, ByRef rgbstrReferences() As String, ByVal cActualReferences As IntPtr) As Integer Implements IVbCompilerProject.GetDefaultReferences Throw New NotImplementedException() End Function Public Sub GetEntryPointsList(cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr) Implements IVbCompilerProject.GetEntryPointsList Dim project = Workspace.CurrentSolution.GetProject(VisualStudioProject.Id) Dim compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None) GetEntryPointsWorker(compilation, cItems, strList, pcActualItems, findFormsOnly:=False) End Sub Public Shared Sub GetEntryPointsWorker(compilation As Compilation, cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr, findFormsOnly As Boolean) ' If called with cItems = 0 and pcActualItems != NULL, GetEntryPointsList returns in pcActualItems the number of items available. Dim entryPoints = EntryPointFinder.FindEntryPoints(compilation.Assembly.GlobalNamespace, findFormsOnly:=findFormsOnly) If cItems = 0 AndAlso pcActualItems <> Nothing Then Marshal.WriteInt32(pcActualItems, entryPoints.Count()) Exit Sub End If ' When called with cItems != 0, GetEntryPointsList assumes that there is ' enough space in strList[] for that many items, and fills up the array with those items ' (up to maximum available). Returns in pcActualItems the actual number of items that ' were put in the array. Assumes that the caller ' takes care of array allocation and de-allocation. If cItems <> 0 Then Dim count = Math.Min(entryPoints.Count(), cItems) Dim names = entryPoints.Select(Function(p) p.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat _ .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted))) _ .ToArray() For i = 0 To count - 1 strList(i) = names(i) Next Marshal.WriteInt32(pcActualItems, count) End If End Sub Public Sub GetMethodFromLine(itemid As UInteger, iLine As Integer, ByRef pBstrProcName As String, ByRef pBstrClassName As String) Implements IVbCompilerProject.GetMethodFromLine Throw New NotImplementedException() End Sub Public Sub GetPEImage(ByRef ppImage As IntPtr) Implements IVbCompilerProject.GetPEImage Throw New NotImplementedException() End Sub Public Sub RemoveAllApplicationObjectVariables() Implements IVbCompilerProject.RemoveAllApplicationObjectVariables Throw New NotImplementedException() End Sub Public Sub RemoveAllReferences() Implements IVbCompilerProject.RemoveAllReferences Throw New NotImplementedException() End Sub Public Shadows Sub RemoveFile(wszFileName As String, itemid As UInteger) Implements IVbCompilerProject.RemoveFile MyBase.RemoveFile(wszFileName) End Sub Public Sub RemoveFileByName(wszPath As String) Implements IVbCompilerProject.RemoveFileByName Throw New NotImplementedException() End Sub Public Shadows Sub RemoveMetaDataReference(wszFileName As String) Implements IVbCompilerProject.RemoveMetaDataReference wszFileName = FileUtilities.NormalizeAbsolutePath(wszFileName) ' If this is a reference which was explicitly added and is also a runtime library, leave it If _explicitlyAddedRuntimeLibraries.Remove(wszFileName) Then Return End If VisualStudioProject.RemoveMetadataReference(wszFileName, VisualStudioProject.GetPropertiesForMetadataReference(wszFileName).Single()) End Sub Public Shadows Sub RemoveProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.RemoveProjectReference Dim referencedProject = TryCast(pReferencedCompilerProject, VisualBasicProject) If referencedProject Is Nothing Then ' Hmm, we got a project which isn't from ourselves. That's somewhat odd, and we really can't do anything ' with it. Throw New ArgumentException("Unknown type of IVbCompilerProject.", NameOf(pReferencedCompilerProject)) End If Dim projectReference = VisualStudioProject.GetProjectReferences().Single(Function(p) p.ProjectId = referencedProject.VisualStudioProject.Id) VisualStudioProject.RemoveProjectReference(projectReference) End Sub Public Sub RenameDefaultNamespace(bstrDefaultNamespace As String) Implements IVbCompilerProject.RenameDefaultNamespace ' TODO: implement End Sub Public Sub RenameFile(wszOldFileName As String, wszNewFileName As String, itemid As UInteger) Implements IVbCompilerProject.RenameFile ' We treat the rename as a removal of the old file and the addition of a new one. RemoveFile(wszOldFileName, itemid) AddFile(wszNewFileName, itemid, fAddDuringOpen:=False) End Sub Public Sub RenameProject(wszNewProjectName As String) Implements IVbCompilerProject.RenameProject ' TODO: implement End Sub Public Sub SetBackgroundCompilerPriorityLow() Implements IVbCompilerProject.SetBackgroundCompilerPriorityLow ' We don't have a background compiler in Roslyn to set the priority of. Throw New NotSupportedException() End Sub Public Sub SetBackgroundCompilerPriorityNormal() Implements IVbCompilerProject.SetBackgroundCompilerPriorityNormal ' We don't have a background compiler in Roslyn to set the priority of. Throw New NotSupportedException() End Sub Public Sub SetCompilerOptions(ByRef pCompilerOptions As VBCompilerOptions) Implements IVbCompilerProject.SetCompilerOptions Dim oldRuntimeLibraries = _runtimeLibraries VisualStudioProjectOptionsProcessor.SetNewRawOptions(pCompilerOptions) If Not String.IsNullOrEmpty(pCompilerOptions.wszExeName) Then VisualStudioProject.AssemblyName = Path.GetFileNameWithoutExtension(pCompilerOptions.wszExeName) ' Some legacy projects (e.g. Venus IntelliSense project) set '\' as the wszOutputPath. ' /src/venus/project/vb/vbprj/vbintelliproj.cpp ' Ignore paths that are not absolute. If Not String.IsNullOrEmpty(pCompilerOptions.wszOutputPath) Then If PathUtilities.IsAbsolute(pCompilerOptions.wszOutputPath) Then VisualStudioProject.CompilationOutputAssemblyFilePath = Path.Combine(pCompilerOptions.wszOutputPath, pCompilerOptions.wszExeName) Else VisualStudioProject.CompilationOutputAssemblyFilePath = Nothing End If End If End If RefreshBinOutputPath() _runtimeLibraries = VisualStudioProjectOptionsProcessor.GetRuntimeLibraries(_compilerHost) If Not _runtimeLibraries.SequenceEqual(oldRuntimeLibraries, StringComparer.Ordinal) Then Using batchScope = VisualStudioProject.CreateBatchScope() ' To keep things simple, we'll just remove everything and add everything back in For Each oldRuntimeLibrary In oldRuntimeLibraries ' If this one was added explicitly in addition to our computation, we don't have to remove it If _explicitlyAddedRuntimeLibraries.Contains(oldRuntimeLibrary) Then _explicitlyAddedRuntimeLibraries.Remove(oldRuntimeLibrary) Else VisualStudioProject.RemoveMetadataReference(oldRuntimeLibrary, MetadataReferenceProperties.Assembly) End If Next For Each newRuntimeLibrary In _runtimeLibraries newRuntimeLibrary = FileUtilities.NormalizeAbsolutePath(newRuntimeLibrary) ' If we already reference this, just skip it If VisualStudioProject.ContainsMetadataReference(newRuntimeLibrary, MetadataReferenceProperties.Assembly) Then _explicitlyAddedRuntimeLibraries.Add(newRuntimeLibrary) Else VisualStudioProject.AddMetadataReference(newRuntimeLibrary, MetadataReferenceProperties.Assembly) End If Next End Using End If End Sub Public Sub SetModuleAssemblyName(wszName As String) Implements IVbCompilerProject.SetModuleAssemblyName Throw New NotImplementedException() End Sub Public Sub SetStreamForPDB(pStreamPDB As IStream) Implements IVbCompilerProject.SetStreamForPDB Throw New NotImplementedException() End Sub Public Sub StartBuild(pVsOutputWindowPane As IVsOutputWindowPane, fRebuildAll As Boolean) Implements IVbCompilerProject.StartBuild ' We currently have nothing to do for this. End Sub Public Sub StopBuild() Implements IVbCompilerProject.StopBuild ' We currently have nothing to do for this. End Sub Public Sub StartDebugging() Implements IVbCompilerProject.StartDebugging ' We currently have nothing to do for this. End Sub Public Sub StopDebugging() Implements IVbCompilerProject.StopDebugging ' We currently have nothing to do for this. End Sub Public Sub StartEdit() Implements IVbCompilerProject.StartEdit ' Since Roslyn's creation this method has not been implemented, because we didn't have a good batching concept in the project system shim code. ' We now have that (with VisualStudioProject.CreateBatchScope), but unfortunately clients are not very well behaved. The native language service ' relies on the old behavior, which was calling VisualBasicProject.StartBackgroundCompiler/VisualBasicProject.StopBackgroundCompiler and this ' method here all increment the same global counter in the end: it was OK to call StopBackgroundCompiler to stop it but FinishEdit() to restart it. ' Rather than trying to make this all work again, we'll leave this unimplemented still until we have evidence that this will help, and time to do it. End Sub Public Sub FinishEdit() Implements IVbCompilerProject.FinishEdit ' See comment in StartEdit for why this isn't implemented. End Sub Public Sub SuspendPostedNotifications() Implements IVbCompilerProject.SuspendPostedNotifications Throw New NotSupportedException() End Sub Public Sub ResumePostedNotifications() Implements IVbCompilerProject.ResumePostedNotifications Throw New NotSupportedException() End Sub Public Sub WaitUntilBound() Implements IVbCompilerProject.WaitUntilBound ' We no longer have a concept in Roslyn equivalent to the native WaitUntilBound, since we don't have a ' background compiler in the same sense. Throw New NotSupportedException() End Sub Public Shadows Sub Disconnect() Implements IVbCompilerProject.Disconnect MyBase.Disconnect() End Sub End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/VisualBasic/Portable/DocumentationComments/CodeFixes/VisualBasicRemoveDocCommentNodeCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.DiagnosticComments.CodeFixes <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveDocCommentNode), [Shared]> Friend Class VisualBasicRemoveDocCommentNodeCodeFixProvider Inherits AbstractRemoveDocCommentNodeCodeFixProvider(Of XmlElementSyntax, XmlTextSyntax) ''' <summary> ''' XML comment tag with identical attributes ''' </summary> Private Const BC42305 As String = NameOf(BC42305) ''' <summary> ''' XML comment tag is not permitted on a 'sub' language element ''' </summary> Private Const BC42306 As String = NameOf(BC42306) ''' <summary> ''' XML comment type parameter does not match a type parameter ''' </summary> Private Const BC42307 As String = NameOf(BC42307) ''' <summary> ''' XML comment tag 'returns' is not permitted on a 'WriteOnly' property ''' </summary> Private Const BC42313 As String = NameOf(BC42313) ''' <summary> ''' XML comment tag 'returns' is not permitted on a 'declare sub' language element ''' </summary> Private Const BC42315 As String = NameOf(BC42315) ''' <summary> ''' XML comment type parameter does not match a type parameter ''' </summary> Private Const BC42317 As String = NameOf(BC42317) Friend ReadOnly Id As ImmutableArray(Of String) = ImmutableArray.Create(BC42305, BC42306, BC42307, BC42313, BC42315, BC42317) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return Id End Get End Property Protected Overrides ReadOnly Property DocCommentSignifierToken As String Get Return "'''" End Get End Property Protected Overrides Function GetRevisedDocCommentTrivia(docCommentText As String) As SyntaxTriviaList Return SyntaxFactory.ParseLeadingTrivia(docCommentText) End Function Protected Overrides Function GetTextTokens(xmlText As XmlTextSyntax) As SyntaxTokenList Return xmlText.TextTokens End Function Protected Overrides Function IsXmlWhitespaceToken(token As SyntaxToken) As Boolean Return token.Kind() = SyntaxKind.XmlTextLiteralToken AndAlso IsWhitespace(token.Text) End Function Protected Overrides Function IsXmlNewLineToken(token As SyntaxToken) As Boolean Return token.Kind() = SyntaxKind.DocumentationCommentLineBreakToken End Function Private Shared Function IsWhitespace(text As String) As Boolean For Each c In text If Not SyntaxFacts.IsWhitespace(c) Then Return False End If Next Return True End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.DiagnosticComments.CodeFixes <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.RemoveDocCommentNode), [Shared]> Friend Class VisualBasicRemoveDocCommentNodeCodeFixProvider Inherits AbstractRemoveDocCommentNodeCodeFixProvider(Of XmlElementSyntax, XmlTextSyntax) ''' <summary> ''' XML comment tag with identical attributes ''' </summary> Private Const BC42305 As String = NameOf(BC42305) ''' <summary> ''' XML comment tag is not permitted on a 'sub' language element ''' </summary> Private Const BC42306 As String = NameOf(BC42306) ''' <summary> ''' XML comment type parameter does not match a type parameter ''' </summary> Private Const BC42307 As String = NameOf(BC42307) ''' <summary> ''' XML comment tag 'returns' is not permitted on a 'WriteOnly' property ''' </summary> Private Const BC42313 As String = NameOf(BC42313) ''' <summary> ''' XML comment tag 'returns' is not permitted on a 'declare sub' language element ''' </summary> Private Const BC42315 As String = NameOf(BC42315) ''' <summary> ''' XML comment type parameter does not match a type parameter ''' </summary> Private Const BC42317 As String = NameOf(BC42317) Friend ReadOnly Id As ImmutableArray(Of String) = ImmutableArray.Create(BC42305, BC42306, BC42307, BC42313, BC42315, BC42317) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return Id End Get End Property Protected Overrides ReadOnly Property DocCommentSignifierToken As String Get Return "'''" End Get End Property Protected Overrides Function GetRevisedDocCommentTrivia(docCommentText As String) As SyntaxTriviaList Return SyntaxFactory.ParseLeadingTrivia(docCommentText) End Function Protected Overrides Function GetTextTokens(xmlText As XmlTextSyntax) As SyntaxTokenList Return xmlText.TextTokens End Function Protected Overrides Function IsXmlWhitespaceToken(token As SyntaxToken) As Boolean Return token.Kind() = SyntaxKind.XmlTextLiteralToken AndAlso IsWhitespace(token.Text) End Function Protected Overrides Function IsXmlNewLineToken(token As SyntaxToken) As Boolean Return token.Kind() = SyntaxKind.DocumentationCommentLineBreakToken End Function Private Shared Function IsWhitespace(text As String) As Boolean For Each c In text If Not SyntaxFacts.IsWhitespace(c) Then Return False End If Next Return True End Function End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/Core/Portable/Workspace/Host/Mef/ExportLanguageServiceAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="ILanguageService"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportLanguageServiceAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The language that the service is target for; LanguageNames.CSharp, etc. /// </summary> public string Language { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="ILanguageService"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="type">The type that will be used to retrieve the service from a <see cref="HostLanguageServices"/>.</param> /// <param name="language">The language that the service is target for; LanguageNames.CSharp, etc.</param> /// <param name="layer">The layer that the service is specified for; ServiceLayer.Default, etc.</param> public ExportLanguageServiceAttribute(Type type, string language, string layer = ServiceLayer.Default) : base(typeof(ILanguageService)) { if (type == null) { throw new ArgumentNullException(nameof(type)); } this.ServiceType = type.AssemblyQualifiedName; this.Language = language ?? throw new ArgumentNullException(nameof(language)); this.Layer = layer; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="ILanguageService"/> implementation for inclusion in a MEF-based workspace. /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] public class ExportLanguageServiceAttribute : ExportAttribute { /// <summary> /// The assembly qualified name of the service's type. /// </summary> public string ServiceType { get; } /// <summary> /// The language that the service is target for; LanguageNames.CSharp, etc. /// </summary> public string Language { get; } /// <summary> /// The layer that the service is specified for; ServiceLayer.Default, etc. /// </summary> public string Layer { get; } /// <summary> /// Declares a <see cref="ILanguageService"/> implementation for inclusion in a MEF-based workspace. /// </summary> /// <param name="type">The type that will be used to retrieve the service from a <see cref="HostLanguageServices"/>.</param> /// <param name="language">The language that the service is target for; LanguageNames.CSharp, etc.</param> /// <param name="layer">The layer that the service is specified for; ServiceLayer.Default, etc.</param> public ExportLanguageServiceAttribute(Type type, string language, string layer = ServiceLayer.Default) : base(typeof(ILanguageService)) { if (type == null) { throw new ArgumentNullException(nameof(type)); } this.ServiceType = type.AssemblyQualifiedName; this.Language = language ?? throw new ArgumentNullException(nameof(language)); this.Layer = layer; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/EditorFeatures/VisualBasicTest/Recommendations/Statements/YieldKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class YieldKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Yield") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InLambdaBodyTest() Dim code = <MethodBody> Dim f = Function() | End Function </MethodBody> VerifyRecommendationsContain(code, "Yield") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInExpressionTest() Dim code = <MethodBody> Dim f = | </MethodBody> VerifyRecommendationsMissing(code, "Yield") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Statements Public Class YieldKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Yield") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InLambdaBodyTest() Dim code = <MethodBody> Dim f = Function() | End Function </MethodBody> VerifyRecommendationsContain(code, "Yield") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInExpressionTest() Dim code = <MethodBody> Dim f = | </MethodBody> VerifyRecommendationsMissing(code, "Yield") End Sub End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/EnumMemberDeclarationStructureTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class EnumMemberDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EnumMemberDeclarationSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New EnumMemberDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Enum E $$Goo Bar End Enum " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Enum E {|hint:{|textspan:<Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Enum E {|hint:{|textspan:' Summary: ' This is a summary. <Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class EnumMemberDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EnumMemberDeclarationSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New EnumMemberDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Enum E $$Goo Bar End Enum " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Enum E {|hint:{|textspan:<Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Enum E {|hint:{|textspan:' Summary: ' This is a summary. <Blah> |}$$Goo|} Bar End Enum " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/VisualBasic/Portable/Syntax/StructuredTriviaSyntax.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------------------------------------- ' Contains hand-written Partial class extensions to certain of the syntax nodes (other that the ' base node SyntaxNode, which is in a different file.) '----------------------------------------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class StructuredTriviaSyntax Inherits VisualBasicSyntaxNode Implements IStructuredTriviaSyntax Private _parentTrivia As SyntaxTrivia Friend Sub New(green As GreenNode, parent As SyntaxNode, startLocation As Integer) MyBase.New(green, startLocation, If(parent IsNot Nothing, parent.SyntaxTree, Nothing)) End Sub Friend Shared Function Create(trivia As SyntaxTrivia) As StructuredTriviaSyntax Dim parent = DirectCast(trivia.Token.Parent, VisualBasicSyntaxNode) Dim position = trivia.Position Dim red = DirectCast(trivia.UnderlyingNode.CreateRed(parent, position), StructuredTriviaSyntax) red._parentTrivia = trivia Return red End Function Public Overrides ReadOnly Property ParentTrivia As SyntaxTrivia Implements IStructuredTriviaSyntax.ParentTrivia Get Return _parentTrivia End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax '----------------------------------------------------------------------------------------------------------- ' Contains hand-written Partial class extensions to certain of the syntax nodes (other that the ' base node SyntaxNode, which is in a different file.) '----------------------------------------------------------------------------------------------------------- Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Partial Public Class StructuredTriviaSyntax Inherits VisualBasicSyntaxNode Implements IStructuredTriviaSyntax Private _parentTrivia As SyntaxTrivia Friend Sub New(green As GreenNode, parent As SyntaxNode, startLocation As Integer) MyBase.New(green, startLocation, If(parent IsNot Nothing, parent.SyntaxTree, Nothing)) End Sub Friend Shared Function Create(trivia As SyntaxTrivia) As StructuredTriviaSyntax Dim parent = DirectCast(trivia.Token.Parent, VisualBasicSyntaxNode) Dim position = trivia.Position Dim red = DirectCast(trivia.UnderlyingNode.CreateRed(parent, position), StructuredTriviaSyntax) red._parentTrivia = trivia Return red End Function Public Overrides ReadOnly Property ParentTrivia As SyntaxTrivia Implements IStructuredTriviaSyntax.ParentTrivia Get Return _parentTrivia End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/Core/Def/Implementation/GCManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { /// <summary> /// This class manages setting the GC mode to SustainedLowLatency. /// /// It is safe to call from any thread, but is intended to be called from /// the UI thread whenever user keyboard or mouse input is received. /// </summary> internal static class GCManager { // The default delay can be overridden by setting <VS Registry>\Performance : SustainedLowLatencyDuration private static int s_delayMilliseconds = 0; private const int DefaultDelayMilliseconds = 5000; private static ResettableDelay s_delay; static GCManager() { // Allow disabling SustainedLowLatency by setting the reg key value to 0 System.Threading.Tasks.Task.Run(() => { using (var root = VSRegistry.RegistryRoot(__VsLocalRegistryType.RegType_UserSettings)) { if (root != null) { using var key = root.OpenSubKey("Performance"); const string name = "SustainedLowLatencyDuration"; if (key != null && key.GetValue(name) != null && key.GetValueKind(name) == Microsoft.Win32.RegistryValueKind.DWord) { s_delayMilliseconds = (int)key.GetValue(name, s_delayMilliseconds); return; } } } s_delayMilliseconds = DefaultDelayMilliseconds; }); } /// <summary> /// Turn off low latency GC mode. /// /// if there is a pending low latency mode request, Latency mode will go back to its original status as /// pending request timeout. once it goes back to its original status, it will not go back to low latency mode again. /// </summary> internal static void TurnOffLowLatencyMode() { // set delay to 0 to turn off the use of sustained low latency s_delayMilliseconds = 0; } /// <summary> /// Call this method to suppress expensive blocking Gen 2 garbage GCs in /// scenarios where high-latency is unacceptable (e.g. processing typing input). /// /// Blocking GCs will be re-enabled automatically after a short duration unless /// UseLowLatencyModeForProcessingUserInput is called again. /// </summary> internal static void UseLowLatencyModeForProcessingUserInput() { if (s_delayMilliseconds <= 0) { // The registry key to opt out of Roslyn's SustainedLowLatency is set, or // we haven't yet initialized the value. return; } var currentMode = GCSettings.LatencyMode; var currentDelay = s_delay; if (currentMode != GCLatencyMode.SustainedLowLatency) { GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency; // Restore the LatencyMode a short duration after the // last request to UseLowLatencyModeForProcessingUserInput. currentDelay = new ResettableDelay(s_delayMilliseconds, AsynchronousOperationListenerProvider.NullListener); currentDelay.Task.SafeContinueWith(_ => RestoreGCLatencyMode(currentMode), TaskScheduler.Default); s_delay = currentDelay; } if (currentDelay != null) { currentDelay.Reset(); } } private static void RestoreGCLatencyMode(GCLatencyMode originalMode) { GCSettings.LatencyMode = originalMode; s_delay = null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation { /// <summary> /// This class manages setting the GC mode to SustainedLowLatency. /// /// It is safe to call from any thread, but is intended to be called from /// the UI thread whenever user keyboard or mouse input is received. /// </summary> internal static class GCManager { // The default delay can be overridden by setting <VS Registry>\Performance : SustainedLowLatencyDuration private static int s_delayMilliseconds = 0; private const int DefaultDelayMilliseconds = 5000; private static ResettableDelay s_delay; static GCManager() { // Allow disabling SustainedLowLatency by setting the reg key value to 0 System.Threading.Tasks.Task.Run(() => { using (var root = VSRegistry.RegistryRoot(__VsLocalRegistryType.RegType_UserSettings)) { if (root != null) { using var key = root.OpenSubKey("Performance"); const string name = "SustainedLowLatencyDuration"; if (key != null && key.GetValue(name) != null && key.GetValueKind(name) == Microsoft.Win32.RegistryValueKind.DWord) { s_delayMilliseconds = (int)key.GetValue(name, s_delayMilliseconds); return; } } } s_delayMilliseconds = DefaultDelayMilliseconds; }); } /// <summary> /// Turn off low latency GC mode. /// /// if there is a pending low latency mode request, Latency mode will go back to its original status as /// pending request timeout. once it goes back to its original status, it will not go back to low latency mode again. /// </summary> internal static void TurnOffLowLatencyMode() { // set delay to 0 to turn off the use of sustained low latency s_delayMilliseconds = 0; } /// <summary> /// Call this method to suppress expensive blocking Gen 2 garbage GCs in /// scenarios where high-latency is unacceptable (e.g. processing typing input). /// /// Blocking GCs will be re-enabled automatically after a short duration unless /// UseLowLatencyModeForProcessingUserInput is called again. /// </summary> internal static void UseLowLatencyModeForProcessingUserInput() { if (s_delayMilliseconds <= 0) { // The registry key to opt out of Roslyn's SustainedLowLatency is set, or // we haven't yet initialized the value. return; } var currentMode = GCSettings.LatencyMode; var currentDelay = s_delay; if (currentMode != GCLatencyMode.SustainedLowLatency) { GCSettings.LatencyMode = GCLatencyMode.SustainedLowLatency; // Restore the LatencyMode a short duration after the // last request to UseLowLatencyModeForProcessingUserInput. currentDelay = new ResettableDelay(s_delayMilliseconds, AsynchronousOperationListenerProvider.NullListener); currentDelay.Task.SafeContinueWith(_ => RestoreGCLatencyMode(currentMode), TaskScheduler.Default); s_delay = currentDelay; } if (currentDelay != null) { currentDelay.Reset(); } } private static void RestoreGCLatencyMode(GCLatencyMode originalMode) { GCSettings.LatencyMode = originalMode; s_delay = null; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/PEWriter/PooledBlobBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { internal sealed class PooledBlobBuilder : BlobBuilder, IDisposable { private const int PoolSize = 128; private const int ChunkSize = 1024; private static readonly ObjectPool<PooledBlobBuilder> s_chunkPool = new ObjectPool<PooledBlobBuilder>(() => new PooledBlobBuilder(ChunkSize), PoolSize); private PooledBlobBuilder(int size) : base(size) { } public static PooledBlobBuilder GetInstance(int size = ChunkSize) { // TODO: use size return s_chunkPool.Allocate(); } protected override BlobBuilder AllocateChunk(int minimalSize) { if (minimalSize <= ChunkSize) { return s_chunkPool.Allocate(); } return new BlobBuilder(minimalSize); } protected override void FreeChunk() { s_chunkPool.Free(this); } public new void Free() { base.Free(); } void IDisposable.Dispose() { Free(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; namespace Microsoft.Cci { internal sealed class PooledBlobBuilder : BlobBuilder, IDisposable { private const int PoolSize = 128; private const int ChunkSize = 1024; private static readonly ObjectPool<PooledBlobBuilder> s_chunkPool = new ObjectPool<PooledBlobBuilder>(() => new PooledBlobBuilder(ChunkSize), PoolSize); private PooledBlobBuilder(int size) : base(size) { } public static PooledBlobBuilder GetInstance(int size = ChunkSize) { // TODO: use size return s_chunkPool.Allocate(); } protected override BlobBuilder AllocateChunk(int minimalSize) { if (minimalSize <= ChunkSize) { return s_chunkPool.Allocate(); } return new BlobBuilder(minimalSize); } protected override void FreeChunk() { s_chunkPool.Free(this); } public new void Free() { base.Free(); } void IDisposable.Dispose() { Free(); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/Core/Test/CodeModel/MethodXML/MethodXMLTests_VBInitializeComponent_TestContent.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests Private Shared ReadOnly s_initializeComponentXML1 As XElement = <Block> <ExpressionStatement line="24"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>components</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.ComponentModel.Container</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="25"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>AutoScaleMode</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>System.Windows.Forms.AutoScaleMode</Type> </Literal> </Expression> <Name>Font</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="26"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Text</Name> </NameRef> </Expression> <Expression> <Literal> <String>Form1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Private Shared ReadOnly s_initializeComponentXML2 As XElement = <Block> <ExpressionStatement line="24"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Windows.Forms.Button</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="25"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>SuspendLayout</Name> </NameRef> </Expression> </MethodCall> </Expression> </ExpressionStatement> <ExpressionStatement line="29"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Location</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.Point</Type> <Argument> <Expression> <Literal> <Number type="System.Int32">87</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">56</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="30"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Name</Name> </NameRef> </Expression> <Expression> <Literal> <String>Button1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="31"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Size</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.Size</Type> <Argument> <Expression> <Literal> <Number type="System.Int32">75</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">23</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="32"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>TabIndex</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="33"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Text</Name> </NameRef> </Expression> <Expression> <Literal> <String>Button1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="34"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>UseVisualStyleBackColor</Name> </NameRef> </Expression> <Expression> <Literal> <Boolean>true</Boolean> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="38"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>AutoScaleDimensions</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.SizeF</Type> <Argument> <Expression> <Literal> <Number type="System.Single">6</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Single">13</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="39"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>AutoScaleMode</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>System.Windows.Forms.AutoScaleMode</Type> </Literal> </Expression> <Name>Font</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="40"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>ClientSize</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.Size</Type> <Argument> <Expression> <Literal> <Number type="System.Int32">284</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">262</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="41"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Controls</Name> </NameRef> </Expression> <Name>Add</Name> </NameRef> </Expression> <Argument> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> </Argument> </MethodCall> </Expression> </ExpressionStatement> <ExpressionStatement line="42"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Name</Name> </NameRef> </Expression> <Expression> <Literal> <String>Form1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="43"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Text</Name> </NameRef> </Expression> <Expression> <Literal> <String>Form1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="44"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>ResumeLayout</Name> </NameRef> </Expression> <Argument> <Expression> <Literal> <Boolean>false</Boolean> </Literal> </Expression> </Argument> </MethodCall> </Expression> </ExpressionStatement> </Block> End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests Private Shared ReadOnly s_initializeComponentXML1 As XElement = <Block> <ExpressionStatement line="24"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>components</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.ComponentModel.Container</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="25"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>AutoScaleMode</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>System.Windows.Forms.AutoScaleMode</Type> </Literal> </Expression> <Name>Font</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="26"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Text</Name> </NameRef> </Expression> <Expression> <Literal> <String>Form1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Private Shared ReadOnly s_initializeComponentXML2 As XElement = <Block> <ExpressionStatement line="24"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Windows.Forms.Button</Type> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="25"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>SuspendLayout</Name> </NameRef> </Expression> </MethodCall> </Expression> </ExpressionStatement> <ExpressionStatement line="29"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Location</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.Point</Type> <Argument> <Expression> <Literal> <Number type="System.Int32">87</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">56</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="30"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Name</Name> </NameRef> </Expression> <Expression> <Literal> <String>Button1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="31"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Size</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.Size</Type> <Argument> <Expression> <Literal> <Number type="System.Int32">75</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">23</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="32"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>TabIndex</Name> </NameRef> </Expression> <Expression> <Literal> <Number type="System.Int32">0</Number> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="33"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>Text</Name> </NameRef> </Expression> <Expression> <Literal> <String>Button1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="34"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> <Name>UseVisualStyleBackColor</Name> </NameRef> </Expression> <Expression> <Literal> <Boolean>true</Boolean> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="38"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>AutoScaleDimensions</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.SizeF</Type> <Argument> <Expression> <Literal> <Number type="System.Single">6</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Single">13</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="39"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>AutoScaleMode</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="field"> <Expression> <Literal> <Type>System.Windows.Forms.AutoScaleMode</Type> </Literal> </Expression> <Name>Font</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="40"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>ClientSize</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.Drawing.Size</Type> <Argument> <Expression> <Literal> <Number type="System.Int32">284</Number> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">262</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="41"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Controls</Name> </NameRef> </Expression> <Name>Add</Name> </NameRef> </Expression> <Argument> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Button1</Name> </NameRef> </Expression> </Argument> </MethodCall> </Expression> </ExpressionStatement> <ExpressionStatement line="42"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Name</Name> </NameRef> </Expression> <Expression> <Literal> <String>Form1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="43"> <Expression> <Assignment> <Expression> <NameRef variablekind="property"> <Expression> <ThisReference/> </Expression> <Name>Text</Name> </NameRef> </Expression> <Expression> <Literal> <String>Form1</String> </Literal> </Expression> </Assignment> </Expression> </ExpressionStatement> <ExpressionStatement line="44"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>ResumeLayout</Name> </NameRef> </Expression> <Argument> <Expression> <Literal> <Boolean>false</Boolean> </Literal> </Expression> </Argument> </MethodCall> </Expression> </ExpressionStatement> </Block> End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourcePropertySymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourcePropertySymbol Inherits PropertySymbol Implements IAttributeTargetSymbol Private ReadOnly _containingType As SourceMemberContainerTypeSymbol Private ReadOnly _name As String Private _lazyMetadataName As String Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _blockRef As SyntaxReference Private ReadOnly _location As Location Private ReadOnly _flags As SourceMemberFlags Private _lazyType As TypeSymbol Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Private _getMethod As MethodSymbol Private _setMethod As MethodSymbol Private _backingField As FieldSymbol Private _lazyDocComment As String Private _lazyExpandedDocComment As String Private _lazyMeParameter As ParameterSymbol ' Attributes on property. Set once after construction. IsNull means not set. Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' Attributes on return type of the property. Set once after construction. IsNull means not set. Private _lazyReturnTypeCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' The explicitly implemented interface properties, or Empty if none. Private _lazyImplementedProperties As ImmutableArray(Of PropertySymbol) ' The overridden or hidden property. Private _lazyOverriddenProperties As OverriddenMembersResult(Of PropertySymbol) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer SymbolDeclaredEvent = &H1 ' Bit value for generating SymbolDeclaredEvent End Enum Private Sub New(container As SourceMemberContainerTypeSymbol, name As String, flags As SourceMemberFlags, syntaxRef As SyntaxReference, blockRef As SyntaxReference, location As Location) Debug.Assert(container IsNot Nothing) Debug.Assert(syntaxRef IsNot Nothing) Debug.Assert(location IsNot Nothing) _containingType = container _name = name _syntaxRef = syntaxRef _blockRef = blockRef _location = location _flags = flags _lazyState = 0 End Sub Friend Shared Function Create(containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, syntax As PropertyStatementSyntax, blockSyntaxOpt As PropertyBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertySymbol ' Decode the flags. Dim modifiers = DecodeModifiers(syntax.Modifiers, containingType, bodyBinder, diagnostics) Dim identifier = syntax.Identifier Dim name = identifier.ValueText Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(name) Dim location = identifier.GetLocation() Dim syntaxRef = bodyBinder.GetSyntaxReference(syntax) Dim blockRef = If(blockSyntaxOpt Is Nothing, Nothing, bodyBinder.GetSyntaxReference(blockSyntaxOpt)) Dim prop = New SourcePropertySymbol(containingType, name, modifiers.AllFlags, syntaxRef, blockRef, location) bodyBinder = New LocationSpecificBinder(BindingLocation.PropertySignature, prop, bodyBinder) If syntax.AttributeLists.Count = 0 Then prop.SetCustomAttributeData(CustomAttributesBag(Of VisualBasicAttributeData).Empty) End If Dim accessorFlags = modifiers.AllFlags And (Not SourceMemberFlags.AccessibilityMask) Dim getMethod As SourcePropertyAccessorSymbol = Nothing Dim setMethod As SourcePropertyAccessorSymbol = Nothing If blockSyntaxOpt IsNot Nothing Then For Each accessor In blockSyntaxOpt.Accessors Dim accessorKind = accessor.BlockStatement.Kind If accessorKind = SyntaxKind.GetAccessorStatement Then Dim accessorMethod = CreateAccessor(prop, SourceMemberFlags.MethodKindPropertyGet, accessorFlags, bodyBinder, accessor, diagnostics) If getMethod Is Nothing Then getMethod = accessorMethod Else diagnostics.Add(ERRID.ERR_DuplicatePropertyGet, accessorMethod.Locations(0)) End If ElseIf accessorKind = SyntaxKind.SetAccessorStatement Then Dim accessorMethod = CreateAccessor(prop, SourceMemberFlags.MethodKindPropertySet, accessorFlags, bodyBinder, accessor, diagnostics) If setMethod Is Nothing Then setMethod = accessorMethod Else diagnostics.Add(ERRID.ERR_DuplicatePropertySet, accessorMethod.Locations(0)) End If End If Next End If Dim isReadOnly = (modifiers.FoundFlags And SourceMemberFlags.ReadOnly) <> 0 Dim isWriteOnly = (modifiers.FoundFlags And SourceMemberFlags.WriteOnly) <> 0 If Not prop.IsMustOverride Then If isReadOnly Then If getMethod IsNot Nothing Then If getMethod.LocalAccessibility <> Accessibility.NotApplicable Then diagnostics.Add(ERRID.ERR_ReadOnlyNoAccessorFlag, GetAccessorBlockBeginLocation(getMethod)) End If ElseIf blockSyntaxOpt IsNot Nothing Then diagnostics.Add(ERRID.ERR_ReadOnlyHasNoGet, location) End If If setMethod IsNot Nothing Then diagnostics.Add(ERRID.ERR_ReadOnlyHasSet, setMethod.Locations(0)) End If End If If isWriteOnly Then If setMethod IsNot Nothing Then If setMethod.LocalAccessibility <> Accessibility.NotApplicable Then diagnostics.Add(ERRID.ERR_WriteOnlyNoAccessorFlag, GetAccessorBlockBeginLocation(setMethod)) End If ElseIf blockSyntaxOpt IsNot Nothing Then diagnostics.Add(ERRID.ERR_WriteOnlyHasNoWrite, location) End If If getMethod IsNot Nothing Then diagnostics.Add(ERRID.ERR_WriteOnlyHasGet, getMethod.Locations(0)) End If End If If (getMethod IsNot Nothing) AndAlso (setMethod IsNot Nothing) Then If (getMethod.LocalAccessibility <> Accessibility.NotApplicable) AndAlso (setMethod.LocalAccessibility <> Accessibility.NotApplicable) Then ' Both accessors have explicit accessibility. Report an error on the second. Dim accessor = If(getMethod.Locations(0).SourceSpan.Start < setMethod.Locations(0).SourceSpan.Start, setMethod, getMethod) diagnostics.Add(ERRID.ERR_OnlyOneAccessorForGetSet, GetAccessorBlockBeginLocation(accessor)) ElseIf prop.IsOverridable AndAlso ((getMethod.LocalAccessibility = Accessibility.Private) OrElse (setMethod.LocalAccessibility = Accessibility.Private)) Then ' If either accessor is Private, property cannot be Overridable. bodyBinder.ReportModifierError(syntax.Modifiers, ERRID.ERR_BadPropertyAccessorFlags3, diagnostics, s_overridableModifierKinds) End If End If If (Not isReadOnly) AndAlso (Not isWriteOnly) AndAlso ((getMethod Is Nothing) OrElse (setMethod Is Nothing)) AndAlso (blockSyntaxOpt IsNot Nothing) AndAlso (Not prop.IsMustOverride) Then diagnostics.Add(ERRID.ERR_PropMustHaveGetSet, location) End If End If If blockSyntaxOpt Is Nothing Then ' Generate backing field for auto property. If Not prop.IsMustOverride Then If isWriteOnly Then diagnostics.Add(ERRID.ERR_AutoPropertyCantBeWriteOnly, location) End If Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) Dim fieldName = "_" + prop._name prop._backingField = New SynthesizedPropertyBackingFieldSymbol(prop, fieldName, isShared:=prop.IsShared) End If Dim flags = prop._flags And Not SourceMemberFlags.MethodKindMask ' Generate accessors for auto property or abstract property. If Not isWriteOnly Then prop._getMethod = New SourcePropertyAccessorSymbol( prop, Binder.GetAccessorName(prop.Name, MethodKind.PropertyGet, isWinMd:=False), flags Or SourceMemberFlags.MethodKindPropertyGet, prop._syntaxRef, prop.Locations) End If If Not isReadOnly Then prop._setMethod = New SourcePropertyAccessorSymbol( prop, Binder.GetAccessorName(prop.Name, MethodKind.PropertySet, isWinMd:=prop.IsCompilationOutputWinMdObj()), flags Or SourceMemberFlags.MethodKindPropertySet Or SourceMemberFlags.MethodIsSub, prop._syntaxRef, prop.Locations) End If Else prop._getMethod = getMethod prop._setMethod = setMethod End If Debug.Assert((prop._getMethod Is Nothing) OrElse prop._getMethod.ImplicitlyDefinedBy Is prop) Debug.Assert((prop._setMethod Is Nothing) OrElse prop._setMethod.ImplicitlyDefinedBy Is prop) Return prop End Function Friend Shared Function CreateWithEvents( containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, identifier As SyntaxToken, syntaxRef As SyntaxReference, modifiers As MemberModifiers, firstFieldDeclarationOfType As Boolean, diagnostics As BindingDiagnosticBag) As SourcePropertySymbol Dim name = identifier.ValueText ' we will require AccessedThroughPropertyAttribute bodyBinder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor, DirectCast(identifier.Parent, VisualBasicSyntaxNode), diagnostics) Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(name) Dim location = identifier.GetLocation() ' WithEvents instance property is always overridable Dim memberFlags = modifiers.AllFlags If (memberFlags And SourceMemberFlags.Shared) = 0 Then memberFlags = modifiers.AllFlags Or SourceMemberFlags.Overridable End If If firstFieldDeclarationOfType Then memberFlags = memberFlags Or SourceMemberFlags.FirstFieldDeclarationOfType End If Dim prop = New SourcePropertySymbol(containingType, name, memberFlags, syntaxRef, Nothing, location) ' no implements. prop._lazyImplementedProperties = ImmutableArray(Of PropertySymbol).Empty prop.SetCustomAttributeData(CustomAttributesBag(Of VisualBasicAttributeData).Empty) Dim fieldName = "_" + prop._name prop._backingField = New SourceWithEventsBackingFieldSymbol(prop, syntaxRef, fieldName) ' Generate synthesized accessors for auto property or abstract property. prop._getMethod = New SynthesizedWithEventsGetAccessorSymbol( containingType, prop) prop._setMethod = New SynthesizedWithEventsSetAccessorSymbol( containingType, prop, bodyBinder.GetSpecialType(SpecialType.System_Void, identifier, diagnostics), valueParameterName:=StringConstants.WithEventsValueParameterName) Debug.Assert((prop._getMethod Is Nothing) OrElse prop._getMethod.ImplicitlyDefinedBy Is prop) Debug.Assert((prop._setMethod Is Nothing) OrElse prop._setMethod.ImplicitlyDefinedBy Is prop) Return prop End Function Friend Sub CloneParametersForAccessor(method As MethodSymbol, parameterBuilder As ArrayBuilder(Of ParameterSymbol)) Dim overriddenMethod As MethodSymbol = method.OverriddenMethod For Each parameter In Me.Parameters Dim clone As ParameterSymbol = New SourcePropertyClonedParameterSymbolForAccessors(DirectCast(parameter, SourceParameterSymbol), method) If overriddenMethod IsNot Nothing Then CustomModifierUtils.CopyParameterCustomModifiers(overriddenMethod.Parameters(parameter.Ordinal), clone) End If parameterBuilder.Add(clone) Next End Sub ''' <summary> ''' Property declaration syntax node. ''' It is either PropertyStatement for normal properties or FieldDeclarationSyntax for WithEvents ones. ''' </summary> Friend ReadOnly Property DeclarationSyntax As DeclarationStatementSyntax Get Dim syntax = _syntaxRef.GetVisualBasicSyntax() If syntax.Kind = SyntaxKind.PropertyStatement Then Return DirectCast(syntax, PropertyStatementSyntax) Else Debug.Assert(syntax.Kind = SyntaxKind.ModifiedIdentifier) Return DirectCast(syntax.Parent.Parent, FieldDeclarationSyntax) End If End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get EnsureSignature() Return _lazyType End Get End Property Private Function ComputeType(diagnostics As BindingDiagnosticBag) As TypeSymbol Dim binder = CreateBinderForTypeDeclaration() If IsWithEvents Then Dim syntax = DirectCast(_syntaxRef.GetSyntax(), ModifiedIdentifierSyntax) Return SourceMemberFieldSymbol.ComputeWithEventsFieldType( Me, syntax, binder, ignoreTypeSyntaxDiagnostics:=(_flags And SourceMemberFlags.FirstFieldDeclarationOfType) = 0, diagnostics:=diagnostics) Else Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Dim asClause = syntax.AsClause If asClause IsNot Nothing AndAlso asClause.Kind = SyntaxKind.AsNewClause AndAlso (DirectCast(asClause, AsNewClauseSyntax).NewExpression.Kind = SyntaxKind.AnonymousObjectCreationExpression) Then Return ErrorTypeSymbol.UnknownResultType Else Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(_name) If Not omitFurtherDiagnostics Then If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedProperty1_WRN_MissingAsClauseinProperty End If End If Dim identifier = syntax.Identifier Dim type = binder.DecodeIdentifierType(identifier, asClause, getErrorInfo, diagnostics) Debug.Assert(type IsNot Nothing) If Not type.IsErrorType() Then Dim errorLocation = SourceSymbolHelpers.GetAsClauseLocation(identifier, asClause) AccessCheck.VerifyAccessExposureForMemberType(Me, errorLocation, type, diagnostics) Dim restrictedType As TypeSymbol = Nothing If type.IsRestrictedTypeOrArrayType(restrictedType) Then Binder.ReportDiagnostic(diagnostics, errorLocation, ERRID.ERR_RestrictedType1, restrictedType) End If Dim getMethod = Me.GetMethod If getMethod IsNot Nothing AndAlso getMethod.IsIterator Then Dim originalRetTypeDef = type.OriginalDefinition If originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerable_T AndAlso originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerator_T AndAlso type.SpecialType <> SpecialType.System_Collections_IEnumerable AndAlso type.SpecialType <> SpecialType.System_Collections_IEnumerator Then Binder.ReportDiagnostic(diagnostics, errorLocation, ERRID.ERR_BadIteratorReturn) End If End If End If Return type End If End If End Function Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get If _lazyMetadataName Is Nothing Then OverloadingHelper.SetMetadataNameForAllOverloads(_name, SymbolKind.Property, _containingType) Debug.Assert(_lazyMetadataName IsNot Nothing) End If Return _lazyMetadataName End Get End Property Friend Overrides Sub SetMetadataName(metadataName As String) Dim old = Interlocked.CompareExchange(_lazyMetadataName, metadataName, Nothing) Debug.Assert(old Is Nothing OrElse old = metadataName) End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public ReadOnly Property ContainingSourceType As SourceMemberContainerTypeSymbol Get Return _containingType End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return New LexicalSortKey(_location, Me.DeclaringCompilation) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_location) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) End Get End Property Friend Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Dim propertyStatementSyntax = Me.Syntax Return propertyStatementSyntax IsNot Nothing AndAlso IsDefinedInSourceTree(propertyStatementSyntax.Parent, tree, definedWithinSpan, cancellationToken) End Function Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Property End Get End Property Private Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.IsWithEvents Then Return Nothing End If Return OneOrMany.Create(DirectCast(_syntaxRef.GetSyntax, PropertyStatementSyntax).AttributeLists) End Function Private Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.IsWithEvents Then Return Nothing End If Dim asClauseOpt = DirectCast(Me.Syntax, PropertyStatementSyntax).AsClause If asClauseOpt Is Nothing Then Return Nothing End If Return OneOrMany.Create(asClauseOpt.Attributes) End Function Friend Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(Me.GetAttributeDeclarations(), _lazyCustomAttributesBag) End If Return _lazyCustomAttributesBag End Function Friend Function GetReturnTypeAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyReturnTypeCustomAttributesBag Is Nothing OrElse Not _lazyReturnTypeCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(GetReturnTypeAttributeDeclarations(), _lazyReturnTypeCustomAttributesBag, symbolPart:=AttributeLocation.Return) End If Return _lazyReturnTypeCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> ''' <remarks> ''' NOTE: This method should always be kept as a NotOverridable method. ''' If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. ''' </remarks> Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetDecodedWellKnownAttributeData() As CommonPropertyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonPropertyWellKnownAttributeData) End Function Private Function GetDecodedReturnTypeWellKnownAttributeData() As CommonReturnTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyReturnTypeCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetReturnTypeAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonReturnTypeWellKnownAttributeData) End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of CommonPropertyEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then diagnostics.Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If arguments.SymbolPart = AttributeLocation.Return Then Dim isMarshalAs = attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) ' write-only property doesn't accept any return type attributes other than MarshalAs ' MarshalAs is applied on the "Value" parameter of the setter if the property has no parameters and the containing type is an interface . If _getMethod Is Nothing AndAlso _setMethod IsNot Nothing AndAlso (Not isMarshalAs OrElse Not SynthesizedParameterSymbol.IsMarshalAsAttributeApplicable(_setMethod)) Then diagnostics.Add(ERRID.WRN_ReturnTypeAttributeOnWriteOnlyProperty, arguments.AttributeSyntaxOpt.GetLocation()) Return End If If isMarshalAs Then MarshalAsAttributeDecoder(Of CommonReturnTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation). Decode(arguments, AttributeTargets.Field, MessageProvider.Instance) Return End If Else If attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of CommonPropertyWellKnownAttributeData).HasSpecialNameAttribute = True Return ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of CommonPropertyWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute = True Return ElseIf Not IsWithEvents AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.DebuggerHiddenAttribute) Then ' if neither getter or setter is marked by DebuggerHidden Dev11 reports a warning If Not (_getMethod IsNot Nothing AndAlso DirectCast(_getMethod, SourcePropertyAccessorSymbol).HasDebuggerHiddenAttribute OrElse _setMethod IsNot Nothing AndAlso DirectCast(_setMethod, SourcePropertyAccessorSymbol).HasDebuggerHiddenAttribute) Then diagnostics.Add(ERRID.WRN_DebuggerHiddenIgnoredOnProperties, arguments.AttributeSyntaxOpt.GetLocation()) End If Return End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Friend ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Dim data = GetDecodedReturnTypeWellKnownAttributeData() Return If(data IsNot Nothing, data.MarshallingInformation, Nothing) End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return (_flags And SourceMemberFlags.MustOverride) <> 0 End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return (_flags And SourceMemberFlags.NotOverridable) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return (_flags And SourceMemberFlags.Overridable) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return (_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return (_flags And SourceMemberFlags.Shared) <> 0 End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return (_flags And SourceMemberFlags.Default) <> 0 End Get End Property Public Overrides ReadOnly Property IsWriteOnly As Boolean Get Return (_flags And SourceMemberFlags.WriteOnly) <> 0 End Get End Property Public Overrides ReadOnly Property IsReadOnly As Boolean Get Return (_flags And SourceMemberFlags.ReadOnly) <> 0 End Get End Property Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return _getMethod End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return _setMethod End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get If (_flags And SourceMemberFlags.Shadows) <> 0 Then Return False ElseIf (_flags And SourceMemberFlags.Overloads) <> 0 Then Return True Else Return (_flags And SourceMemberFlags.Overrides) <> 0 End If End Get End Property Public Overrides ReadOnly Property IsWithEvents As Boolean Get Return (_flags And SourceMemberFlags.WithEvents) <> 0 End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Shadows) <> 0 End Get End Property ''' <summary> True if 'Overloads' is explicitly specified in method's declaration </summary> Friend ReadOnly Property OverloadsExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Overloads) <> 0 End Get End Property ''' <summary> True if 'Overrides' is explicitly specified in method's declaration </summary> Friend ReadOnly Property OverridesExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return (If(IsShared, Microsoft.Cci.CallingConvention.Default, Microsoft.Cci.CallingConvention.HasThis)) End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get EnsureSignature() Return _lazyParameters End Get End Property Private Sub EnsureSignature() If _lazyParameters.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim sourceModule = DirectCast(ContainingModule, SourceModuleSymbol) Dim params As ImmutableArray(Of ParameterSymbol) = ComputeParameters(diagnostics) Dim retType As TypeSymbol = ComputeType(diagnostics) ' For an overriding property, we need to copy custom modifiers from the property we override. Dim overriddenMembers As OverriddenMembersResult(Of PropertySymbol) If Not Me.IsOverrides OrElse Not OverrideHidingHelper.CanOverrideOrHide(Me) Then overriddenMembers = OverriddenMembersResult(Of PropertySymbol).Empty Else ' Since we cannot expose parameters and return type to the outside world yet, ' let's create a fake symbol to use for overriding resolution Dim fakeParamsBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(params.Length) For Each param As ParameterSymbol In params fakeParamsBuilder.Add(New SignatureOnlyParameterSymbol( param.Type, ImmutableArray(Of CustomModifier).Empty, ImmutableArray(Of CustomModifier).Empty, defaultConstantValue:=Nothing, isParamArray:=False, isByRef:=param.IsByRef, isOut:=False, isOptional:=param.IsOptional)) Next overriddenMembers = OverrideHidingHelper(Of PropertySymbol). MakeOverriddenMembers(New SignatureOnlyPropertySymbol(Me.Name, _containingType, Me.IsReadOnly, Me.IsWriteOnly, fakeParamsBuilder.ToImmutableAndFree(), returnsByRef:=False, [type]:=retType, typeCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, refCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, isOverrides:=True, isWithEvents:=Me.IsWithEvents)) End If Debug.Assert(IsDefinition) Dim overridden = overriddenMembers.OverriddenMember If overridden IsNot Nothing Then ' Copy custom modifiers Dim returnTypeWithCustomModifiers As TypeSymbol = overridden.Type ' We do an extra check before copying the return type to handle the case where the overriding ' property (incorrectly) has a different return type than the overridden property. In such cases, ' we want to retain the original (incorrect) return type to avoid hiding the return type ' given in source. If retType.IsSameType(returnTypeWithCustomModifiers, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) Then retType = CustomModifierUtils.CopyTypeCustomModifiers(returnTypeWithCustomModifiers, retType) End If params = CustomModifierUtils.CopyParameterCustomModifiers(overridden.Parameters, params) End If ' Unlike PropertySymbol, in SourcePropertySymbol we cache the result of MakeOverriddenOfHiddenMembers, because we use ' it heavily while validating methods and emitting. Interlocked.CompareExchange(_lazyOverriddenProperties, overriddenMembers, Nothing) Interlocked.CompareExchange(_lazyType, retType, Nothing) sourceModule.AtomicStoreArrayAndDiagnostics( _lazyParameters, params, diagnostics) diagnostics.Free() End If End Sub Public Overrides ReadOnly Property ParameterCount As Integer Get If Not Me._lazyParameters.IsDefault Then Return Me._lazyParameters.Length End If Dim decl = Me.DeclarationSyntax If decl.Kind = SyntaxKind.PropertyStatement Then Dim paramList As ParameterListSyntax = DirectCast(decl, PropertyStatementSyntax).ParameterList Return If(paramList Is Nothing, 0, paramList.Parameters.Count) End If Return MyBase.ParameterCount End Get End Property Private Function ComputeParameters(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) If Me.IsWithEvents Then ' no parameters Return ImmutableArray(Of ParameterSymbol).Empty End If Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Dim parameters = binder.DecodePropertyParameterList(Me, syntax.ParameterList, diagnostics) If IsDefault Then ' Default properties must have required parameters. If Not HasRequiredParameters(parameters) Then diagnostics.Add(ERRID.ERR_DefaultPropertyWithNoParams, _location) End If ' 'touch' System_Reflection_DefaultMemberAttribute__ctor to make sure all diagnostics are reported binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, syntax, diagnostics) End If Return parameters End Function Friend Overrides ReadOnly Property MeParameter As ParameterSymbol Get If IsShared Then Return Nothing Else If _lazyMeParameter Is Nothing Then Interlocked.CompareExchange(Of ParameterSymbol)(_lazyMeParameter, New MeParameterSymbol(Me), Nothing) End If Return _lazyMeParameter End If End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get If _lazyImplementedProperties.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) sourceModule.AtomicStoreArrayAndDiagnostics(_lazyImplementedProperties, ComputeExplicitInterfaceImplementations(diagnostics), diagnostics) diagnostics.Free() End If Return _lazyImplementedProperties End Get End Property Private Function ComputeExplicitInterfaceImplementations(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of PropertySymbol) Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Return BindImplementsClause(_containingType, binder, Me, syntax, diagnostics) End Function ''' <summary> ''' Helper method for accessors to get the overridden accessor methods. Should only be called by the ''' accessor method symbols. ''' </summary> ''' <param name="getter">True to get implemented getters, False to get implemented setters</param> ''' <returns>All the accessors of the given kind implemented by this property.</returns> Friend Function GetAccessorImplementations(getter As Boolean) As ImmutableArray(Of MethodSymbol) Dim implementedProperties = ExplicitInterfaceImplementations Debug.Assert(Not implementedProperties.IsDefault) If implementedProperties.IsEmpty Then Return ImmutableArray(Of MethodSymbol).Empty Else Dim builder As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() For Each implementedProp In implementedProperties Dim accessor = If(getter, implementedProp.GetMethod, implementedProp.SetMethod) If accessor IsNot Nothing AndAlso accessor.RequiresImplementation() Then builder.Add(accessor) End If Next Return builder.ToImmutableAndFree() End If End Function Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of PropertySymbol) Get EnsureSignature() Return Me._lazyOverriddenProperties End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Dim overridden = Me.OverriddenProperty If overridden Is Nothing Then Return ImmutableArray(Of CustomModifier).Empty Else Return overridden.TypeCustomModifiers End If End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return CType((_flags And SourceMemberFlags.AccessibilityMask), Accessibility) End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _containingType.AreMembersImplicitlyDeclared End Get End Property Friend ReadOnly Property IsCustomProperty As Boolean Get ' Auto and WithEvents properties have backing fields Return _backingField Is Nothing AndAlso Not IsMustOverride End Get End Property Friend ReadOnly Property IsAutoProperty As Boolean Get Return Not IsWithEvents AndAlso _backingField IsNot Nothing End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return _backingField End Get End Property ''' <summary> ''' Property declaration syntax node. ''' It is either PropertyStatement for normal properties or ModifiedIdentifier for WithEvents ones. ''' </summary> Friend ReadOnly Property Syntax As VisualBasicSyntaxNode Get Return If(_syntaxRef IsNot Nothing, _syntaxRef.GetVisualBasicSyntax(), Nothing) End Get End Property Friend ReadOnly Property SyntaxReference As SyntaxReference Get Return Me._syntaxRef End Get End Property Friend ReadOnly Property BlockSyntaxReference As SyntaxReference Get Return Me._blockRef End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ' If there are no attributes then this symbol is not Obsolete. If (Not Me._containingType.AnyMemberHasAttributes) Then Return Nothing End If Dim lazyCustomAttributesBag = Me._lazyCustomAttributesBag If (lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) Then Dim data = DirectCast(_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonPropertyEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If Return ObsoleteAttributeData.Uninitialized End Get End Property ' Get the location of the implements name for an explicit implemented property, for later error reporting. Friend Function GetImplementingLocation(implementedProperty As PropertySymbol) As Location Debug.Assert(ExplicitInterfaceImplementations.Contains(implementedProperty)) Dim propertySyntax = TryCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) If propertySyntax IsNot Nothing AndAlso propertySyntax.ImplementsClause IsNot Nothing Then Dim binder = CreateBinderForTypeDeclaration() Dim implementingSyntax = FindImplementingSyntax(Of PropertySymbol)(propertySyntax.ImplementsClause, Me, implementedProperty, _containingType, binder) Return implementingSyntax.GetLocation() End If Return If(Locations.FirstOrDefault(), NoLocation.Singleton) End Function Private Function CreateBinderForTypeDeclaration() As Binder Dim binder = BinderBuilder.CreateBinderForType(DirectCast(ContainingModule, SourceModuleSymbol), _syntaxRef.SyntaxTree, _containingType) Return New LocationSpecificBinder(BindingLocation.PropertySignature, Me, binder) End Function Private Shared Function CreateAccessor([property] As SourcePropertySymbol, kindFlags As SourceMemberFlags, propertyFlags As SourceMemberFlags, bodyBinder As Binder, syntax As AccessorBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertyAccessorSymbol Dim accessor = SourcePropertyAccessorSymbol.CreatePropertyAccessor([property], kindFlags, propertyFlags, bodyBinder, syntax, diagnostics) Debug.Assert(accessor IsNot Nothing) Dim localAccessibility = accessor.LocalAccessibility If Not IsAccessibilityMoreRestrictive([property].DeclaredAccessibility, localAccessibility) Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlagsRestrict, diagnostics) ElseIf [property].IsNotOverridable AndAlso localAccessibility = Accessibility.Private Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlags1, diagnostics) ElseIf [property].IsDefault AndAlso localAccessibility = Accessibility.Private Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlags2, diagnostics) End If Return accessor End Function ''' <summary> ''' Return true if the accessor accessibility is more restrictive ''' than the property accessibility, otherwise false. ''' </summary> Private Shared Function IsAccessibilityMoreRestrictive([property] As Accessibility, accessor As Accessibility) As Boolean If accessor = Accessibility.NotApplicable Then Return True End If Return (accessor < [property]) AndAlso ((accessor <> Accessibility.Protected) OrElse ([property] <> Accessibility.Friend)) End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function Private Shared Function DecodeModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim propertyModifiers = binder.DecodeModifiers(modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Default Or SourceMemberFlags.Overloads Or SourceMemberFlags.Shadows Or SourceMemberFlags.Shared Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Overrides Or SourceMemberFlags.MustOverride Or SourceMemberFlags.ReadOnly Or SourceMemberFlags.Iterator Or SourceMemberFlags.WriteOnly, ERRID.ERR_BadPropertyFlags1, Accessibility.Public, diagBag) ' Diagnose Shared with an overriding modifier. Dim flags = propertyModifiers.FoundFlags If (flags And SourceMemberFlags.Default) <> 0 AndAlso (flags And SourceMemberFlags.InvalidIfDefault) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadFlagsWithDefault1, diagBag, InvalidModifiersIfDefault) flags = flags And Not SourceMemberFlags.InvalidIfDefault propertyModifiers = New MemberModifiers(flags, propertyModifiers.ComputedFlags) End If propertyModifiers = binder.ValidateSharedPropertyAndMethodModifiers(modifiers, propertyModifiers, True, container, diagBag) Return propertyModifiers End Function Private Shared Function BindImplementsClause(containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, prop As SourcePropertySymbol, syntax As PropertyStatementSyntax, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of PropertySymbol) If syntax.ImplementsClause IsNot Nothing Then If prop.IsShared And Not containingType.IsModuleType Then ' Implementing with shared methods is illegal. ' Module case is caught inside ProcessImplementsClause and has different message. Binder.ReportDiagnostic(diagnostics, syntax.Modifiers.First(SyntaxKind.SharedKeyword), ERRID.ERR_SharedOnProcThatImpl, syntax.Identifier.ToString()) Else Return ProcessImplementsClause(Of PropertySymbol)(syntax.ImplementsClause, prop, containingType, bodyBinder, diagnostics) End If End If Return ImmutableArray(Of PropertySymbol).Empty End Function ''' <summary> ''' Returns the location (span) of the accessor begin block. ''' (Used for consistency with the native compiler that ''' highlights the entire begin block for certain diagnostics.) ''' </summary> Private Shared Function GetAccessorBlockBeginLocation(accessor As SourcePropertyAccessorSymbol) As Location Dim syntaxTree = accessor.SyntaxTree Dim block = DirectCast(accessor.BlockSyntax, AccessorBlockSyntax) Debug.Assert(syntaxTree IsNot Nothing) Debug.Assert(block IsNot Nothing) Debug.Assert(block.BlockStatement IsNot Nothing) Return syntaxTree.GetLocation(block.BlockStatement.Span) End Function Private Shared ReadOnly s_overridableModifierKinds() As SyntaxKind = { SyntaxKind.OverridableKeyword } Private Shared ReadOnly s_accessibilityModifierKinds() As SyntaxKind = { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword, SyntaxKind.PublicKeyword } ''' <summary> ''' Report an error associated with the accessor accessibility modifier. ''' </summary> Private Shared Sub ReportAccessorAccessibilityError(binder As Binder, syntax As AccessorBlockSyntax, errorId As ERRID, diagnostics As DiagnosticBag) binder.ReportModifierError(syntax.BlockStatement.Modifiers, errorId, diagnostics, s_accessibilityModifierKinds) End Sub Private Shared Function HasRequiredParameters(parameters As ImmutableArray(Of ParameterSymbol)) As Boolean For Each parameter In parameters If Not parameter.IsOptional AndAlso Not parameter.IsParamArray Then Return True End If Next Return False End Function ''' <summary> ''' Gets the syntax tree. ''' </summary> Friend ReadOnly Property SyntaxTree As SyntaxTree Get Return _syntaxRef.SyntaxTree End Get End Property ' This should be called at most once after the attributes are bound. Attributes must be bound after the class ' and members are fully declared to avoid infinite recursion. Private Sub SetCustomAttributeData(attributeData As CustomAttributesBag(Of VisualBasicAttributeData)) Debug.Assert(attributeData IsNot Nothing) Debug.Assert(_lazyCustomAttributesBag Is Nothing) _lazyCustomAttributesBag = attributeData End Sub Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) ' Ensure return type attributes are bound Dim unusedType = Me.Type Dim unusedParameters = Me.Parameters Me.GetReturnTypeAttributesBag() Dim unusedImplementations = Me.ExplicitInterfaceImplementations If DeclaringCompilation.EventQueue IsNot Nothing Then DirectCast(Me.ContainingModule, SourceModuleSymbol).AtomicSetFlagAndRaiseSymbolDeclaredEvent(_lazyState, StateFlags.SymbolDeclaredEvent, 0, Me) End If End Sub Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Return False End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If Me.Type.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class SourcePropertySymbol Inherits PropertySymbol Implements IAttributeTargetSymbol Private ReadOnly _containingType As SourceMemberContainerTypeSymbol Private ReadOnly _name As String Private _lazyMetadataName As String Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _blockRef As SyntaxReference Private ReadOnly _location As Location Private ReadOnly _flags As SourceMemberFlags Private _lazyType As TypeSymbol Private _lazyParameters As ImmutableArray(Of ParameterSymbol) Private _getMethod As MethodSymbol Private _setMethod As MethodSymbol Private _backingField As FieldSymbol Private _lazyDocComment As String Private _lazyExpandedDocComment As String Private _lazyMeParameter As ParameterSymbol ' Attributes on property. Set once after construction. IsNull means not set. Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' Attributes on return type of the property. Set once after construction. IsNull means not set. Private _lazyReturnTypeCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) ' The explicitly implemented interface properties, or Empty if none. Private _lazyImplementedProperties As ImmutableArray(Of PropertySymbol) ' The overridden or hidden property. Private _lazyOverriddenProperties As OverriddenMembersResult(Of PropertySymbol) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer SymbolDeclaredEvent = &H1 ' Bit value for generating SymbolDeclaredEvent End Enum Private Sub New(container As SourceMemberContainerTypeSymbol, name As String, flags As SourceMemberFlags, syntaxRef As SyntaxReference, blockRef As SyntaxReference, location As Location) Debug.Assert(container IsNot Nothing) Debug.Assert(syntaxRef IsNot Nothing) Debug.Assert(location IsNot Nothing) _containingType = container _name = name _syntaxRef = syntaxRef _blockRef = blockRef _location = location _flags = flags _lazyState = 0 End Sub Friend Shared Function Create(containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, syntax As PropertyStatementSyntax, blockSyntaxOpt As PropertyBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertySymbol ' Decode the flags. Dim modifiers = DecodeModifiers(syntax.Modifiers, containingType, bodyBinder, diagnostics) Dim identifier = syntax.Identifier Dim name = identifier.ValueText Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(name) Dim location = identifier.GetLocation() Dim syntaxRef = bodyBinder.GetSyntaxReference(syntax) Dim blockRef = If(blockSyntaxOpt Is Nothing, Nothing, bodyBinder.GetSyntaxReference(blockSyntaxOpt)) Dim prop = New SourcePropertySymbol(containingType, name, modifiers.AllFlags, syntaxRef, blockRef, location) bodyBinder = New LocationSpecificBinder(BindingLocation.PropertySignature, prop, bodyBinder) If syntax.AttributeLists.Count = 0 Then prop.SetCustomAttributeData(CustomAttributesBag(Of VisualBasicAttributeData).Empty) End If Dim accessorFlags = modifiers.AllFlags And (Not SourceMemberFlags.AccessibilityMask) Dim getMethod As SourcePropertyAccessorSymbol = Nothing Dim setMethod As SourcePropertyAccessorSymbol = Nothing If blockSyntaxOpt IsNot Nothing Then For Each accessor In blockSyntaxOpt.Accessors Dim accessorKind = accessor.BlockStatement.Kind If accessorKind = SyntaxKind.GetAccessorStatement Then Dim accessorMethod = CreateAccessor(prop, SourceMemberFlags.MethodKindPropertyGet, accessorFlags, bodyBinder, accessor, diagnostics) If getMethod Is Nothing Then getMethod = accessorMethod Else diagnostics.Add(ERRID.ERR_DuplicatePropertyGet, accessorMethod.Locations(0)) End If ElseIf accessorKind = SyntaxKind.SetAccessorStatement Then Dim accessorMethod = CreateAccessor(prop, SourceMemberFlags.MethodKindPropertySet, accessorFlags, bodyBinder, accessor, diagnostics) If setMethod Is Nothing Then setMethod = accessorMethod Else diagnostics.Add(ERRID.ERR_DuplicatePropertySet, accessorMethod.Locations(0)) End If End If Next End If Dim isReadOnly = (modifiers.FoundFlags And SourceMemberFlags.ReadOnly) <> 0 Dim isWriteOnly = (modifiers.FoundFlags And SourceMemberFlags.WriteOnly) <> 0 If Not prop.IsMustOverride Then If isReadOnly Then If getMethod IsNot Nothing Then If getMethod.LocalAccessibility <> Accessibility.NotApplicable Then diagnostics.Add(ERRID.ERR_ReadOnlyNoAccessorFlag, GetAccessorBlockBeginLocation(getMethod)) End If ElseIf blockSyntaxOpt IsNot Nothing Then diagnostics.Add(ERRID.ERR_ReadOnlyHasNoGet, location) End If If setMethod IsNot Nothing Then diagnostics.Add(ERRID.ERR_ReadOnlyHasSet, setMethod.Locations(0)) End If End If If isWriteOnly Then If setMethod IsNot Nothing Then If setMethod.LocalAccessibility <> Accessibility.NotApplicable Then diagnostics.Add(ERRID.ERR_WriteOnlyNoAccessorFlag, GetAccessorBlockBeginLocation(setMethod)) End If ElseIf blockSyntaxOpt IsNot Nothing Then diagnostics.Add(ERRID.ERR_WriteOnlyHasNoWrite, location) End If If getMethod IsNot Nothing Then diagnostics.Add(ERRID.ERR_WriteOnlyHasGet, getMethod.Locations(0)) End If End If If (getMethod IsNot Nothing) AndAlso (setMethod IsNot Nothing) Then If (getMethod.LocalAccessibility <> Accessibility.NotApplicable) AndAlso (setMethod.LocalAccessibility <> Accessibility.NotApplicable) Then ' Both accessors have explicit accessibility. Report an error on the second. Dim accessor = If(getMethod.Locations(0).SourceSpan.Start < setMethod.Locations(0).SourceSpan.Start, setMethod, getMethod) diagnostics.Add(ERRID.ERR_OnlyOneAccessorForGetSet, GetAccessorBlockBeginLocation(accessor)) ElseIf prop.IsOverridable AndAlso ((getMethod.LocalAccessibility = Accessibility.Private) OrElse (setMethod.LocalAccessibility = Accessibility.Private)) Then ' If either accessor is Private, property cannot be Overridable. bodyBinder.ReportModifierError(syntax.Modifiers, ERRID.ERR_BadPropertyAccessorFlags3, diagnostics, s_overridableModifierKinds) End If End If If (Not isReadOnly) AndAlso (Not isWriteOnly) AndAlso ((getMethod Is Nothing) OrElse (setMethod Is Nothing)) AndAlso (blockSyntaxOpt IsNot Nothing) AndAlso (Not prop.IsMustOverride) Then diagnostics.Add(ERRID.ERR_PropMustHaveGetSet, location) End If End If If blockSyntaxOpt Is Nothing Then ' Generate backing field for auto property. If Not prop.IsMustOverride Then If isWriteOnly Then diagnostics.Add(ERRID.ERR_AutoPropertyCantBeWriteOnly, location) End If Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)) Dim fieldName = "_" + prop._name prop._backingField = New SynthesizedPropertyBackingFieldSymbol(prop, fieldName, isShared:=prop.IsShared) End If Dim flags = prop._flags And Not SourceMemberFlags.MethodKindMask ' Generate accessors for auto property or abstract property. If Not isWriteOnly Then prop._getMethod = New SourcePropertyAccessorSymbol( prop, Binder.GetAccessorName(prop.Name, MethodKind.PropertyGet, isWinMd:=False), flags Or SourceMemberFlags.MethodKindPropertyGet, prop._syntaxRef, prop.Locations) End If If Not isReadOnly Then prop._setMethod = New SourcePropertyAccessorSymbol( prop, Binder.GetAccessorName(prop.Name, MethodKind.PropertySet, isWinMd:=prop.IsCompilationOutputWinMdObj()), flags Or SourceMemberFlags.MethodKindPropertySet Or SourceMemberFlags.MethodIsSub, prop._syntaxRef, prop.Locations) End If Else prop._getMethod = getMethod prop._setMethod = setMethod End If Debug.Assert((prop._getMethod Is Nothing) OrElse prop._getMethod.ImplicitlyDefinedBy Is prop) Debug.Assert((prop._setMethod Is Nothing) OrElse prop._setMethod.ImplicitlyDefinedBy Is prop) Return prop End Function Friend Shared Function CreateWithEvents( containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, identifier As SyntaxToken, syntaxRef As SyntaxReference, modifiers As MemberModifiers, firstFieldDeclarationOfType As Boolean, diagnostics As BindingDiagnosticBag) As SourcePropertySymbol Dim name = identifier.ValueText ' we will require AccessedThroughPropertyAttribute bodyBinder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_AccessedThroughPropertyAttribute__ctor, DirectCast(identifier.Parent, VisualBasicSyntaxNode), diagnostics) Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(name) Dim location = identifier.GetLocation() ' WithEvents instance property is always overridable Dim memberFlags = modifiers.AllFlags If (memberFlags And SourceMemberFlags.Shared) = 0 Then memberFlags = modifiers.AllFlags Or SourceMemberFlags.Overridable End If If firstFieldDeclarationOfType Then memberFlags = memberFlags Or SourceMemberFlags.FirstFieldDeclarationOfType End If Dim prop = New SourcePropertySymbol(containingType, name, memberFlags, syntaxRef, Nothing, location) ' no implements. prop._lazyImplementedProperties = ImmutableArray(Of PropertySymbol).Empty prop.SetCustomAttributeData(CustomAttributesBag(Of VisualBasicAttributeData).Empty) Dim fieldName = "_" + prop._name prop._backingField = New SourceWithEventsBackingFieldSymbol(prop, syntaxRef, fieldName) ' Generate synthesized accessors for auto property or abstract property. prop._getMethod = New SynthesizedWithEventsGetAccessorSymbol( containingType, prop) prop._setMethod = New SynthesizedWithEventsSetAccessorSymbol( containingType, prop, bodyBinder.GetSpecialType(SpecialType.System_Void, identifier, diagnostics), valueParameterName:=StringConstants.WithEventsValueParameterName) Debug.Assert((prop._getMethod Is Nothing) OrElse prop._getMethod.ImplicitlyDefinedBy Is prop) Debug.Assert((prop._setMethod Is Nothing) OrElse prop._setMethod.ImplicitlyDefinedBy Is prop) Return prop End Function Friend Sub CloneParametersForAccessor(method As MethodSymbol, parameterBuilder As ArrayBuilder(Of ParameterSymbol)) Dim overriddenMethod As MethodSymbol = method.OverriddenMethod For Each parameter In Me.Parameters Dim clone As ParameterSymbol = New SourcePropertyClonedParameterSymbolForAccessors(DirectCast(parameter, SourceParameterSymbol), method) If overriddenMethod IsNot Nothing Then CustomModifierUtils.CopyParameterCustomModifiers(overriddenMethod.Parameters(parameter.Ordinal), clone) End If parameterBuilder.Add(clone) Next End Sub ''' <summary> ''' Property declaration syntax node. ''' It is either PropertyStatement for normal properties or FieldDeclarationSyntax for WithEvents ones. ''' </summary> Friend ReadOnly Property DeclarationSyntax As DeclarationStatementSyntax Get Dim syntax = _syntaxRef.GetVisualBasicSyntax() If syntax.Kind = SyntaxKind.PropertyStatement Then Return DirectCast(syntax, PropertyStatementSyntax) Else Debug.Assert(syntax.Kind = SyntaxKind.ModifiedIdentifier) Return DirectCast(syntax.Parent.Parent, FieldDeclarationSyntax) End If End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property Type As TypeSymbol Get EnsureSignature() Return _lazyType End Get End Property Private Function ComputeType(diagnostics As BindingDiagnosticBag) As TypeSymbol Dim binder = CreateBinderForTypeDeclaration() If IsWithEvents Then Dim syntax = DirectCast(_syntaxRef.GetSyntax(), ModifiedIdentifierSyntax) Return SourceMemberFieldSymbol.ComputeWithEventsFieldType( Me, syntax, binder, ignoreTypeSyntaxDiagnostics:=(_flags And SourceMemberFlags.FirstFieldDeclarationOfType) = 0, diagnostics:=diagnostics) Else Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Dim asClause = syntax.AsClause If asClause IsNot Nothing AndAlso asClause.Kind = SyntaxKind.AsNewClause AndAlso (DirectCast(asClause, AsNewClauseSyntax).NewExpression.Kind = SyntaxKind.AnonymousObjectCreationExpression) Then Return ErrorTypeSymbol.UnknownResultType Else Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing Dim omitFurtherDiagnostics As Boolean = String.IsNullOrEmpty(_name) If Not omitFurtherDiagnostics Then If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedProperty1_WRN_MissingAsClauseinProperty End If End If Dim identifier = syntax.Identifier Dim type = binder.DecodeIdentifierType(identifier, asClause, getErrorInfo, diagnostics) Debug.Assert(type IsNot Nothing) If Not type.IsErrorType() Then Dim errorLocation = SourceSymbolHelpers.GetAsClauseLocation(identifier, asClause) AccessCheck.VerifyAccessExposureForMemberType(Me, errorLocation, type, diagnostics) Dim restrictedType As TypeSymbol = Nothing If type.IsRestrictedTypeOrArrayType(restrictedType) Then Binder.ReportDiagnostic(diagnostics, errorLocation, ERRID.ERR_RestrictedType1, restrictedType) End If Dim getMethod = Me.GetMethod If getMethod IsNot Nothing AndAlso getMethod.IsIterator Then Dim originalRetTypeDef = type.OriginalDefinition If originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerable_T AndAlso originalRetTypeDef.SpecialType <> SpecialType.System_Collections_Generic_IEnumerator_T AndAlso type.SpecialType <> SpecialType.System_Collections_IEnumerable AndAlso type.SpecialType <> SpecialType.System_Collections_IEnumerator Then Binder.ReportDiagnostic(diagnostics, errorLocation, ERRID.ERR_BadIteratorReturn) End If End If End If Return type End If End If End Function Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property MetadataName As String Get If _lazyMetadataName Is Nothing Then OverloadingHelper.SetMetadataNameForAllOverloads(_name, SymbolKind.Property, _containingType) Debug.Assert(_lazyMetadataName IsNot Nothing) End If Return _lazyMetadataName End Get End Property Friend Overrides Sub SetMetadataName(metadataName As String) Dim old = Interlocked.CompareExchange(_lazyMetadataName, metadataName, Nothing) Debug.Assert(old Is Nothing OrElse old = metadataName) End Sub Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public ReadOnly Property ContainingSourceType As SourceMemberContainerTypeSymbol Get Return _containingType End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return New LexicalSortKey(_location, Me.DeclaringCompilation) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_location) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) End Get End Property Friend Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Dim propertyStatementSyntax = Me.Syntax Return propertyStatementSyntax IsNot Nothing AndAlso IsDefinedInSourceTree(propertyStatementSyntax.Parent, tree, definedWithinSpan, cancellationToken) End Function Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Property End Get End Property Private Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.IsWithEvents Then Return Nothing End If Return OneOrMany.Create(DirectCast(_syntaxRef.GetSyntax, PropertyStatementSyntax).AttributeLists) End Function Private Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.IsWithEvents Then Return Nothing End If Dim asClauseOpt = DirectCast(Me.Syntax, PropertyStatementSyntax).AsClause If asClauseOpt Is Nothing Then Return Nothing End If Return OneOrMany.Create(asClauseOpt.Attributes) End Function Friend Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(Me.GetAttributeDeclarations(), _lazyCustomAttributesBag) End If Return _lazyCustomAttributesBag End Function Friend Function GetReturnTypeAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyReturnTypeCustomAttributesBag Is Nothing OrElse Not _lazyReturnTypeCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(GetReturnTypeAttributeDeclarations(), _lazyReturnTypeCustomAttributesBag, symbolPart:=AttributeLocation.Return) End If Return _lazyReturnTypeCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> ''' <remarks> ''' NOTE: This method should always be kept as a NotOverridable method. ''' If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. ''' </remarks> Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetDecodedWellKnownAttributeData() As CommonPropertyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonPropertyWellKnownAttributeData) End Function Private Function GetDecodedReturnTypeWellKnownAttributeData() As CommonReturnTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyReturnTypeCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetReturnTypeAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonReturnTypeWellKnownAttributeData) End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of CommonPropertyEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then diagnostics.Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If If arguments.SymbolPart = AttributeLocation.Return Then Dim isMarshalAs = attrData.IsTargetAttribute(Me, AttributeDescription.MarshalAsAttribute) ' write-only property doesn't accept any return type attributes other than MarshalAs ' MarshalAs is applied on the "Value" parameter of the setter if the property has no parameters and the containing type is an interface . If _getMethod Is Nothing AndAlso _setMethod IsNot Nothing AndAlso (Not isMarshalAs OrElse Not SynthesizedParameterSymbol.IsMarshalAsAttributeApplicable(_setMethod)) Then diagnostics.Add(ERRID.WRN_ReturnTypeAttributeOnWriteOnlyProperty, arguments.AttributeSyntaxOpt.GetLocation()) Return End If If isMarshalAs Then MarshalAsAttributeDecoder(Of CommonReturnTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation). Decode(arguments, AttributeTargets.Field, MessageProvider.Instance) Return End If Else If attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of CommonPropertyWellKnownAttributeData).HasSpecialNameAttribute = True Return ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of CommonPropertyWellKnownAttributeData).HasExcludeFromCodeCoverageAttribute = True Return ElseIf Not IsWithEvents AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.DebuggerHiddenAttribute) Then ' if neither getter or setter is marked by DebuggerHidden Dev11 reports a warning If Not (_getMethod IsNot Nothing AndAlso DirectCast(_getMethod, SourcePropertyAccessorSymbol).HasDebuggerHiddenAttribute OrElse _setMethod IsNot Nothing AndAlso DirectCast(_setMethod, SourcePropertyAccessorSymbol).HasDebuggerHiddenAttribute) Then diagnostics.Add(ERRID.WRN_DebuggerHiddenIgnoredOnProperties, arguments.AttributeSyntaxOpt.GetLocation()) End If Return End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Friend ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Dim data = GetDecodedReturnTypeWellKnownAttributeData() Return If(data IsNot Nothing, data.MarshallingInformation, Nothing) End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return (_flags And SourceMemberFlags.MustOverride) <> 0 End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return (_flags And SourceMemberFlags.NotOverridable) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return (_flags And SourceMemberFlags.Overridable) <> 0 End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return (_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return (_flags And SourceMemberFlags.Shared) <> 0 End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return (_flags And SourceMemberFlags.Default) <> 0 End Get End Property Public Overrides ReadOnly Property IsWriteOnly As Boolean Get Return (_flags And SourceMemberFlags.WriteOnly) <> 0 End Get End Property Public Overrides ReadOnly Property IsReadOnly As Boolean Get Return (_flags And SourceMemberFlags.ReadOnly) <> 0 End Get End Property Public Overrides ReadOnly Property GetMethod As MethodSymbol Get Return _getMethod End Get End Property Public Overrides ReadOnly Property SetMethod As MethodSymbol Get Return _setMethod End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get If (_flags And SourceMemberFlags.Shadows) <> 0 Then Return False ElseIf (_flags And SourceMemberFlags.Overloads) <> 0 Then Return True Else Return (_flags And SourceMemberFlags.Overrides) <> 0 End If End Get End Property Public Overrides ReadOnly Property IsWithEvents As Boolean Get Return (_flags And SourceMemberFlags.WithEvents) <> 0 End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Shadows) <> 0 End Get End Property ''' <summary> True if 'Overloads' is explicitly specified in method's declaration </summary> Friend ReadOnly Property OverloadsExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Overloads) <> 0 End Get End Property ''' <summary> True if 'Overrides' is explicitly specified in method's declaration </summary> Friend ReadOnly Property OverridesExplicitly As Boolean Get Return (_flags And SourceMemberFlags.Overrides) <> 0 End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return (If(IsShared, Microsoft.Cci.CallingConvention.Default, Microsoft.Cci.CallingConvention.HasThis)) End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get EnsureSignature() Return _lazyParameters End Get End Property Private Sub EnsureSignature() If _lazyParameters.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim sourceModule = DirectCast(ContainingModule, SourceModuleSymbol) Dim params As ImmutableArray(Of ParameterSymbol) = ComputeParameters(diagnostics) Dim retType As TypeSymbol = ComputeType(diagnostics) ' For an overriding property, we need to copy custom modifiers from the property we override. Dim overriddenMembers As OverriddenMembersResult(Of PropertySymbol) If Not Me.IsOverrides OrElse Not OverrideHidingHelper.CanOverrideOrHide(Me) Then overriddenMembers = OverriddenMembersResult(Of PropertySymbol).Empty Else ' Since we cannot expose parameters and return type to the outside world yet, ' let's create a fake symbol to use for overriding resolution Dim fakeParamsBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance(params.Length) For Each param As ParameterSymbol In params fakeParamsBuilder.Add(New SignatureOnlyParameterSymbol( param.Type, ImmutableArray(Of CustomModifier).Empty, ImmutableArray(Of CustomModifier).Empty, defaultConstantValue:=Nothing, isParamArray:=False, isByRef:=param.IsByRef, isOut:=False, isOptional:=param.IsOptional)) Next overriddenMembers = OverrideHidingHelper(Of PropertySymbol). MakeOverriddenMembers(New SignatureOnlyPropertySymbol(Me.Name, _containingType, Me.IsReadOnly, Me.IsWriteOnly, fakeParamsBuilder.ToImmutableAndFree(), returnsByRef:=False, [type]:=retType, typeCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, refCustomModifiers:=ImmutableArray(Of CustomModifier).Empty, isOverrides:=True, isWithEvents:=Me.IsWithEvents)) End If Debug.Assert(IsDefinition) Dim overridden = overriddenMembers.OverriddenMember If overridden IsNot Nothing Then ' Copy custom modifiers Dim returnTypeWithCustomModifiers As TypeSymbol = overridden.Type ' We do an extra check before copying the return type to handle the case where the overriding ' property (incorrectly) has a different return type than the overridden property. In such cases, ' we want to retain the original (incorrect) return type to avoid hiding the return type ' given in source. If retType.IsSameType(returnTypeWithCustomModifiers, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds) Then retType = CustomModifierUtils.CopyTypeCustomModifiers(returnTypeWithCustomModifiers, retType) End If params = CustomModifierUtils.CopyParameterCustomModifiers(overridden.Parameters, params) End If ' Unlike PropertySymbol, in SourcePropertySymbol we cache the result of MakeOverriddenOfHiddenMembers, because we use ' it heavily while validating methods and emitting. Interlocked.CompareExchange(_lazyOverriddenProperties, overriddenMembers, Nothing) Interlocked.CompareExchange(_lazyType, retType, Nothing) sourceModule.AtomicStoreArrayAndDiagnostics( _lazyParameters, params, diagnostics) diagnostics.Free() End If End Sub Public Overrides ReadOnly Property ParameterCount As Integer Get If Not Me._lazyParameters.IsDefault Then Return Me._lazyParameters.Length End If Dim decl = Me.DeclarationSyntax If decl.Kind = SyntaxKind.PropertyStatement Then Dim paramList As ParameterListSyntax = DirectCast(decl, PropertyStatementSyntax).ParameterList Return If(paramList Is Nothing, 0, paramList.Parameters.Count) End If Return MyBase.ParameterCount End Get End Property Private Function ComputeParameters(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of ParameterSymbol) If Me.IsWithEvents Then ' no parameters Return ImmutableArray(Of ParameterSymbol).Empty End If Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Dim parameters = binder.DecodePropertyParameterList(Me, syntax.ParameterList, diagnostics) If IsDefault Then ' Default properties must have required parameters. If Not HasRequiredParameters(parameters) Then diagnostics.Add(ERRID.ERR_DefaultPropertyWithNoParams, _location) End If ' 'touch' System_Reflection_DefaultMemberAttribute__ctor to make sure all diagnostics are reported binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, syntax, diagnostics) End If Return parameters End Function Friend Overrides ReadOnly Property MeParameter As ParameterSymbol Get If IsShared Then Return Nothing Else If _lazyMeParameter Is Nothing Then Interlocked.CompareExchange(Of ParameterSymbol)(_lazyMeParameter, New MeParameterSymbol(Me), Nothing) End If Return _lazyMeParameter End If End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of PropertySymbol) Get If _lazyImplementedProperties.IsDefault Then Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) sourceModule.AtomicStoreArrayAndDiagnostics(_lazyImplementedProperties, ComputeExplicitInterfaceImplementations(diagnostics), diagnostics) diagnostics.Free() End If Return _lazyImplementedProperties End Get End Property Private Function ComputeExplicitInterfaceImplementations(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of PropertySymbol) Dim binder = CreateBinderForTypeDeclaration() Dim syntax = DirectCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) Return BindImplementsClause(_containingType, binder, Me, syntax, diagnostics) End Function ''' <summary> ''' Helper method for accessors to get the overridden accessor methods. Should only be called by the ''' accessor method symbols. ''' </summary> ''' <param name="getter">True to get implemented getters, False to get implemented setters</param> ''' <returns>All the accessors of the given kind implemented by this property.</returns> Friend Function GetAccessorImplementations(getter As Boolean) As ImmutableArray(Of MethodSymbol) Dim implementedProperties = ExplicitInterfaceImplementations Debug.Assert(Not implementedProperties.IsDefault) If implementedProperties.IsEmpty Then Return ImmutableArray(Of MethodSymbol).Empty Else Dim builder As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() For Each implementedProp In implementedProperties Dim accessor = If(getter, implementedProp.GetMethod, implementedProp.SetMethod) If accessor IsNot Nothing AndAlso accessor.RequiresImplementation() Then builder.Add(accessor) End If Next Return builder.ToImmutableAndFree() End If End Function Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of PropertySymbol) Get EnsureSignature() Return Me._lazyOverriddenProperties End Get End Property Public Overrides ReadOnly Property TypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Dim overridden = Me.OverriddenProperty If overridden Is Nothing Then Return ImmutableArray(Of CustomModifier).Empty Else Return overridden.TypeCustomModifiers End If End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return CType((_flags And SourceMemberFlags.AccessibilityMask), Accessibility) End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return _containingType.AreMembersImplicitlyDeclared End Get End Property Friend ReadOnly Property IsCustomProperty As Boolean Get ' Auto and WithEvents properties have backing fields Return _backingField Is Nothing AndAlso Not IsMustOverride End Get End Property Friend ReadOnly Property IsAutoProperty As Boolean Get Return Not IsWithEvents AndAlso _backingField IsNot Nothing End Get End Property Friend Overrides ReadOnly Property AssociatedField As FieldSymbol Get Return _backingField End Get End Property ''' <summary> ''' Property declaration syntax node. ''' It is either PropertyStatement for normal properties or ModifiedIdentifier for WithEvents ones. ''' </summary> Friend ReadOnly Property Syntax As VisualBasicSyntaxNode Get Return If(_syntaxRef IsNot Nothing, _syntaxRef.GetVisualBasicSyntax(), Nothing) End Get End Property Friend ReadOnly Property SyntaxReference As SyntaxReference Get Return Me._syntaxRef End Get End Property Friend ReadOnly Property BlockSyntaxReference As SyntaxReference Get Return Me._blockRef End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get ' If there are no attributes then this symbol is not Obsolete. If (Not Me._containingType.AnyMemberHasAttributes) Then Return Nothing End If Dim lazyCustomAttributesBag = Me._lazyCustomAttributesBag If (lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) Then Dim data = DirectCast(_lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonPropertyEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If Return ObsoleteAttributeData.Uninitialized End Get End Property ' Get the location of the implements name for an explicit implemented property, for later error reporting. Friend Function GetImplementingLocation(implementedProperty As PropertySymbol) As Location Debug.Assert(ExplicitInterfaceImplementations.Contains(implementedProperty)) Dim propertySyntax = TryCast(_syntaxRef.GetSyntax(), PropertyStatementSyntax) If propertySyntax IsNot Nothing AndAlso propertySyntax.ImplementsClause IsNot Nothing Then Dim binder = CreateBinderForTypeDeclaration() Dim implementingSyntax = FindImplementingSyntax(Of PropertySymbol)(propertySyntax.ImplementsClause, Me, implementedProperty, _containingType, binder) Return implementingSyntax.GetLocation() End If Return If(Locations.FirstOrDefault(), NoLocation.Singleton) End Function Private Function CreateBinderForTypeDeclaration() As Binder Dim binder = BinderBuilder.CreateBinderForType(DirectCast(ContainingModule, SourceModuleSymbol), _syntaxRef.SyntaxTree, _containingType) Return New LocationSpecificBinder(BindingLocation.PropertySignature, Me, binder) End Function Private Shared Function CreateAccessor([property] As SourcePropertySymbol, kindFlags As SourceMemberFlags, propertyFlags As SourceMemberFlags, bodyBinder As Binder, syntax As AccessorBlockSyntax, diagnostics As DiagnosticBag) As SourcePropertyAccessorSymbol Dim accessor = SourcePropertyAccessorSymbol.CreatePropertyAccessor([property], kindFlags, propertyFlags, bodyBinder, syntax, diagnostics) Debug.Assert(accessor IsNot Nothing) Dim localAccessibility = accessor.LocalAccessibility If Not IsAccessibilityMoreRestrictive([property].DeclaredAccessibility, localAccessibility) Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlagsRestrict, diagnostics) ElseIf [property].IsNotOverridable AndAlso localAccessibility = Accessibility.Private Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlags1, diagnostics) ElseIf [property].IsDefault AndAlso localAccessibility = Accessibility.Private Then ReportAccessorAccessibilityError(bodyBinder, syntax, ERRID.ERR_BadPropertyAccessorFlags2, diagnostics) End If Return accessor End Function ''' <summary> ''' Return true if the accessor accessibility is more restrictive ''' than the property accessibility, otherwise false. ''' </summary> Private Shared Function IsAccessibilityMoreRestrictive([property] As Accessibility, accessor As Accessibility) As Boolean If accessor = Accessibility.NotApplicable Then Return True End If Return (accessor < [property]) AndAlso ((accessor <> Accessibility.Protected) OrElse ([property] <> Accessibility.Friend)) End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function Private Shared Function DecodeModifiers(modifiers As SyntaxTokenList, container As SourceMemberContainerTypeSymbol, binder As Binder, diagBag As DiagnosticBag) As MemberModifiers ' Decode the flags. Dim propertyModifiers = binder.DecodeModifiers(modifiers, SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Default Or SourceMemberFlags.Overloads Or SourceMemberFlags.Shadows Or SourceMemberFlags.Shared Or SourceMemberFlags.Overridable Or SourceMemberFlags.NotOverridable Or SourceMemberFlags.Overrides Or SourceMemberFlags.MustOverride Or SourceMemberFlags.ReadOnly Or SourceMemberFlags.Iterator Or SourceMemberFlags.WriteOnly, ERRID.ERR_BadPropertyFlags1, Accessibility.Public, diagBag) ' Diagnose Shared with an overriding modifier. Dim flags = propertyModifiers.FoundFlags If (flags And SourceMemberFlags.Default) <> 0 AndAlso (flags And SourceMemberFlags.InvalidIfDefault) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadFlagsWithDefault1, diagBag, InvalidModifiersIfDefault) flags = flags And Not SourceMemberFlags.InvalidIfDefault propertyModifiers = New MemberModifiers(flags, propertyModifiers.ComputedFlags) End If propertyModifiers = binder.ValidateSharedPropertyAndMethodModifiers(modifiers, propertyModifiers, True, container, diagBag) Return propertyModifiers End Function Private Shared Function BindImplementsClause(containingType As SourceMemberContainerTypeSymbol, bodyBinder As Binder, prop As SourcePropertySymbol, syntax As PropertyStatementSyntax, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of PropertySymbol) If syntax.ImplementsClause IsNot Nothing Then If prop.IsShared And Not containingType.IsModuleType Then ' Implementing with shared methods is illegal. ' Module case is caught inside ProcessImplementsClause and has different message. Binder.ReportDiagnostic(diagnostics, syntax.Modifiers.First(SyntaxKind.SharedKeyword), ERRID.ERR_SharedOnProcThatImpl, syntax.Identifier.ToString()) Else Return ProcessImplementsClause(Of PropertySymbol)(syntax.ImplementsClause, prop, containingType, bodyBinder, diagnostics) End If End If Return ImmutableArray(Of PropertySymbol).Empty End Function ''' <summary> ''' Returns the location (span) of the accessor begin block. ''' (Used for consistency with the native compiler that ''' highlights the entire begin block for certain diagnostics.) ''' </summary> Private Shared Function GetAccessorBlockBeginLocation(accessor As SourcePropertyAccessorSymbol) As Location Dim syntaxTree = accessor.SyntaxTree Dim block = DirectCast(accessor.BlockSyntax, AccessorBlockSyntax) Debug.Assert(syntaxTree IsNot Nothing) Debug.Assert(block IsNot Nothing) Debug.Assert(block.BlockStatement IsNot Nothing) Return syntaxTree.GetLocation(block.BlockStatement.Span) End Function Private Shared ReadOnly s_overridableModifierKinds() As SyntaxKind = { SyntaxKind.OverridableKeyword } Private Shared ReadOnly s_accessibilityModifierKinds() As SyntaxKind = { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword, SyntaxKind.PublicKeyword } ''' <summary> ''' Report an error associated with the accessor accessibility modifier. ''' </summary> Private Shared Sub ReportAccessorAccessibilityError(binder As Binder, syntax As AccessorBlockSyntax, errorId As ERRID, diagnostics As DiagnosticBag) binder.ReportModifierError(syntax.BlockStatement.Modifiers, errorId, diagnostics, s_accessibilityModifierKinds) End Sub Private Shared Function HasRequiredParameters(parameters As ImmutableArray(Of ParameterSymbol)) As Boolean For Each parameter In parameters If Not parameter.IsOptional AndAlso Not parameter.IsParamArray Then Return True End If Next Return False End Function ''' <summary> ''' Gets the syntax tree. ''' </summary> Friend ReadOnly Property SyntaxTree As SyntaxTree Get Return _syntaxRef.SyntaxTree End Get End Property ' This should be called at most once after the attributes are bound. Attributes must be bound after the class ' and members are fully declared to avoid infinite recursion. Private Sub SetCustomAttributeData(attributeData As CustomAttributesBag(Of VisualBasicAttributeData)) Debug.Assert(attributeData IsNot Nothing) Debug.Assert(_lazyCustomAttributesBag Is Nothing) _lazyCustomAttributesBag = attributeData End Sub Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) MyBase.GenerateDeclarationErrors(cancellationToken) ' Ensure return type attributes are bound Dim unusedType = Me.Type Dim unusedParameters = Me.Parameters Me.GetReturnTypeAttributesBag() Dim unusedImplementations = Me.ExplicitInterfaceImplementations If DeclaringCompilation.EventQueue IsNot Nothing Then DirectCast(Me.ContainingModule, SourceModuleSymbol).AtomicSetFlagAndRaiseSymbolDeclaredEvent(_lazyState, StateFlags.SymbolDeclaredEvent, 0, Me) End If End Sub Friend Overrides ReadOnly Property IsMyGroupCollectionProperty As Boolean Get Return False End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If Me.Type.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(Type)) End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/BoundTree/BoundExpressionExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class BoundExpressionExtensions { /// <summary> /// Returns the RefKind if the expression represents a symbol /// that has a RefKind, or RefKind.None otherwise. /// </summary> public static RefKind GetRefKind(this BoundExpression node) { switch (node.Kind) { case BoundKind.Local: return ((BoundLocal)node).LocalSymbol.RefKind; case BoundKind.Parameter: return ((BoundParameter)node).ParameterSymbol.RefKind; case BoundKind.Call: return ((BoundCall)node).Method.RefKind; case BoundKind.PropertyAccess: return ((BoundPropertyAccess)node).PropertySymbol.RefKind; default: return RefKind.None; } } public static bool IsLiteralNull(this BoundExpression node) { return node is { Kind: BoundKind.Literal, ConstantValue: { Discriminator: ConstantValueTypeDiscriminator.Null } }; } public static bool IsLiteralDefault(this BoundExpression node) { return node.Kind == BoundKind.DefaultLiteral; } public static bool IsImplicitObjectCreation(this BoundExpression node) { return node.Kind == BoundKind.UnconvertedObjectCreationExpression; } public static bool IsLiteralDefaultOrImplicitObjectCreation(this BoundExpression node) { return node.IsLiteralDefault() || node.IsImplicitObjectCreation(); } // returns true when expression has no side-effects and produces // default value (null, zero, false, default(T) ...) // // NOTE: This method is a very shallow check. // It does not make any assumptions about what this node could become // after some folding/propagation/algebraic transformations. public static bool IsDefaultValue(this BoundExpression node) { if (node.Kind == BoundKind.DefaultExpression || node.Kind == BoundKind.DefaultLiteral) { return true; } var constValue = node.ConstantValue; if (constValue != null) { return constValue.IsDefaultValue; } return false; } public static bool HasExpressionType(this BoundExpression node) { // null literal, method group, and anonymous function expressions have no type. return node.Type is { }; } public static bool HasDynamicType(this BoundExpression node) { var type = node.Type; return type is { } && type.IsDynamic(); } public static NamedTypeSymbol? GetInferredDelegateType(this BoundExpression expr, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expr.Kind is BoundKind.MethodGroup or BoundKind.UnboundLambda); var delegateType = expr.GetFunctionType()?.GetInternalDelegateType(); delegateType?.AddUseSiteInfo(ref useSiteInfo); return delegateType; } public static TypeSymbol? GetTypeOrFunctionType(this BoundExpression expr) { if (expr.Type is { } type) { return type; } return expr.GetFunctionType(); } public static FunctionTypeSymbol? GetFunctionType(this BoundExpression expr) { var lazyType = expr switch { BoundMethodGroup methodGroup => methodGroup.FunctionType, UnboundLambda unboundLambda => unboundLambda.FunctionType, _ => null }; return lazyType?.GetValue(); } public static bool MethodGroupReceiverIsDynamic(this BoundMethodGroup node) { return node.InstanceOpt != null && node.InstanceOpt.HasDynamicType(); } public static bool HasExpressionSymbols(this BoundExpression node) { switch (node.Kind) { case BoundKind.Call: case BoundKind.Local: case BoundKind.FieldAccess: case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: case BoundKind.EventAccess: case BoundKind.MethodGroup: case BoundKind.ObjectCreationExpression: case BoundKind.TypeExpression: case BoundKind.NamespaceExpression: return true; case BoundKind.BadExpression: return ((BoundBadExpression)node).Symbols.Length > 0; default: return false; } } public static void GetExpressionSymbols(this BoundExpression node, ArrayBuilder<Symbol> symbols, BoundNode parent, Binder binder) { switch (node.Kind) { case BoundKind.MethodGroup: // Special case: if we are looking for info on "M" in "new Action(M)" in the context of a parent // then we want to get the symbol that overload resolution chose for M, not on the whole method group M. var delegateCreation = parent as BoundDelegateCreationExpression; if (delegateCreation != null && delegateCreation.MethodOpt is { }) { symbols.Add(delegateCreation.MethodOpt); } else { symbols.AddRange(CSharpSemanticModel.GetReducedAndFilteredMethodGroupSymbols(binder, (BoundMethodGroup)node)); } break; case BoundKind.BadExpression: foreach (var s in ((BoundBadExpression)node).Symbols) { if (s is { }) symbols.Add(s); } break; case BoundKind.DelegateCreationExpression: var expr = (BoundDelegateCreationExpression)node; var ctor = expr.Type.GetMembers(WellKnownMemberNames.InstanceConstructorName).FirstOrDefault(); if (ctor is { }) { symbols.Add(ctor); } break; case BoundKind.Call: // Either overload resolution succeeded for this call or it did not. If it did not // succeed then we've stashed the original method symbols from the method group, // and we should use those as the symbols displayed for the call. If it did succeed // then we did not stash any symbols; just fall through to the default case. var originalMethods = ((BoundCall)node).OriginalMethodsOpt; if (originalMethods.IsDefault) { goto default; } symbols.AddRange(originalMethods); break; case BoundKind.IndexerAccess: // Same behavior as for a BoundCall: if overload resolution failed, pull out stashed candidates; // otherwise use the default behavior. var originalIndexers = ((BoundIndexerAccess)node).OriginalIndexersOpt; if (originalIndexers.IsDefault) { goto default; } symbols.AddRange(originalIndexers); break; default: var symbol = node.ExpressionSymbol; if (symbol is { }) { symbols.Add(symbol); } break; } } // Get the conversion associated with a bound node, or else Identity. public static Conversion GetConversion(this BoundExpression boundNode) { switch (boundNode.Kind) { case BoundKind.Conversion: BoundConversion conversionNode = (BoundConversion)boundNode; return conversionNode.Conversion; default: return Conversion.Identity; } } internal static bool IsExpressionOfComImportType([NotNullWhen(true)] this BoundExpression? expressionOpt) { // NOTE: Dev11 also returns false if expressionOpt is a TypeExpression. Unfortunately, // that makes it impossible to handle TypeOrValueExpression in a consistent way, since // we don't know whether it's a type until after overload resolution and we can't do // overload resolution without knowing whether 'ref' can be omitted (which is what this // method is used to determine). Since there is no intuitive reason to disallow // omitting 'ref' for static methods, we'll drop the restriction on TypeExpression. if (expressionOpt == null) return false; TypeSymbol? receiverType = expressionOpt.Type; return receiverType is NamedTypeSymbol { Kind: SymbolKind.NamedType, IsComImport: true }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class BoundExpressionExtensions { /// <summary> /// Returns the RefKind if the expression represents a symbol /// that has a RefKind, or RefKind.None otherwise. /// </summary> public static RefKind GetRefKind(this BoundExpression node) { switch (node.Kind) { case BoundKind.Local: return ((BoundLocal)node).LocalSymbol.RefKind; case BoundKind.Parameter: return ((BoundParameter)node).ParameterSymbol.RefKind; case BoundKind.Call: return ((BoundCall)node).Method.RefKind; case BoundKind.PropertyAccess: return ((BoundPropertyAccess)node).PropertySymbol.RefKind; default: return RefKind.None; } } public static bool IsLiteralNull(this BoundExpression node) { return node is { Kind: BoundKind.Literal, ConstantValue: { Discriminator: ConstantValueTypeDiscriminator.Null } }; } public static bool IsLiteralDefault(this BoundExpression node) { return node.Kind == BoundKind.DefaultLiteral; } public static bool IsImplicitObjectCreation(this BoundExpression node) { return node.Kind == BoundKind.UnconvertedObjectCreationExpression; } public static bool IsLiteralDefaultOrImplicitObjectCreation(this BoundExpression node) { return node.IsLiteralDefault() || node.IsImplicitObjectCreation(); } // returns true when expression has no side-effects and produces // default value (null, zero, false, default(T) ...) // // NOTE: This method is a very shallow check. // It does not make any assumptions about what this node could become // after some folding/propagation/algebraic transformations. public static bool IsDefaultValue(this BoundExpression node) { if (node.Kind == BoundKind.DefaultExpression || node.Kind == BoundKind.DefaultLiteral) { return true; } var constValue = node.ConstantValue; if (constValue != null) { return constValue.IsDefaultValue; } return false; } public static bool HasExpressionType(this BoundExpression node) { // null literal, method group, and anonymous function expressions have no type. return node.Type is { }; } public static bool HasDynamicType(this BoundExpression node) { var type = node.Type; return type is { } && type.IsDynamic(); } public static NamedTypeSymbol? GetInferredDelegateType(this BoundExpression expr, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expr.Kind is BoundKind.MethodGroup or BoundKind.UnboundLambda); var delegateType = expr.GetFunctionType()?.GetInternalDelegateType(); delegateType?.AddUseSiteInfo(ref useSiteInfo); return delegateType; } public static TypeSymbol? GetTypeOrFunctionType(this BoundExpression expr) { if (expr.Type is { } type) { return type; } return expr.GetFunctionType(); } public static FunctionTypeSymbol? GetFunctionType(this BoundExpression expr) { var lazyType = expr switch { BoundMethodGroup methodGroup => methodGroup.FunctionType, UnboundLambda unboundLambda => unboundLambda.FunctionType, _ => null }; return lazyType?.GetValue(); } public static bool MethodGroupReceiverIsDynamic(this BoundMethodGroup node) { return node.InstanceOpt != null && node.InstanceOpt.HasDynamicType(); } public static bool HasExpressionSymbols(this BoundExpression node) { switch (node.Kind) { case BoundKind.Call: case BoundKind.Local: case BoundKind.FieldAccess: case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: case BoundKind.EventAccess: case BoundKind.MethodGroup: case BoundKind.ObjectCreationExpression: case BoundKind.TypeExpression: case BoundKind.NamespaceExpression: return true; case BoundKind.BadExpression: return ((BoundBadExpression)node).Symbols.Length > 0; default: return false; } } public static void GetExpressionSymbols(this BoundExpression node, ArrayBuilder<Symbol> symbols, BoundNode parent, Binder binder) { switch (node.Kind) { case BoundKind.MethodGroup: // Special case: if we are looking for info on "M" in "new Action(M)" in the context of a parent // then we want to get the symbol that overload resolution chose for M, not on the whole method group M. var delegateCreation = parent as BoundDelegateCreationExpression; if (delegateCreation != null && delegateCreation.MethodOpt is { }) { symbols.Add(delegateCreation.MethodOpt); } else { symbols.AddRange(CSharpSemanticModel.GetReducedAndFilteredMethodGroupSymbols(binder, (BoundMethodGroup)node)); } break; case BoundKind.BadExpression: foreach (var s in ((BoundBadExpression)node).Symbols) { if (s is { }) symbols.Add(s); } break; case BoundKind.DelegateCreationExpression: var expr = (BoundDelegateCreationExpression)node; var ctor = expr.Type.GetMembers(WellKnownMemberNames.InstanceConstructorName).FirstOrDefault(); if (ctor is { }) { symbols.Add(ctor); } break; case BoundKind.Call: // Either overload resolution succeeded for this call or it did not. If it did not // succeed then we've stashed the original method symbols from the method group, // and we should use those as the symbols displayed for the call. If it did succeed // then we did not stash any symbols; just fall through to the default case. var originalMethods = ((BoundCall)node).OriginalMethodsOpt; if (originalMethods.IsDefault) { goto default; } symbols.AddRange(originalMethods); break; case BoundKind.IndexerAccess: // Same behavior as for a BoundCall: if overload resolution failed, pull out stashed candidates; // otherwise use the default behavior. var originalIndexers = ((BoundIndexerAccess)node).OriginalIndexersOpt; if (originalIndexers.IsDefault) { goto default; } symbols.AddRange(originalIndexers); break; default: var symbol = node.ExpressionSymbol; if (symbol is { }) { symbols.Add(symbol); } break; } } // Get the conversion associated with a bound node, or else Identity. public static Conversion GetConversion(this BoundExpression boundNode) { switch (boundNode.Kind) { case BoundKind.Conversion: BoundConversion conversionNode = (BoundConversion)boundNode; return conversionNode.Conversion; default: return Conversion.Identity; } } internal static bool IsExpressionOfComImportType([NotNullWhen(true)] this BoundExpression? expressionOpt) { // NOTE: Dev11 also returns false if expressionOpt is a TypeExpression. Unfortunately, // that makes it impossible to handle TypeOrValueExpression in a consistent way, since // we don't know whether it's a type until after overload resolution and we can't do // overload resolution without knowing whether 'ref' can be omitted (which is what this // method is used to determine). Since there is no intuitive reason to disallow // omitting 'ref' for static methods, we'll drop the restriction on TypeExpression. if (expressionOpt == null) return false; TypeSymbol? receiverType = expressionOpt.Type; return receiverType is NamedTypeSymbol { Kind: SymbolKind.NamedType, IsComImport: true }; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Binder/SwitchBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SwitchBinder : LocalScopeBinder { protected readonly SwitchStatementSyntax SwitchSyntax; private readonly GeneratedLabelSymbol _breakLabel; private BoundExpression _switchGoverningExpression; private BindingDiagnosticBag _switchGoverningDiagnostics; private SwitchBinder(Binder next, SwitchStatementSyntax switchSyntax) : base(next) { SwitchSyntax = switchSyntax; _breakLabel = new GeneratedLabelSymbol("break"); } protected bool PatternsEnabled => ((CSharpParseOptions)SwitchSyntax.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching) != false; protected BoundExpression SwitchGoverningExpression { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); Debug.Assert(_switchGoverningExpression != null); return _switchGoverningExpression; } } protected TypeSymbol SwitchGoverningType => SwitchGoverningExpression.Type; protected uint SwitchGoverningValEscape => GetValEscape(SwitchGoverningExpression, LocalScopeDepth); protected BindingDiagnosticBag SwitchGoverningDiagnostics { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); return _switchGoverningDiagnostics; } } private void EnsureSwitchGoverningExpressionAndDiagnosticsBound() { if (_switchGoverningExpression == null) { var switchGoverningDiagnostics = new BindingDiagnosticBag(); var boundSwitchExpression = BindSwitchGoverningExpression(switchGoverningDiagnostics); _switchGoverningDiagnostics = switchGoverningDiagnostics; Interlocked.CompareExchange(ref _switchGoverningExpression, boundSwitchExpression, null); } } // Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Default label(s) are indexed on a special DefaultKey object. // Invalid case labels with null constant value are indexed on the labelName. private Dictionary<object, SourceLabelSymbol> _lazySwitchLabelsMap; private static readonly object s_defaultKey = new object(); private Dictionary<object, SourceLabelSymbol> LabelsByValue { get { if (_lazySwitchLabelsMap == null && this.Labels.Length > 0) { _lazySwitchLabelsMap = BuildLabelsByValue(this.Labels); } return _lazySwitchLabelsMap; } } private static Dictionary<object, SourceLabelSymbol> BuildLabelsByValue(ImmutableArray<LabelSymbol> labels) { Debug.Assert(labels.Length > 0); var map = new Dictionary<object, SourceLabelSymbol>(labels.Length, new SwitchConstantValueHelper.SwitchLabelsComparer()); foreach (SourceLabelSymbol label in labels) { SyntaxKind labelKind = label.IdentifierNodeOrToken.Kind(); if (labelKind == SyntaxKind.IdentifierToken) { continue; } object key; var constantValue = label.SwitchCaseLabelConstant; if ((object)constantValue != null && !constantValue.IsBad) { // Case labels with a non-null constant value are indexed on their ConstantValue. key = KeyForConstant(constantValue); } else if (labelKind == SyntaxKind.DefaultSwitchLabel) { // Default label(s) are indexed on a special DefaultKey object. key = s_defaultKey; } else { // Invalid case labels with null constant value are indexed on the labelName. key = label.IdentifierNodeOrToken.AsNode(); } // If there is a duplicate label, ignore it. It will be reported when binding the switch label. if (!map.ContainsKey(key)) { map.Add(key, label); } } return map; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocals(section.Statements, GetBinder(section))); } return builder.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { var builder = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocalFunctions(section.Statements)); } return builder.ToImmutableAndFree(); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } internal override GeneratedLabelSymbol BreakLabel { get { return _breakLabel; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { // We bind the switch expression and the switch case label expressions so that the constant values can be // part of the label, but we do not report any diagnostics here. Diagnostics will be reported during binding. ArrayBuilder<LabelSymbol> labels = ArrayBuilder<LabelSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { // add switch case/default labels BuildSwitchLabels(section.Labels, GetBinder(section), labels, BindingDiagnosticBag.Discarded); // add regular labels from the statements in the switch section BuildLabels(section.Statements, ref labels); } return labels.ToImmutableAndFree(); } internal override bool IsLabelsScopeBinder { get { return true; } } private void BuildSwitchLabels(SyntaxList<SwitchLabelSyntax> labelsSyntax, Binder sectionBinder, ArrayBuilder<LabelSymbol> labels, BindingDiagnosticBag tempDiagnosticBag) { // add switch case/default labels foreach (var labelSyntax in labelsSyntax) { ConstantValue boundLabelConstantOpt = null; switch (labelSyntax.Kind()) { case SyntaxKind.CaseSwitchLabel: // compute the constant value to place in the label symbol var caseLabel = (CaseSwitchLabelSyntax)labelSyntax; Debug.Assert(caseLabel.Value != null); var boundLabelExpression = sectionBinder.BindTypeOrRValue(caseLabel.Value, tempDiagnosticBag); if (boundLabelExpression is BoundTypeExpression type) { // Nothing to do at this point. The label will be bound later. } else { _ = ConvertCaseExpression(labelSyntax, boundLabelExpression, sectionBinder, out boundLabelConstantOpt, tempDiagnosticBag); } break; case SyntaxKind.CasePatternSwitchLabel: // bind the pattern, to cause its pattern variables to be inferred if necessary var matchLabel = (CasePatternSwitchLabelSyntax)labelSyntax; _ = sectionBinder.BindPattern( matchLabel.Pattern, SwitchGoverningType, SwitchGoverningValEscape, permitDesignations: true, labelSyntax.HasErrors, tempDiagnosticBag); break; default: // No constant value break; } // Create the label symbol labels.Add(new SourceLabelSymbol((MethodSymbol)this.ContainingMemberOrLambda, labelSyntax, boundLabelConstantOpt)); } } protected BoundExpression ConvertCaseExpression(CSharpSyntaxNode node, BoundExpression caseExpression, Binder sectionBinder, out ConstantValue constantValueOpt, BindingDiagnosticBag diagnostics, bool isGotoCaseExpr = false) { bool hasErrors = false; if (isGotoCaseExpr) { // SPEC VIOLATION for Dev10 COMPATIBILITY: // Dev10 compiler violates the SPEC comment below: // "if the constant-expression is not implicitly convertible (§6.1) to // the governing type of the nearest enclosing switch statement, // a compile-time error occurs" // If there is no implicit conversion from gotoCaseExpression to switchGoverningType, // but there exists an explicit conversion, Dev10 compiler generates a warning "WRN_GotoCaseShouldConvert" // instead of an error. See test "CS0469_NoImplicitConversionWarning". CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(caseExpression, SwitchGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, caseExpression, SwitchGoverningType); hasErrors = true; } else if (!conversion.IsImplicit) { diagnostics.Add(ErrorCode.WRN_GotoCaseShouldConvert, node.Location, SwitchGoverningType); hasErrors = true; } caseExpression = CreateConversion(caseExpression, conversion, SwitchGoverningType, diagnostics); } return ConvertPatternExpression(SwitchGoverningType, node, caseExpression, out constantValueOpt, hasErrors, diagnostics); } private static readonly object s_nullKey = new object(); protected static object KeyForConstant(ConstantValue constantValue) { Debug.Assert((object)constantValue != null); return constantValue.IsNull ? s_nullKey : constantValue.Value; } protected SourceLabelSymbol FindMatchingSwitchCaseLabel(ConstantValue constantValue, CSharpSyntaxNode labelSyntax) { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Invalid case labels (with null constant value) are indexed on the label syntax. object key; if ((object)constantValue != null && !constantValue.IsBad) { key = KeyForConstant(constantValue); } else { key = labelSyntax; } return FindMatchingSwitchLabel(key); } private SourceLabelSymbol GetDefaultLabel() { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Default label(s) are indexed on a special DefaultKey object. return FindMatchingSwitchLabel(s_defaultKey); } private SourceLabelSymbol FindMatchingSwitchLabel(object key) { Debug.Assert(key != null); var labelsMap = LabelsByValue; if (labelsMap != null) { SourceLabelSymbol label; if (labelsMap.TryGetValue(key, out label)) { Debug.Assert((object)label != null); return label; } } return null; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return SwitchSyntax; } } # region "Switch statement binding methods" // Bind the switch expression private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { // We are at present inside the switch binder, but the switch expression is not // bound in the context of the switch binder; it's bound in the context of the // enclosing binder. For example: // // class C { // int x; // void M() { // switch(x) { // case 1: // int x; // // The "x" in "switch(x)" refers to this.x, not the local x that is in scope inside the switch block. Debug.Assert(ScopeDesignator == SwitchSyntax); ExpressionSyntax node = SwitchSyntax.Expression; var binder = this.GetBinder(node); Debug.Assert(binder != null); var switchGoverningExpression = binder.BindRValueWithoutTargetType(node, diagnostics); var switchGoverningType = switchGoverningExpression.Type; if ((object)switchGoverningType != null && !switchGoverningType.IsErrorType()) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise if exactly one user-defined implicit conversion (§6.4) exists from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types, then the result is the switch governing type // SPEC: 3) Otherwise (in C# 7 and later) the switch governing type is the type of the // SPEC: switch expression. if (switchGoverningType.IsValidV6SwitchGoverningType()) { // Condition (1) satisfied // Note: dev11 actually checks the stripped type, but nullable was introduced at the same // time, so it doesn't really matter. if (switchGoverningType.SpecialType == SpecialType.System_Boolean) { CheckFeatureAvailability(node, MessageID.IDS_FeatureSwitchOnBool, diagnostics); } return switchGoverningExpression; } else { TypeSymbol resultantGoverningType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(switchGoverningType, out resultantGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (conversion.IsValid) { // Condition (2) satisfied Debug.Assert(conversion.Kind == ConversionKind.ImplicitUserDefined); Debug.Assert(conversion.Method.IsUserDefinedConversion()); Debug.Assert(conversion.UserDefinedToConversion.IsIdentity); Debug.Assert(resultantGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); return binder.CreateConversion(node, switchGoverningExpression, conversion, isCast: false, conversionGroupOpt: null, resultantGoverningType, diagnostics); } else if (!switchGoverningType.IsVoidType()) { // Otherwise (3) satisfied if (!PatternsEnabled) { diagnostics.Add(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, node.Location); } return switchGoverningExpression; } else { switchGoverningType = CreateErrorType(switchGoverningType.Name); } } } if (!switchGoverningExpression.HasAnyErrors) { Debug.Assert((object)switchGoverningExpression.Type == null || switchGoverningExpression.Type.IsVoidType()); diagnostics.Add(ErrorCode.ERR_SwitchExpressionValueExpected, node.Location, switchGoverningExpression.Display); } return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(switchGoverningExpression), switchGoverningType ?? CreateErrorType()); } private Dictionary<SyntaxNode, LabelSymbol> _labelsByNode; protected Dictionary<SyntaxNode, LabelSymbol> LabelsByNode { get { if (_labelsByNode == null) { var result = new Dictionary<SyntaxNode, LabelSymbol>(); foreach (var label in Labels) { var node = ((SourceLabelSymbol)label).IdentifierNodeOrToken.AsNode(); if (node != null) { result.Add(node, label); } } _labelsByNode = result; } return _labelsByNode; } } internal BoundStatement BindGotoCaseOrDefault(GotoStatementSyntax node, Binder gotoBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement || node.Kind() == SyntaxKind.GotoDefaultStatement); BoundExpression gotoCaseExpressionOpt = null; // Prevent cascading diagnostics if (!node.HasErrors) { ConstantValue gotoCaseExpressionConstant = null; bool hasErrors = false; SourceLabelSymbol matchedLabelSymbol; // SPEC: If the goto case statement is not enclosed by a switch statement, if the constant-expression // SPEC: is not implicitly convertible (§6.1) to the governing type of the nearest enclosing switch statement, // SPEC: or if the nearest enclosing switch statement does not contain a case label with the given constant value, // SPEC: a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, or if the nearest enclosing // SPEC: switch statement does not contain a default label, a compile-time error occurs. if (node.Expression != null) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement); // Bind the goto case expression gotoCaseExpressionOpt = gotoBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); gotoCaseExpressionOpt = ConvertCaseExpression(node, gotoCaseExpressionOpt, gotoBinder, out gotoCaseExpressionConstant, diagnostics, isGotoCaseExpr: true); // Check for bind errors hasErrors = hasErrors || gotoCaseExpressionOpt.HasAnyErrors; if (!hasErrors && gotoCaseExpressionConstant == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, node.Location); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(gotoCaseExpressionOpt, diagnostics); // LabelSymbols for all the switch case labels are created by BuildLabels(). // Fetch the matching switch case label symbols matchedLabelSymbol = FindMatchingSwitchCaseLabel(gotoCaseExpressionConstant, node); } else { Debug.Assert(node.Kind() == SyntaxKind.GotoDefaultStatement); matchedLabelSymbol = GetDefaultLabel(); } if ((object)matchedLabelSymbol == null) { if (!hasErrors) { // No matching case label/default label found var labelName = SyntaxFacts.GetText(node.CaseOrDefaultKeyword.Kind()); if (node.Kind() == SyntaxKind.GotoCaseStatement) { labelName += " " + gotoCaseExpressionConstant.Value?.ToString(); } labelName += ":"; diagnostics.Add(ErrorCode.ERR_LabelNotFound, node.Location, labelName); hasErrors = true; } } else { return new BoundGotoStatement(node, matchedLabelSymbol, gotoCaseExpressionOpt, null, hasErrors); } } return new BoundBadStatement( syntax: node, childBoundNodes: gotoCaseExpressionOpt != null ? ImmutableArray.Create<BoundNode>(gotoCaseExpressionOpt) : ImmutableArray<BoundNode>.Empty, hasErrors: true); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SwitchBinder : LocalScopeBinder { protected readonly SwitchStatementSyntax SwitchSyntax; private readonly GeneratedLabelSymbol _breakLabel; private BoundExpression _switchGoverningExpression; private BindingDiagnosticBag _switchGoverningDiagnostics; private SwitchBinder(Binder next, SwitchStatementSyntax switchSyntax) : base(next) { SwitchSyntax = switchSyntax; _breakLabel = new GeneratedLabelSymbol("break"); } protected bool PatternsEnabled => ((CSharpParseOptions)SwitchSyntax.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching) != false; protected BoundExpression SwitchGoverningExpression { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); Debug.Assert(_switchGoverningExpression != null); return _switchGoverningExpression; } } protected TypeSymbol SwitchGoverningType => SwitchGoverningExpression.Type; protected uint SwitchGoverningValEscape => GetValEscape(SwitchGoverningExpression, LocalScopeDepth); protected BindingDiagnosticBag SwitchGoverningDiagnostics { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); return _switchGoverningDiagnostics; } } private void EnsureSwitchGoverningExpressionAndDiagnosticsBound() { if (_switchGoverningExpression == null) { var switchGoverningDiagnostics = new BindingDiagnosticBag(); var boundSwitchExpression = BindSwitchGoverningExpression(switchGoverningDiagnostics); _switchGoverningDiagnostics = switchGoverningDiagnostics; Interlocked.CompareExchange(ref _switchGoverningExpression, boundSwitchExpression, null); } } // Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Default label(s) are indexed on a special DefaultKey object. // Invalid case labels with null constant value are indexed on the labelName. private Dictionary<object, SourceLabelSymbol> _lazySwitchLabelsMap; private static readonly object s_defaultKey = new object(); private Dictionary<object, SourceLabelSymbol> LabelsByValue { get { if (_lazySwitchLabelsMap == null && this.Labels.Length > 0) { _lazySwitchLabelsMap = BuildLabelsByValue(this.Labels); } return _lazySwitchLabelsMap; } } private static Dictionary<object, SourceLabelSymbol> BuildLabelsByValue(ImmutableArray<LabelSymbol> labels) { Debug.Assert(labels.Length > 0); var map = new Dictionary<object, SourceLabelSymbol>(labels.Length, new SwitchConstantValueHelper.SwitchLabelsComparer()); foreach (SourceLabelSymbol label in labels) { SyntaxKind labelKind = label.IdentifierNodeOrToken.Kind(); if (labelKind == SyntaxKind.IdentifierToken) { continue; } object key; var constantValue = label.SwitchCaseLabelConstant; if ((object)constantValue != null && !constantValue.IsBad) { // Case labels with a non-null constant value are indexed on their ConstantValue. key = KeyForConstant(constantValue); } else if (labelKind == SyntaxKind.DefaultSwitchLabel) { // Default label(s) are indexed on a special DefaultKey object. key = s_defaultKey; } else { // Invalid case labels with null constant value are indexed on the labelName. key = label.IdentifierNodeOrToken.AsNode(); } // If there is a duplicate label, ignore it. It will be reported when binding the switch label. if (!map.ContainsKey(key)) { map.Add(key, label); } } return map; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocals(section.Statements, GetBinder(section))); } return builder.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { var builder = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocalFunctions(section.Statements)); } return builder.ToImmutableAndFree(); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } internal override GeneratedLabelSymbol BreakLabel { get { return _breakLabel; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { // We bind the switch expression and the switch case label expressions so that the constant values can be // part of the label, but we do not report any diagnostics here. Diagnostics will be reported during binding. ArrayBuilder<LabelSymbol> labels = ArrayBuilder<LabelSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { // add switch case/default labels BuildSwitchLabels(section.Labels, GetBinder(section), labels, BindingDiagnosticBag.Discarded); // add regular labels from the statements in the switch section BuildLabels(section.Statements, ref labels); } return labels.ToImmutableAndFree(); } internal override bool IsLabelsScopeBinder { get { return true; } } private void BuildSwitchLabels(SyntaxList<SwitchLabelSyntax> labelsSyntax, Binder sectionBinder, ArrayBuilder<LabelSymbol> labels, BindingDiagnosticBag tempDiagnosticBag) { // add switch case/default labels foreach (var labelSyntax in labelsSyntax) { ConstantValue boundLabelConstantOpt = null; switch (labelSyntax.Kind()) { case SyntaxKind.CaseSwitchLabel: // compute the constant value to place in the label symbol var caseLabel = (CaseSwitchLabelSyntax)labelSyntax; Debug.Assert(caseLabel.Value != null); var boundLabelExpression = sectionBinder.BindTypeOrRValue(caseLabel.Value, tempDiagnosticBag); if (boundLabelExpression is BoundTypeExpression type) { // Nothing to do at this point. The label will be bound later. } else { _ = ConvertCaseExpression(labelSyntax, boundLabelExpression, sectionBinder, out boundLabelConstantOpt, tempDiagnosticBag); } break; case SyntaxKind.CasePatternSwitchLabel: // bind the pattern, to cause its pattern variables to be inferred if necessary var matchLabel = (CasePatternSwitchLabelSyntax)labelSyntax; _ = sectionBinder.BindPattern( matchLabel.Pattern, SwitchGoverningType, SwitchGoverningValEscape, permitDesignations: true, labelSyntax.HasErrors, tempDiagnosticBag); break; default: // No constant value break; } // Create the label symbol labels.Add(new SourceLabelSymbol((MethodSymbol)this.ContainingMemberOrLambda, labelSyntax, boundLabelConstantOpt)); } } protected BoundExpression ConvertCaseExpression(CSharpSyntaxNode node, BoundExpression caseExpression, Binder sectionBinder, out ConstantValue constantValueOpt, BindingDiagnosticBag diagnostics, bool isGotoCaseExpr = false) { bool hasErrors = false; if (isGotoCaseExpr) { // SPEC VIOLATION for Dev10 COMPATIBILITY: // Dev10 compiler violates the SPEC comment below: // "if the constant-expression is not implicitly convertible (§6.1) to // the governing type of the nearest enclosing switch statement, // a compile-time error occurs" // If there is no implicit conversion from gotoCaseExpression to switchGoverningType, // but there exists an explicit conversion, Dev10 compiler generates a warning "WRN_GotoCaseShouldConvert" // instead of an error. See test "CS0469_NoImplicitConversionWarning". CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(caseExpression, SwitchGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, caseExpression, SwitchGoverningType); hasErrors = true; } else if (!conversion.IsImplicit) { diagnostics.Add(ErrorCode.WRN_GotoCaseShouldConvert, node.Location, SwitchGoverningType); hasErrors = true; } caseExpression = CreateConversion(caseExpression, conversion, SwitchGoverningType, diagnostics); } return ConvertPatternExpression(SwitchGoverningType, node, caseExpression, out constantValueOpt, hasErrors, diagnostics); } private static readonly object s_nullKey = new object(); protected static object KeyForConstant(ConstantValue constantValue) { Debug.Assert((object)constantValue != null); return constantValue.IsNull ? s_nullKey : constantValue.Value; } protected SourceLabelSymbol FindMatchingSwitchCaseLabel(ConstantValue constantValue, CSharpSyntaxNode labelSyntax) { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Invalid case labels (with null constant value) are indexed on the label syntax. object key; if ((object)constantValue != null && !constantValue.IsBad) { key = KeyForConstant(constantValue); } else { key = labelSyntax; } return FindMatchingSwitchLabel(key); } private SourceLabelSymbol GetDefaultLabel() { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Default label(s) are indexed on a special DefaultKey object. return FindMatchingSwitchLabel(s_defaultKey); } private SourceLabelSymbol FindMatchingSwitchLabel(object key) { Debug.Assert(key != null); var labelsMap = LabelsByValue; if (labelsMap != null) { SourceLabelSymbol label; if (labelsMap.TryGetValue(key, out label)) { Debug.Assert((object)label != null); return label; } } return null; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return SwitchSyntax; } } # region "Switch statement binding methods" // Bind the switch expression private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { // We are at present inside the switch binder, but the switch expression is not // bound in the context of the switch binder; it's bound in the context of the // enclosing binder. For example: // // class C { // int x; // void M() { // switch(x) { // case 1: // int x; // // The "x" in "switch(x)" refers to this.x, not the local x that is in scope inside the switch block. Debug.Assert(ScopeDesignator == SwitchSyntax); ExpressionSyntax node = SwitchSyntax.Expression; var binder = this.GetBinder(node); Debug.Assert(binder != null); var switchGoverningExpression = binder.BindRValueWithoutTargetType(node, diagnostics); var switchGoverningType = switchGoverningExpression.Type; if ((object)switchGoverningType != null && !switchGoverningType.IsErrorType()) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise if exactly one user-defined implicit conversion (§6.4) exists from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types, then the result is the switch governing type // SPEC: 3) Otherwise (in C# 7 and later) the switch governing type is the type of the // SPEC: switch expression. if (switchGoverningType.IsValidV6SwitchGoverningType()) { // Condition (1) satisfied // Note: dev11 actually checks the stripped type, but nullable was introduced at the same // time, so it doesn't really matter. if (switchGoverningType.SpecialType == SpecialType.System_Boolean) { CheckFeatureAvailability(node, MessageID.IDS_FeatureSwitchOnBool, diagnostics); } return switchGoverningExpression; } else { TypeSymbol resultantGoverningType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(switchGoverningType, out resultantGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (conversion.IsValid) { // Condition (2) satisfied Debug.Assert(conversion.Kind == ConversionKind.ImplicitUserDefined); Debug.Assert(conversion.Method.IsUserDefinedConversion()); Debug.Assert(conversion.UserDefinedToConversion.IsIdentity); Debug.Assert(resultantGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); return binder.CreateConversion(node, switchGoverningExpression, conversion, isCast: false, conversionGroupOpt: null, resultantGoverningType, diagnostics); } else if (!switchGoverningType.IsVoidType()) { // Otherwise (3) satisfied if (!PatternsEnabled) { diagnostics.Add(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, node.Location); } return switchGoverningExpression; } else { switchGoverningType = CreateErrorType(switchGoverningType.Name); } } } if (!switchGoverningExpression.HasAnyErrors) { Debug.Assert((object)switchGoverningExpression.Type == null || switchGoverningExpression.Type.IsVoidType()); diagnostics.Add(ErrorCode.ERR_SwitchExpressionValueExpected, node.Location, switchGoverningExpression.Display); } return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(switchGoverningExpression), switchGoverningType ?? CreateErrorType()); } private Dictionary<SyntaxNode, LabelSymbol> _labelsByNode; protected Dictionary<SyntaxNode, LabelSymbol> LabelsByNode { get { if (_labelsByNode == null) { var result = new Dictionary<SyntaxNode, LabelSymbol>(); foreach (var label in Labels) { var node = ((SourceLabelSymbol)label).IdentifierNodeOrToken.AsNode(); if (node != null) { result.Add(node, label); } } _labelsByNode = result; } return _labelsByNode; } } internal BoundStatement BindGotoCaseOrDefault(GotoStatementSyntax node, Binder gotoBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement || node.Kind() == SyntaxKind.GotoDefaultStatement); BoundExpression gotoCaseExpressionOpt = null; // Prevent cascading diagnostics if (!node.HasErrors) { ConstantValue gotoCaseExpressionConstant = null; bool hasErrors = false; SourceLabelSymbol matchedLabelSymbol; // SPEC: If the goto case statement is not enclosed by a switch statement, if the constant-expression // SPEC: is not implicitly convertible (§6.1) to the governing type of the nearest enclosing switch statement, // SPEC: or if the nearest enclosing switch statement does not contain a case label with the given constant value, // SPEC: a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, or if the nearest enclosing // SPEC: switch statement does not contain a default label, a compile-time error occurs. if (node.Expression != null) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement); // Bind the goto case expression gotoCaseExpressionOpt = gotoBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); gotoCaseExpressionOpt = ConvertCaseExpression(node, gotoCaseExpressionOpt, gotoBinder, out gotoCaseExpressionConstant, diagnostics, isGotoCaseExpr: true); // Check for bind errors hasErrors = hasErrors || gotoCaseExpressionOpt.HasAnyErrors; if (!hasErrors && gotoCaseExpressionConstant == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, node.Location); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(gotoCaseExpressionOpt, diagnostics); // LabelSymbols for all the switch case labels are created by BuildLabels(). // Fetch the matching switch case label symbols matchedLabelSymbol = FindMatchingSwitchCaseLabel(gotoCaseExpressionConstant, node); } else { Debug.Assert(node.Kind() == SyntaxKind.GotoDefaultStatement); matchedLabelSymbol = GetDefaultLabel(); } if ((object)matchedLabelSymbol == null) { if (!hasErrors) { // No matching case label/default label found var labelName = SyntaxFacts.GetText(node.CaseOrDefaultKeyword.Kind()); if (node.Kind() == SyntaxKind.GotoCaseStatement) { labelName += " " + gotoCaseExpressionConstant.Value?.ToString(); } labelName += ":"; diagnostics.Add(ErrorCode.ERR_LabelNotFound, node.Location, labelName); hasErrors = true; } } else { return new BoundGotoStatement(node, matchedLabelSymbol, gotoCaseExpressionOpt, null, hasErrors); } } return new BoundBadStatement( syntax: node, childBoundNodes: gotoCaseExpressionOpt != null ? ImmutableArray.Create<BoundNode>(gotoCaseExpressionOpt) : ImmutableArray<BoundNode>.Empty, hasErrors: true); } #endregion } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/Core/Portable/Symbols/ISourceAssemblySymbolInternal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; namespace Microsoft.CodeAnalysis.Symbols { internal interface ISourceAssemblySymbolInternal : IAssemblySymbolInternal { AssemblyFlags AssemblyFlags { get; } /// <summary> /// The contents of the AssemblySignatureKeyAttribute /// </summary> string? SignatureKey { get; } AssemblyHashAlgorithm HashAlgorithm { get; } bool InternalsAreVisible { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; namespace Microsoft.CodeAnalysis.Symbols { internal interface ISourceAssemblySymbolInternal : IAssemblySymbolInternal { AssemblyFlags AssemblyFlags { get; } /// <summary> /// The contents of the AssemblySignatureKeyAttribute /// </summary> string? SignatureKey { get; } AssemblyHashAlgorithm HashAlgorithm { get; } bool InternalsAreVisible { get; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CommonFormattingHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class CommonFormattingHelpers { public static readonly Comparison<SuppressOperation> SuppressOperationComparer = (o1, o2) => { return o1.TextSpan.Start - o2.TextSpan.Start; }; public static readonly Comparison<IndentBlockOperation> IndentBlockOperationComparer = (o1, o2) => { // smaller one goes left var s = o1.TextSpan.Start - o2.TextSpan.Start; if (s != 0) { return s; } // bigger one goes left var e = o2.TextSpan.End - o1.TextSpan.End; if (e != 0) { return e; } return 0; }; public static IEnumerable<ValueTuple<SyntaxToken, SyntaxToken>> ConvertToTokenPairs(this SyntaxNode root, IList<TextSpan> spans) { Contract.ThrowIfNull(root); Contract.ThrowIfFalse(spans.Count > 0); if (spans.Count == 1) { // special case, if there is only one span, return right away yield return root.ConvertToTokenPair(spans[0]); yield break; } var previousOne = root.ConvertToTokenPair(spans[0]); // iterate through each spans and make sure each one doesn't overlap each other for (var i = 1; i < spans.Count; i++) { var currentOne = root.ConvertToTokenPair(spans[i]); if (currentOne.Item1.SpanStart <= previousOne.Item2.Span.End) { // oops, looks like two spans are overlapping each other. merge them previousOne = ValueTuple.Create(previousOne.Item1, previousOne.Item2.Span.End < currentOne.Item2.Span.End ? currentOne.Item2 : previousOne.Item2); continue; } // okay, looks like things are in good shape yield return previousOne; // move to next one previousOne = currentOne; } // give out the last one yield return previousOne; } public static ValueTuple<SyntaxToken, SyntaxToken> ConvertToTokenPair(this SyntaxNode root, TextSpan textSpan) { Contract.ThrowIfNull(root); Contract.ThrowIfTrue(textSpan.IsEmpty); var startToken = root.FindToken(textSpan.Start); // empty token, get previous non-zero length token if (startToken.IsMissing) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // span is on leading trivia if (textSpan.Start < startToken.SpanStart) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // adjust position where we try to search end token var endToken = (root.FullSpan.End <= textSpan.End) ? root.GetLastToken(includeZeroWidth: true) : root.FindToken(textSpan.End); // empty token, get next token if (endToken.IsMissing) { endToken = endToken.GetNextToken(); } // span is on trailing trivia if (endToken.Span.End < textSpan.End) { endToken = endToken.GetNextToken(); } // make sure tokens are not SyntaxKind.None startToken = (startToken.RawKind != 0) ? startToken : root.GetFirstToken(includeZeroWidth: true); endToken = (endToken.RawKind != 0) ? endToken : root.GetLastToken(includeZeroWidth: true); // token is in right order Contract.ThrowIfFalse(startToken.Equals(endToken) || startToken.Span.End <= endToken.SpanStart); return ValueTuple.Create(startToken, endToken); } public static bool IsInvalidTokenRange(this SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { // given token must be token exist excluding EndOfFile token. if (startToken.RawKind == 0 || endToken.RawKind == 0) { return true; } if (startToken.Equals(endToken)) { return false; } // regular case. // start token can't be end of file token and start token must be before end token if it's not the same token. return root.FullSpan.End == startToken.SpanStart || startToken.FullSpan.End > endToken.FullSpan.Start; } public static int GetTokenColumn(this SyntaxTree tree, SyntaxToken token, int tabSize) { Contract.ThrowIfNull(tree); Contract.ThrowIfTrue(token.RawKind == 0); var startPosition = token.SpanStart; var line = tree.GetText().Lines.GetLineFromPosition(startPosition); return line.GetColumnFromLineOffset(startPosition - line.Start, tabSize); } public static string GetText(this SourceText text, SyntaxToken token1, SyntaxToken token2) => (token1.RawKind == 0) ? text.ToString(TextSpan.FromBounds(0, token2.SpanStart)) : text.ToString(TextSpan.FromBounds(token1.Span.End, token2.SpanStart)); public static string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { var builder = new StringBuilder(); AppendTextBetween(token1, token2, builder); return builder.ToString(); } public static void AppendTextBetween(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { Contract.ThrowIfTrue(token1.RawKind == 0 && token2.RawKind == 0); Contract.ThrowIfTrue(token1.Equals(token2)); if (token1.RawKind == 0) { AppendLeadingTriviaText(token2, builder); return; } if (token2.RawKind == 0) { AppendTrailingTriviaText(token1, builder); return; } if (token1.FullSpan.End == token2.FullSpan.Start) { AppendTextBetweenTwoAdjacentTokens(token1, token2, builder); return; } AppendTrailingTriviaText(token1, builder); for (var token = token1.GetNextToken(includeZeroWidth: true); token.FullSpan.End <= token2.FullSpan.Start; token = token.GetNextToken(includeZeroWidth: true)) { builder.Append(token.ToFullString()); } AppendPartialLeadingTriviaText(token2, builder, token1.TrailingTrivia.FullSpan.End); } private static void AppendTextBetweenTwoAdjacentTokens(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { AppendTrailingTriviaText(token1, builder); AppendLeadingTriviaText(token2, builder); } private static void AppendLeadingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// If the token1 is expected to be part of the leading trivia of the token2 then the trivia /// before the token1FullSpanEnd, which the fullspan end of the token1 should be ignored /// </summary> private static void AppendPartialLeadingTriviaText(SyntaxToken token, StringBuilder builder, int token1FullSpanEnd) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { if (trivia.FullSpan.End <= token1FullSpanEnd) { continue; } builder.Append(trivia.ToFullString()); } } private static void AppendTrailingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasTrailingTrivia) { return; } foreach (var trivia in token.TrailingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// this will create a span that includes its trailing trivia of its previous token and leading trivia of its next token /// for example, for code such as "class A { int ...", if given tokens are "A" and "{", this will return span [] of "class[ A { ]int ..." /// which included trailing trivia of "class" which is previous token of "A", and leading trivia of "int" which is next token of "{" /// </summary> public static TextSpan GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(SyntaxToken startToken, SyntaxToken endToken) { // most of cases we can just ask previous and next token to create the span, but in some corner cases such as omitted token case, // those navigation function doesn't work, so we have to explore the tree ourselves to create correct span var startPosition = GetStartPositionOfSpan(startToken); var endPosition = GetEndPositionOfSpan(endToken); return TextSpan.FromBounds(startPosition, endPosition); } private static int GetEndPositionOfSpan(SyntaxToken token) { var nextToken = token.GetNextToken(); if (nextToken.RawKind != 0) { return nextToken.SpanStart; } var backwardPosition = token.FullSpan.End; var parentNode = GetParentThatContainsGivenSpan(token.Parent, backwardPosition, forward: false); if (parentNode == null) { // reached the end of tree return token.FullSpan.End; } Contract.ThrowIfFalse(backwardPosition < parentNode.FullSpan.End); nextToken = parentNode.FindToken(backwardPosition + 1); Contract.ThrowIfTrue(nextToken.RawKind == 0); return nextToken.SpanStart; } public static int GetStartPositionOfSpan(SyntaxToken token) { var previousToken = token.GetPreviousToken(); if (previousToken.RawKind != 0) { return previousToken.Span.End; } // first token in the tree var forwardPosition = token.FullSpan.Start; if (forwardPosition <= 0) { return 0; } var parentNode = GetParentThatContainsGivenSpan(token.Parent, forwardPosition, forward: true); Contract.ThrowIfNull(parentNode); Contract.ThrowIfFalse(parentNode.FullSpan.Start < forwardPosition); previousToken = parentNode.FindToken(forwardPosition + 1); Contract.ThrowIfTrue(previousToken.RawKind == 0); return previousToken.Span.End; } private static SyntaxNode? GetParentThatContainsGivenSpan(SyntaxNode? node, int position, bool forward) { while (node != null) { var fullSpan = node.FullSpan; if (forward) { if (fullSpan.Start < position) { return node; } } else { if (position > fullSpan.End) { return node; } } node = node.Parent; } return null; } public static bool HasAnyWhitespaceElasticTrivia(SyntaxToken previousToken, SyntaxToken currentToken) { if ((!previousToken.ContainsAnnotations && !currentToken.ContainsAnnotations) || (!previousToken.HasTrailingTrivia && !currentToken.HasLeadingTrivia)) { return false; } return previousToken.TrailingTrivia.HasAnyWhitespaceElasticTrivia() || currentToken.LeadingTrivia.HasAnyWhitespaceElasticTrivia(); } public static bool IsNull<T>(T t) where T : class => t == null; public static bool IsNotNull<T>(T t) where T : class => !IsNull(t); public static TextSpan GetFormattingSpan(SyntaxNode root, TextSpan span) { Contract.ThrowIfNull(root); var startToken = root.FindToken(span.Start).GetPreviousToken(); var endToken = root.FindTokenFromEnd(span.End).GetNextToken(); var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class CommonFormattingHelpers { public static readonly Comparison<SuppressOperation> SuppressOperationComparer = (o1, o2) => { return o1.TextSpan.Start - o2.TextSpan.Start; }; public static readonly Comparison<IndentBlockOperation> IndentBlockOperationComparer = (o1, o2) => { // smaller one goes left var s = o1.TextSpan.Start - o2.TextSpan.Start; if (s != 0) { return s; } // bigger one goes left var e = o2.TextSpan.End - o1.TextSpan.End; if (e != 0) { return e; } return 0; }; public static IEnumerable<ValueTuple<SyntaxToken, SyntaxToken>> ConvertToTokenPairs(this SyntaxNode root, IList<TextSpan> spans) { Contract.ThrowIfNull(root); Contract.ThrowIfFalse(spans.Count > 0); if (spans.Count == 1) { // special case, if there is only one span, return right away yield return root.ConvertToTokenPair(spans[0]); yield break; } var previousOne = root.ConvertToTokenPair(spans[0]); // iterate through each spans and make sure each one doesn't overlap each other for (var i = 1; i < spans.Count; i++) { var currentOne = root.ConvertToTokenPair(spans[i]); if (currentOne.Item1.SpanStart <= previousOne.Item2.Span.End) { // oops, looks like two spans are overlapping each other. merge them previousOne = ValueTuple.Create(previousOne.Item1, previousOne.Item2.Span.End < currentOne.Item2.Span.End ? currentOne.Item2 : previousOne.Item2); continue; } // okay, looks like things are in good shape yield return previousOne; // move to next one previousOne = currentOne; } // give out the last one yield return previousOne; } public static ValueTuple<SyntaxToken, SyntaxToken> ConvertToTokenPair(this SyntaxNode root, TextSpan textSpan) { Contract.ThrowIfNull(root); Contract.ThrowIfTrue(textSpan.IsEmpty); var startToken = root.FindToken(textSpan.Start); // empty token, get previous non-zero length token if (startToken.IsMissing) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // span is on leading trivia if (textSpan.Start < startToken.SpanStart) { // if there is no previous token, startToken will be set to SyntaxKind.None startToken = startToken.GetPreviousToken(); } // adjust position where we try to search end token var endToken = (root.FullSpan.End <= textSpan.End) ? root.GetLastToken(includeZeroWidth: true) : root.FindToken(textSpan.End); // empty token, get next token if (endToken.IsMissing) { endToken = endToken.GetNextToken(); } // span is on trailing trivia if (endToken.Span.End < textSpan.End) { endToken = endToken.GetNextToken(); } // make sure tokens are not SyntaxKind.None startToken = (startToken.RawKind != 0) ? startToken : root.GetFirstToken(includeZeroWidth: true); endToken = (endToken.RawKind != 0) ? endToken : root.GetLastToken(includeZeroWidth: true); // token is in right order Contract.ThrowIfFalse(startToken.Equals(endToken) || startToken.Span.End <= endToken.SpanStart); return ValueTuple.Create(startToken, endToken); } public static bool IsInvalidTokenRange(this SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken) { // given token must be token exist excluding EndOfFile token. if (startToken.RawKind == 0 || endToken.RawKind == 0) { return true; } if (startToken.Equals(endToken)) { return false; } // regular case. // start token can't be end of file token and start token must be before end token if it's not the same token. return root.FullSpan.End == startToken.SpanStart || startToken.FullSpan.End > endToken.FullSpan.Start; } public static int GetTokenColumn(this SyntaxTree tree, SyntaxToken token, int tabSize) { Contract.ThrowIfNull(tree); Contract.ThrowIfTrue(token.RawKind == 0); var startPosition = token.SpanStart; var line = tree.GetText().Lines.GetLineFromPosition(startPosition); return line.GetColumnFromLineOffset(startPosition - line.Start, tabSize); } public static string GetText(this SourceText text, SyntaxToken token1, SyntaxToken token2) => (token1.RawKind == 0) ? text.ToString(TextSpan.FromBounds(0, token2.SpanStart)) : text.ToString(TextSpan.FromBounds(token1.Span.End, token2.SpanStart)); public static string GetTextBetween(SyntaxToken token1, SyntaxToken token2) { var builder = new StringBuilder(); AppendTextBetween(token1, token2, builder); return builder.ToString(); } public static void AppendTextBetween(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { Contract.ThrowIfTrue(token1.RawKind == 0 && token2.RawKind == 0); Contract.ThrowIfTrue(token1.Equals(token2)); if (token1.RawKind == 0) { AppendLeadingTriviaText(token2, builder); return; } if (token2.RawKind == 0) { AppendTrailingTriviaText(token1, builder); return; } if (token1.FullSpan.End == token2.FullSpan.Start) { AppendTextBetweenTwoAdjacentTokens(token1, token2, builder); return; } AppendTrailingTriviaText(token1, builder); for (var token = token1.GetNextToken(includeZeroWidth: true); token.FullSpan.End <= token2.FullSpan.Start; token = token.GetNextToken(includeZeroWidth: true)) { builder.Append(token.ToFullString()); } AppendPartialLeadingTriviaText(token2, builder, token1.TrailingTrivia.FullSpan.End); } private static void AppendTextBetweenTwoAdjacentTokens(SyntaxToken token1, SyntaxToken token2, StringBuilder builder) { AppendTrailingTriviaText(token1, builder); AppendLeadingTriviaText(token2, builder); } private static void AppendLeadingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// If the token1 is expected to be part of the leading trivia of the token2 then the trivia /// before the token1FullSpanEnd, which the fullspan end of the token1 should be ignored /// </summary> private static void AppendPartialLeadingTriviaText(SyntaxToken token, StringBuilder builder, int token1FullSpanEnd) { if (!token.HasLeadingTrivia) { return; } foreach (var trivia in token.LeadingTrivia) { if (trivia.FullSpan.End <= token1FullSpanEnd) { continue; } builder.Append(trivia.ToFullString()); } } private static void AppendTrailingTriviaText(SyntaxToken token, StringBuilder builder) { if (!token.HasTrailingTrivia) { return; } foreach (var trivia in token.TrailingTrivia) { builder.Append(trivia.ToFullString()); } } /// <summary> /// this will create a span that includes its trailing trivia of its previous token and leading trivia of its next token /// for example, for code such as "class A { int ...", if given tokens are "A" and "{", this will return span [] of "class[ A { ]int ..." /// which included trailing trivia of "class" which is previous token of "A", and leading trivia of "int" which is next token of "{" /// </summary> public static TextSpan GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(SyntaxToken startToken, SyntaxToken endToken) { // most of cases we can just ask previous and next token to create the span, but in some corner cases such as omitted token case, // those navigation function doesn't work, so we have to explore the tree ourselves to create correct span var startPosition = GetStartPositionOfSpan(startToken); var endPosition = GetEndPositionOfSpan(endToken); return TextSpan.FromBounds(startPosition, endPosition); } private static int GetEndPositionOfSpan(SyntaxToken token) { var nextToken = token.GetNextToken(); if (nextToken.RawKind != 0) { return nextToken.SpanStart; } var backwardPosition = token.FullSpan.End; var parentNode = GetParentThatContainsGivenSpan(token.Parent, backwardPosition, forward: false); if (parentNode == null) { // reached the end of tree return token.FullSpan.End; } Contract.ThrowIfFalse(backwardPosition < parentNode.FullSpan.End); nextToken = parentNode.FindToken(backwardPosition + 1); Contract.ThrowIfTrue(nextToken.RawKind == 0); return nextToken.SpanStart; } public static int GetStartPositionOfSpan(SyntaxToken token) { var previousToken = token.GetPreviousToken(); if (previousToken.RawKind != 0) { return previousToken.Span.End; } // first token in the tree var forwardPosition = token.FullSpan.Start; if (forwardPosition <= 0) { return 0; } var parentNode = GetParentThatContainsGivenSpan(token.Parent, forwardPosition, forward: true); Contract.ThrowIfNull(parentNode); Contract.ThrowIfFalse(parentNode.FullSpan.Start < forwardPosition); previousToken = parentNode.FindToken(forwardPosition + 1); Contract.ThrowIfTrue(previousToken.RawKind == 0); return previousToken.Span.End; } private static SyntaxNode? GetParentThatContainsGivenSpan(SyntaxNode? node, int position, bool forward) { while (node != null) { var fullSpan = node.FullSpan; if (forward) { if (fullSpan.Start < position) { return node; } } else { if (position > fullSpan.End) { return node; } } node = node.Parent; } return null; } public static bool HasAnyWhitespaceElasticTrivia(SyntaxToken previousToken, SyntaxToken currentToken) { if ((!previousToken.ContainsAnnotations && !currentToken.ContainsAnnotations) || (!previousToken.HasTrailingTrivia && !currentToken.HasLeadingTrivia)) { return false; } return previousToken.TrailingTrivia.HasAnyWhitespaceElasticTrivia() || currentToken.LeadingTrivia.HasAnyWhitespaceElasticTrivia(); } public static bool IsNull<T>(T t) where T : class => t == null; public static bool IsNotNull<T>(T t) where T : class => !IsNull(t); public static TextSpan GetFormattingSpan(SyntaxNode root, TextSpan span) { Contract.ThrowIfNull(root); var startToken = root.FindToken(span.Start).GetPreviousToken(); var endToken = root.FindTokenFromEnd(span.End).GetNextToken(); var startPosition = startToken.SpanStart; var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End; return TextSpan.FromBounds(startPosition, endPosition); } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/CSharp/Portable/Syntax/WhileStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class WhileStatementSyntax { public WhileStatementSyntax Update(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AttributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static WhileStatementSyntax WhileStatement(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) => WhileStatement(attributeLists: default, whileKeyword, openParenToken, condition, closeParenToken, statement); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class WhileStatementSyntax { public WhileStatementSyntax Update(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AttributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static WhileStatementSyntax WhileStatement(SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) => WhileStatement(attributeLists: default, whileKeyword, openParenToken, condition, closeParenToken, statement); } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ElseKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ElseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ElseKeywordRecommender() : base(SyntaxKind.ElseKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsPreProcessorKeywordContext) { return true; } var token = context.TargetToken; // We have to consider all ancestor if statements of the last token until we find a match for this 'else': // while (true) // if (true) // while (true) // if (true) // Console.WriteLine(); // else // Console.WriteLine(); // $$ foreach (var ifStatement in token.GetAncestors<IfStatementSyntax>()) { // If there's a missing token at the end of the statement, it's incomplete and we do not offer 'else'. // context.TargetToken does not include zero width so in that case these will never be equal. if (ifStatement.Statement.GetLastToken(includeZeroWidth: true) == token) { return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ElseKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ElseKeywordRecommender() : base(SyntaxKind.ElseKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (context.IsPreProcessorKeywordContext) { return true; } var token = context.TargetToken; // We have to consider all ancestor if statements of the last token until we find a match for this 'else': // while (true) // if (true) // while (true) // if (true) // Console.WriteLine(); // else // Console.WriteLine(); // $$ foreach (var ifStatement in token.GetAncestors<IfStatementSyntax>()) { // If there's a missing token at the end of the statement, it's incomplete and we do not offer 'else'. // context.TargetToken does not include zero width so in that case these will never be equal. if (ifStatement.Statement.GetLastToken(includeZeroWidth: true) == token) { return true; } } return false; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ContinueKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ContinueKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ContinueKeywordRecommender() : base(SyntaxKind.ContinueKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (!context.IsStatementContext) { return false; } // allowed if we're inside a loop construct. var leaf = context.LeftToken; foreach (var v in leaf.GetAncestors<SyntaxNode>()) { if (v.IsAnyLambdaOrAnonymousMethod()) { // if we hit a lambda while walking up, then we can't // 'continue' any outer loops. return false; } if (v.IsContinuableConstruct()) { return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ContinueKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ContinueKeywordRecommender() : base(SyntaxKind.ContinueKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { if (!context.IsStatementContext) { return false; } // allowed if we're inside a loop construct. var leaf = context.LeftToken; foreach (var v in leaf.GetAncestors<SyntaxNode>()) { if (v.IsAnyLambdaOrAnonymousMethod()) { // if we hit a lambda while walking up, then we can't // 'continue' any outer loops. return false; } if (v.IsContinuableConstruct()) { return true; } } return false; } } }
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/Compilers/VisualBasic/Test/Semantic/Semantics/BinaryOperatorsTestSource5.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict Off Imports System Module Module1 Sub Main() PrintResult("False + False", False + False) PrintResult("False + True", False + True) PrintResult("False + System.SByte.MinValue", False + System.SByte.MinValue) PrintResult("False + System.Byte.MaxValue", False + System.Byte.MaxValue) PrintResult("False + -3S", False + -3S) PrintResult("False + 24US", False + 24US) PrintResult("False + -5I", False + -5I) PrintResult("False + 26UI", False + 26UI) PrintResult("False + -7L", False + -7L) PrintResult("False + 28UL", False + 28UL) PrintResult("False + -9D", False + -9D) PrintResult("False + 10.0F", False + 10.0F) PrintResult("False + -11.0R", False + -11.0R) PrintResult("False + ""12""", False + "12") PrintResult("False + TypeCode.Double", False + TypeCode.Double) PrintResult("True + False", True + False) PrintResult("True + True", True + True) PrintResult("True + System.SByte.MaxValue", True + System.SByte.MaxValue) PrintResult("True + System.Byte.MaxValue", True + System.Byte.MaxValue) PrintResult("True + -3S", True + -3S) PrintResult("True + 24US", True + 24US) PrintResult("True + -5I", True + -5I) PrintResult("True + 26UI", True + 26UI) PrintResult("True + -7L", True + -7L) PrintResult("True + 28UL", True + 28UL) PrintResult("True + -9D", True + -9D) PrintResult("True + 10.0F", True + 10.0F) PrintResult("True + -11.0R", True + -11.0R) PrintResult("True + ""12""", True + "12") PrintResult("True + TypeCode.Double", True + TypeCode.Double) PrintResult("System.SByte.MinValue + False", System.SByte.MinValue + False) PrintResult("System.SByte.MaxValue + True", System.SByte.MaxValue + True) PrintResult("System.SByte.MinValue + System.SByte.MaxValue", System.SByte.MinValue + System.SByte.MaxValue) PrintResult("System.SByte.MinValue + System.Byte.MaxValue", System.SByte.MinValue + System.Byte.MaxValue) PrintResult("System.SByte.MinValue + -3S", System.SByte.MinValue + -3S) PrintResult("System.SByte.MinValue + 24US", System.SByte.MinValue + 24US) PrintResult("System.SByte.MinValue + -5I", System.SByte.MinValue + -5I) PrintResult("System.SByte.MinValue + 26UI", System.SByte.MinValue + 26UI) PrintResult("System.SByte.MinValue + -7L", System.SByte.MinValue + -7L) PrintResult("System.SByte.MinValue + 28UL", System.SByte.MinValue + 28UL) PrintResult("System.SByte.MinValue + -9D", System.SByte.MinValue + -9D) PrintResult("System.SByte.MinValue + 10.0F", System.SByte.MinValue + 10.0F) PrintResult("System.SByte.MinValue + -11.0R", System.SByte.MinValue + -11.0R) PrintResult("System.SByte.MinValue + ""12""", System.SByte.MinValue + "12") PrintResult("System.SByte.MinValue + TypeCode.Double", System.SByte.MinValue + TypeCode.Double) PrintResult("System.Byte.MaxValue + False", System.Byte.MaxValue + False) PrintResult("System.Byte.MaxValue + True", System.Byte.MaxValue + True) PrintResult("System.Byte.MaxValue + System.SByte.MinValue", System.Byte.MaxValue + System.SByte.MinValue) PrintResult("System.Byte.MaxValue + System.Byte.MinValue", System.Byte.MaxValue + System.Byte.MinValue) PrintResult("System.Byte.MaxValue + -3S", System.Byte.MaxValue + -3S) PrintResult("System.Byte.MaxValue + 24US", System.Byte.MaxValue + 24US) PrintResult("System.Byte.MaxValue + -5I", System.Byte.MaxValue + -5I) PrintResult("System.Byte.MaxValue + 26UI", System.Byte.MaxValue + 26UI) PrintResult("System.Byte.MaxValue + -7L", System.Byte.MaxValue + -7L) PrintResult("System.Byte.MaxValue + 28UL", System.Byte.MaxValue + 28UL) PrintResult("System.Byte.MaxValue + -9D", System.Byte.MaxValue + -9D) PrintResult("System.Byte.MaxValue + 10.0F", System.Byte.MaxValue + 10.0F) PrintResult("System.Byte.MaxValue + -11.0R", System.Byte.MaxValue + -11.0R) PrintResult("System.Byte.MaxValue + ""12""", System.Byte.MaxValue + "12") PrintResult("System.Byte.MaxValue + TypeCode.Double", System.Byte.MaxValue + TypeCode.Double) PrintResult("-3S + False", -3S + False) PrintResult("-3S + True", -3S + True) PrintResult("-3S + System.SByte.MinValue", -3S + System.SByte.MinValue) PrintResult("-3S + System.Byte.MaxValue", -3S + System.Byte.MaxValue) PrintResult("-3S + -3S", -3S + -3S) PrintResult("-3S + 24US", -3S + 24US) PrintResult("-3S + -5I", -3S + -5I) PrintResult("-3S + 26UI", -3S + 26UI) PrintResult("-3S + -7L", -3S + -7L) PrintResult("-3S + 28UL", -3S + 28UL) PrintResult("-3S + -9D", -3S + -9D) PrintResult("-3S + 10.0F", -3S + 10.0F) PrintResult("-3S + -11.0R", -3S + -11.0R) PrintResult("-3S + ""12""", -3S + "12") PrintResult("-3S + TypeCode.Double", -3S + TypeCode.Double) PrintResult("24US + False", 24US + False) PrintResult("24US + True", 24US + True) PrintResult("24US + System.SByte.MinValue", 24US + System.SByte.MinValue) PrintResult("24US + System.Byte.MaxValue", 24US + System.Byte.MaxValue) PrintResult("24US + -3S", 24US + -3S) PrintResult("24US + 24US", 24US + 24US) PrintResult("24US + -5I", 24US + -5I) PrintResult("24US + 26UI", 24US + 26UI) PrintResult("24US + -7L", 24US + -7L) PrintResult("24US + 28UL", 24US + 28UL) PrintResult("24US + -9D", 24US + -9D) PrintResult("24US + 10.0F", 24US + 10.0F) PrintResult("24US + -11.0R", 24US + -11.0R) PrintResult("24US + ""12""", 24US + "12") PrintResult("24US + TypeCode.Double", 24US + TypeCode.Double) PrintResult("-5I + False", -5I + False) PrintResult("-5I + True", -5I + True) PrintResult("-5I + System.SByte.MinValue", -5I + System.SByte.MinValue) PrintResult("-5I + System.Byte.MaxValue", -5I + System.Byte.MaxValue) PrintResult("-5I + -3S", -5I + -3S) PrintResult("-5I + 24US", -5I + 24US) PrintResult("-5I + -5I", -5I + -5I) PrintResult("-5I + 26UI", -5I + 26UI) PrintResult("-5I + -7L", -5I + -7L) PrintResult("-5I + 28UL", -5I + 28UL) PrintResult("-5I + -9D", -5I + -9D) PrintResult("-5I + 10.0F", -5I + 10.0F) PrintResult("-5I + -11.0R", -5I + -11.0R) PrintResult("-5I + ""12""", -5I + "12") PrintResult("-5I + TypeCode.Double", -5I + TypeCode.Double) PrintResult("26UI + False", 26UI + False) PrintResult("26UI + True", 26UI + True) PrintResult("26UI + System.SByte.MinValue", 26UI + System.SByte.MinValue) PrintResult("26UI + System.Byte.MaxValue", 26UI + System.Byte.MaxValue) PrintResult("26UI + -3S", 26UI + -3S) PrintResult("26UI + 24US", 26UI + 24US) PrintResult("26UI + -5I", 26UI + -5I) PrintResult("26UI + 26UI", 26UI + 26UI) PrintResult("26UI + -7L", 26UI + -7L) PrintResult("26UI + 28UL", 26UI + 28UL) PrintResult("26UI + -9D", 26UI + -9D) PrintResult("26UI + 10.0F", 26UI + 10.0F) PrintResult("26UI + -11.0R", 26UI + -11.0R) PrintResult("26UI + ""12""", 26UI + "12") PrintResult("26UI + TypeCode.Double", 26UI + TypeCode.Double) PrintResult("-7L + False", -7L + False) PrintResult("-7L + True", -7L + True) PrintResult("-7L + System.SByte.MinValue", -7L + System.SByte.MinValue) PrintResult("-7L + System.Byte.MaxValue", -7L + System.Byte.MaxValue) PrintResult("-7L + -3S", -7L + -3S) PrintResult("-7L + 24US", -7L + 24US) PrintResult("-7L + -5I", -7L + -5I) PrintResult("-7L + 26UI", -7L + 26UI) PrintResult("-7L + -7L", -7L + -7L) PrintResult("-7L + 28UL", -7L + 28UL) PrintResult("-7L + -9D", -7L + -9D) PrintResult("-7L + 10.0F", -7L + 10.0F) PrintResult("-7L + -11.0R", -7L + -11.0R) PrintResult("-7L + ""12""", -7L + "12") PrintResult("-7L + TypeCode.Double", -7L + TypeCode.Double) PrintResult("28UL + False", 28UL + False) PrintResult("28UL + True", 28UL + True) PrintResult("28UL + System.SByte.MinValue", 28UL + System.SByte.MinValue) PrintResult("28UL + System.Byte.MaxValue", 28UL + System.Byte.MaxValue) PrintResult("28UL + -3S", 28UL + -3S) PrintResult("28UL + 24US", 28UL + 24US) PrintResult("28UL + -5I", 28UL + -5I) PrintResult("28UL + 26UI", 28UL + 26UI) PrintResult("28UL + -7L", 28UL + -7L) PrintResult("28UL + 28UL", 28UL + 28UL) PrintResult("28UL + -9D", 28UL + -9D) PrintResult("28UL + 10.0F", 28UL + 10.0F) PrintResult("28UL + -11.0R", 28UL + -11.0R) PrintResult("28UL + ""12""", 28UL + "12") PrintResult("28UL + TypeCode.Double", 28UL + TypeCode.Double) PrintResult("-9D + False", -9D + False) PrintResult("-9D + True", -9D + True) PrintResult("-9D + System.SByte.MinValue", -9D + System.SByte.MinValue) PrintResult("-9D + System.Byte.MaxValue", -9D + System.Byte.MaxValue) PrintResult("-9D + -3S", -9D + -3S) PrintResult("-9D + 24US", -9D + 24US) PrintResult("-9D + -5I", -9D + -5I) PrintResult("-9D + 26UI", -9D + 26UI) PrintResult("-9D + -7L", -9D + -7L) PrintResult("-9D + 28UL", -9D + 28UL) PrintResult("-9D + -9D", -9D + -9D) PrintResult("-9D + 10.0F", -9D + 10.0F) PrintResult("-9D + -11.0R", -9D + -11.0R) PrintResult("-9D + ""12""", -9D + "12") PrintResult("-9D + TypeCode.Double", -9D + TypeCode.Double) PrintResult("10.0F + False", 10.0F + False) PrintResult("10.0F + True", 10.0F + True) PrintResult("10.0F + System.SByte.MinValue", 10.0F + System.SByte.MinValue) PrintResult("10.0F + System.Byte.MaxValue", 10.0F + System.Byte.MaxValue) PrintResult("10.0F + -3S", 10.0F + -3S) PrintResult("10.0F + 24US", 10.0F + 24US) PrintResult("10.0F + -5I", 10.0F + -5I) PrintResult("10.0F + 26UI", 10.0F + 26UI) PrintResult("10.0F + -7L", 10.0F + -7L) PrintResult("10.0F + 28UL", 10.0F + 28UL) PrintResult("10.0F + -9D", 10.0F + -9D) PrintResult("10.0F + 10.0F", 10.0F + 10.0F) PrintResult("10.0F + -11.0R", 10.0F + -11.0R) PrintResult("10.0F + ""12""", 10.0F + "12") PrintResult("10.0F + TypeCode.Double", 10.0F + TypeCode.Double) PrintResult("-11.0R + False", -11.0R + False) PrintResult("-11.0R + True", -11.0R + True) PrintResult("-11.0R + System.SByte.MinValue", -11.0R + System.SByte.MinValue) PrintResult("-11.0R + System.Byte.MaxValue", -11.0R + System.Byte.MaxValue) PrintResult("-11.0R + -3S", -11.0R + -3S) PrintResult("-11.0R + 24US", -11.0R + 24US) PrintResult("-11.0R + -5I", -11.0R + -5I) PrintResult("-11.0R + 26UI", -11.0R + 26UI) PrintResult("-11.0R + -7L", -11.0R + -7L) PrintResult("-11.0R + 28UL", -11.0R + 28UL) PrintResult("-11.0R + -9D", -11.0R + -9D) PrintResult("-11.0R + 10.0F", -11.0R + 10.0F) PrintResult("-11.0R + -11.0R", -11.0R + -11.0R) PrintResult("-11.0R + ""12""", -11.0R + "12") PrintResult("-11.0R + TypeCode.Double", -11.0R + TypeCode.Double) PrintResult("""12"" + False", "12" + False) PrintResult("""12"" + True", "12" + True) PrintResult("""12"" + System.SByte.MinValue", "12" + System.SByte.MinValue) PrintResult("""12"" + System.Byte.MaxValue", "12" + System.Byte.MaxValue) PrintResult("""12"" + -3S", "12" + -3S) PrintResult("""12"" + 24US", "12" + 24US) PrintResult("""12"" + -5I", "12" + -5I) PrintResult("""12"" + 26UI", "12" + 26UI) PrintResult("""12"" + -7L", "12" + -7L) PrintResult("""12"" + 28UL", "12" + 28UL) PrintResult("""12"" + -9D", "12" + -9D) PrintResult("""12"" + 10.0F", "12" + 10.0F) PrintResult("""12"" + -11.0R", "12" + -11.0R) PrintResult("""12"" + ""12""", "12" + "12") PrintResult("""12"" + TypeCode.Double", "12" + TypeCode.Double) PrintResult("TypeCode.Double + False", TypeCode.Double + False) PrintResult("TypeCode.Double + True", TypeCode.Double + True) PrintResult("TypeCode.Double + System.SByte.MinValue", TypeCode.Double + System.SByte.MinValue) PrintResult("TypeCode.Double + System.Byte.MaxValue", TypeCode.Double + System.Byte.MaxValue) PrintResult("TypeCode.Double + -3S", TypeCode.Double + -3S) PrintResult("TypeCode.Double + 24US", TypeCode.Double + 24US) PrintResult("TypeCode.Double + -5I", TypeCode.Double + -5I) PrintResult("TypeCode.Double + 26UI", TypeCode.Double + 26UI) PrintResult("TypeCode.Double + -7L", TypeCode.Double + -7L) PrintResult("TypeCode.Double + 28UL", TypeCode.Double + 28UL) PrintResult("TypeCode.Double + -9D", TypeCode.Double + -9D) PrintResult("TypeCode.Double + 10.0F", TypeCode.Double + 10.0F) PrintResult("TypeCode.Double + -11.0R", TypeCode.Double + -11.0R) PrintResult("TypeCode.Double + ""12""", TypeCode.Double + "12") PrintResult("TypeCode.Double + TypeCode.Double", TypeCode.Double + TypeCode.Double) PrintResult("False - False", False - False) PrintResult("False - True", False - True) PrintResult("False - System.SByte.MaxValue", False - System.SByte.MaxValue) PrintResult("False - System.Byte.MaxValue", False - System.Byte.MaxValue) PrintResult("False - -3S", False - -3S) PrintResult("False - 24US", False - 24US) PrintResult("False - -5I", False - -5I) PrintResult("False - 26UI", False - 26UI) PrintResult("False - -7L", False - -7L) PrintResult("False - 28UL", False - 28UL) PrintResult("False - -9D", False - -9D) PrintResult("False - 10.0F", False - 10.0F) PrintResult("False - -11.0R", False - -11.0R) PrintResult("False - ""12""", False - "12") PrintResult("False - TypeCode.Double", False - TypeCode.Double) PrintResult("True - False", True - False) PrintResult("True - True", True - True) PrintResult("True - System.SByte.MinValue", True - System.SByte.MinValue) PrintResult("True - System.Byte.MaxValue", True - System.Byte.MaxValue) PrintResult("True - -3S", True - -3S) PrintResult("True - 24US", True - 24US) PrintResult("True - -5I", True - -5I) PrintResult("True - 26UI", True - 26UI) PrintResult("True - -7L", True - -7L) PrintResult("True - 28UL", True - 28UL) PrintResult("True - -9D", True - -9D) PrintResult("True - 10.0F", True - 10.0F) PrintResult("True - -11.0R", True - -11.0R) PrintResult("True - ""12""", True - "12") PrintResult("True - TypeCode.Double", True - TypeCode.Double) PrintResult("System.SByte.MinValue - False", System.SByte.MinValue - False) PrintResult("System.SByte.MinValue - True", System.SByte.MinValue - True) PrintResult("System.SByte.MinValue - System.SByte.MinValue", System.SByte.MinValue - System.SByte.MinValue) PrintResult("System.SByte.MinValue - System.Byte.MaxValue", System.SByte.MinValue - System.Byte.MaxValue) PrintResult("System.SByte.MinValue - -3S", System.SByte.MinValue - -3S) PrintResult("System.SByte.MinValue - 24US", System.SByte.MinValue - 24US) PrintResult("System.SByte.MinValue - -5I", System.SByte.MinValue - -5I) PrintResult("System.SByte.MinValue - 26UI", System.SByte.MinValue - 26UI) PrintResult("System.SByte.MinValue - -7L", System.SByte.MinValue - -7L) PrintResult("System.SByte.MinValue - 28UL", System.SByte.MinValue - 28UL) PrintResult("System.SByte.MinValue - -9D", System.SByte.MinValue - -9D) PrintResult("System.SByte.MinValue - 10.0F", System.SByte.MinValue - 10.0F) PrintResult("System.SByte.MinValue - -11.0R", System.SByte.MinValue - -11.0R) PrintResult("System.SByte.MinValue - ""12""", System.SByte.MinValue - "12") PrintResult("System.SByte.MinValue - TypeCode.Double", System.SByte.MinValue - TypeCode.Double) PrintResult("System.Byte.MaxValue - False", System.Byte.MaxValue - False) PrintResult("System.Byte.MaxValue - True", System.Byte.MaxValue - True) PrintResult("System.Byte.MaxValue - System.SByte.MinValue", System.Byte.MaxValue - System.SByte.MinValue) PrintResult("System.Byte.MaxValue - System.Byte.MaxValue", System.Byte.MaxValue - System.Byte.MaxValue) PrintResult("System.Byte.MaxValue - -3S", System.Byte.MaxValue - -3S) PrintResult("System.Byte.MaxValue - -5I", System.Byte.MaxValue - -5I) PrintResult("System.Byte.MaxValue - -7L", System.Byte.MaxValue - -7L) PrintResult("System.Byte.MaxValue - -9D", System.Byte.MaxValue - -9D) PrintResult("System.Byte.MaxValue - 10.0F", System.Byte.MaxValue - 10.0F) PrintResult("System.Byte.MaxValue - -11.0R", System.Byte.MaxValue - -11.0R) PrintResult("System.Byte.MaxValue - ""12""", System.Byte.MaxValue - "12") PrintResult("System.Byte.MaxValue - TypeCode.Double", System.Byte.MaxValue - TypeCode.Double) PrintResult("-3S - False", -3S - False) PrintResult("-3S - True", -3S - True) PrintResult("-3S - System.SByte.MinValue", -3S - System.SByte.MinValue) PrintResult("-3S - System.Byte.MaxValue", -3S - System.Byte.MaxValue) PrintResult("-3S - -3S", -3S - -3S) PrintResult("-3S - 24US", -3S - 24US) PrintResult("-3S - -5I", -3S - -5I) PrintResult("-3S - 26UI", -3S - 26UI) PrintResult("-3S - -7L", -3S - -7L) PrintResult("-3S - 28UL", -3S - 28UL) PrintResult("-3S - -9D", -3S - -9D) PrintResult("-3S - 10.0F", -3S - 10.0F) PrintResult("-3S - -11.0R", -3S - -11.0R) PrintResult("-3S - ""12""", -3S - "12") PrintResult("-3S - TypeCode.Double", -3S - TypeCode.Double) PrintResult("24US - False", 24US - False) PrintResult("24US - True", 24US - True) PrintResult("24US - System.SByte.MinValue", 24US - System.SByte.MinValue) PrintResult("System.UInt16.MaxValue - System.Byte.MaxValue", System.UInt16.MaxValue - System.Byte.MaxValue) PrintResult("24US - -3S", 24US - -3S) PrintResult("24US - 24US", 24US - 24US) PrintResult("24US - -5I", 24US - -5I) PrintResult("24US - -7L", 24US - -7L) PrintResult("24US - -9D", 24US - -9D) PrintResult("24US - 10.0F", 24US - 10.0F) PrintResult("24US - -11.0R", 24US - -11.0R) PrintResult("24US - ""12""", 24US - "12") PrintResult("24US - TypeCode.Double", 24US - TypeCode.Double) PrintResult("-5I - False", -5I - False) PrintResult("-5I - True", -5I - True) PrintResult("-5I - System.SByte.MinValue", -5I - System.SByte.MinValue) PrintResult("-5I - System.Byte.MaxValue", -5I - System.Byte.MaxValue) PrintResult("-5I - -3S", -5I - -3S) PrintResult("-5I - 24US", -5I - 24US) PrintResult("-5I - -5I", -5I - -5I) PrintResult("-5I - 26UI", -5I - 26UI) PrintResult("-5I - -7L", -5I - -7L) PrintResult("-5I - 28UL", -5I - 28UL) PrintResult("-5I - -9D", -5I - -9D) PrintResult("-5I - 10.0F", -5I - 10.0F) PrintResult("-5I - -11.0R", -5I - -11.0R) PrintResult("-5I - ""12""", -5I - "12") PrintResult("-5I - TypeCode.Double", -5I - TypeCode.Double) PrintResult("26UI - False", 26UI - False) PrintResult("26UI - True", 26UI - True) PrintResult("26UI - System.SByte.MinValue", 26UI - System.SByte.MinValue) PrintResult("System.UInt32.MaxValue - System.Byte.MaxValue", System.UInt32.MaxValue - System.Byte.MaxValue) PrintResult("26UI - -3S", 26UI - -3S) PrintResult("26UI - 24US", 26UI - 24US) PrintResult("26UI - -5I", 26UI - -5I) PrintResult("26UI - 26UI", 26UI - 26UI) PrintResult("26UI - -7L", 26UI - -7L) PrintResult("26UI - -9D", 26UI - -9D) PrintResult("26UI - 10.0F", 26UI - 10.0F) PrintResult("26UI - -11.0R", 26UI - -11.0R) PrintResult("26UI - ""12""", 26UI - "12") PrintResult("26UI - TypeCode.Double", 26UI - TypeCode.Double) PrintResult("-7L - False", -7L - False) PrintResult("-7L - True", -7L - True) PrintResult("-7L - System.SByte.MinValue", -7L - System.SByte.MinValue) PrintResult("-7L - System.Byte.MaxValue", -7L - System.Byte.MaxValue) PrintResult("-7L - -3S", -7L - -3S) PrintResult("-7L - 24US", -7L - 24US) PrintResult("-7L - -5I", -7L - -5I) PrintResult("-7L - 26UI", -7L - 26UI) PrintResult("-7L - -7L", -7L - -7L) PrintResult("-7L - 28UL", -7L - 28UL) PrintResult("-7L - -9D", -7L - -9D) PrintResult("-7L - 10.0F", -7L - 10.0F) PrintResult("-7L - -11.0R", -7L - -11.0R) PrintResult("-7L - ""12""", -7L - "12") PrintResult("-7L - TypeCode.Double", -7L - TypeCode.Double) PrintResult("28UL - False", 28UL - False) PrintResult("28UL - True", 28UL - True) PrintResult("28UL - System.SByte.MinValue", 28UL - System.SByte.MinValue) PrintResult("System.UInt64.MaxValue - System.Byte.MaxValue", System.UInt64.MaxValue - System.Byte.MaxValue) PrintResult("28UL - -3S", 28UL - -3S) PrintResult("28UL - 24US", 28UL - 24US) PrintResult("28UL - -5I", 28UL - -5I) PrintResult("28UL - 26UI", 28UL - 26UI) PrintResult("28UL - -7L", 28UL - -7L) PrintResult("28UL - 28UL", 28UL - 28UL) PrintResult("28UL - -9D", 28UL - -9D) PrintResult("28UL - 10.0F", 28UL - 10.0F) PrintResult("28UL - -11.0R", 28UL - -11.0R) PrintResult("28UL - ""12""", 28UL - "12") PrintResult("28UL - TypeCode.Double", 28UL - TypeCode.Double) PrintResult("-9D - False", -9D - False) PrintResult("-9D - True", -9D - True) PrintResult("-9D - System.SByte.MinValue", -9D - System.SByte.MinValue) PrintResult("-9D - System.Byte.MaxValue", -9D - System.Byte.MaxValue) PrintResult("-9D - -3S", -9D - -3S) PrintResult("-9D - 24US", -9D - 24US) PrintResult("-9D - -5I", -9D - -5I) PrintResult("-9D - 26UI", -9D - 26UI) PrintResult("-9D - -7L", -9D - -7L) PrintResult("-9D - 28UL", -9D - 28UL) PrintResult("-9D - -9D", -9D - -9D) PrintResult("-9D - 10.0F", -9D - 10.0F) PrintResult("-9D - -11.0R", -9D - -11.0R) PrintResult("-9D - ""12""", -9D - "12") PrintResult("-9D - TypeCode.Double", -9D - TypeCode.Double) PrintResult("10.0F - False", 10.0F - False) PrintResult("10.0F - True", 10.0F - True) PrintResult("10.0F - System.SByte.MinValue", 10.0F - System.SByte.MinValue) PrintResult("10.0F - System.Byte.MaxValue", 10.0F - System.Byte.MaxValue) PrintResult("10.0F - -3S", 10.0F - -3S) PrintResult("10.0F - 24US", 10.0F - 24US) PrintResult("10.0F - -5I", 10.0F - -5I) PrintResult("10.0F - 26UI", 10.0F - 26UI) PrintResult("10.0F - -7L", 10.0F - -7L) PrintResult("10.0F - 28UL", 10.0F - 28UL) PrintResult("10.0F - -9D", 10.0F - -9D) PrintResult("10.0F - 10.0F", 10.0F - 10.0F) PrintResult("10.0F - -11.0R", 10.0F - -11.0R) PrintResult("10.0F - ""12""", 10.0F - "12") PrintResult("10.0F - TypeCode.Double", 10.0F - TypeCode.Double) PrintResult("-11.0R - False", -11.0R - False) PrintResult("-11.0R - True", -11.0R - True) PrintResult("-11.0R - System.SByte.MinValue", -11.0R - System.SByte.MinValue) PrintResult("-11.0R - System.Byte.MaxValue", -11.0R - System.Byte.MaxValue) PrintResult("-11.0R - -3S", -11.0R - -3S) PrintResult("-11.0R - 24US", -11.0R - 24US) PrintResult("-11.0R - -5I", -11.0R - -5I) PrintResult("-11.0R - 26UI", -11.0R - 26UI) PrintResult("-11.0R - -7L", -11.0R - -7L) PrintResult("-11.0R - 28UL", -11.0R - 28UL) PrintResult("-11.0R - -9D", -11.0R - -9D) PrintResult("-11.0R - 10.0F", -11.0R - 10.0F) PrintResult("-11.0R - -11.0R", -11.0R - -11.0R) PrintResult("-11.0R - ""12""", -11.0R - "12") PrintResult("-11.0R - TypeCode.Double", -11.0R - TypeCode.Double) PrintResult("""12"" - False", "12" - False) PrintResult("""12"" - True", "12" - True) PrintResult("""12"" - System.SByte.MinValue", "12" - System.SByte.MinValue) PrintResult("""12"" - System.Byte.MaxValue", "12" - System.Byte.MaxValue) PrintResult("""12"" - -3S", "12" - -3S) PrintResult("""12"" - 24US", "12" - 24US) PrintResult("""12"" - -5I", "12" - -5I) PrintResult("""12"" - 26UI", "12" - 26UI) PrintResult("""12"" - -7L", "12" - -7L) PrintResult("""12"" - 28UL", "12" - 28UL) PrintResult("""12"" - -9D", "12" - -9D) PrintResult("""12"" - 10.0F", "12" - 10.0F) PrintResult("""12"" - -11.0R", "12" - -11.0R) PrintResult("""12"" - ""12""", "12" - "12") PrintResult("""12"" - TypeCode.Double", "12" - TypeCode.Double) PrintResult("TypeCode.Double - False", TypeCode.Double - False) PrintResult("TypeCode.Double - True", TypeCode.Double - True) PrintResult("TypeCode.Double - System.SByte.MinValue", TypeCode.Double - System.SByte.MinValue) PrintResult("TypeCode.Double - System.Byte.MaxValue", TypeCode.Double - System.Byte.MaxValue) PrintResult("TypeCode.Double - -3S", TypeCode.Double - -3S) PrintResult("TypeCode.Double - 24US", TypeCode.Double - 24US) PrintResult("TypeCode.Double - -5I", TypeCode.Double - -5I) PrintResult("TypeCode.Double - 26UI", TypeCode.Double - 26UI) PrintResult("TypeCode.Double - -7L", TypeCode.Double - -7L) PrintResult("TypeCode.Double - 28UL", TypeCode.Double - 28UL) PrintResult("TypeCode.Double - -9D", TypeCode.Double - -9D) PrintResult("TypeCode.Double - 10.0F", TypeCode.Double - 10.0F) PrintResult("TypeCode.Double - -11.0R", TypeCode.Double - -11.0R) PrintResult("TypeCode.Double - ""12""", TypeCode.Double - "12") PrintResult("TypeCode.Double - TypeCode.Double", TypeCode.Double - TypeCode.Double) PrintResult("False * False", False * False) PrintResult("False * True", False * True) PrintResult("False * System.SByte.MinValue", False * System.SByte.MinValue) PrintResult("False * System.Byte.MaxValue", False * System.Byte.MaxValue) PrintResult("False * -3S", False * -3S) PrintResult("False * 24US", False * 24US) PrintResult("False * -5I", False * -5I) PrintResult("False * 26UI", False * 26UI) PrintResult("False * -7L", False * -7L) PrintResult("False * 28UL", False * 28UL) PrintResult("False * -9D", False * -9D) PrintResult("False * 10.0F", False * 10.0F) PrintResult("False * -11.0R", False * -11.0R) PrintResult("False * ""12""", False * "12") PrintResult("False * TypeCode.Double", False * TypeCode.Double) PrintResult("True * False", True * False) PrintResult("True * True", True * True) PrintResult("True * System.SByte.MaxValue", True * System.SByte.MaxValue) PrintResult("True * System.Byte.MaxValue", True * System.Byte.MaxValue) PrintResult("True * -3S", True * -3S) PrintResult("True * 24US", True * 24US) PrintResult("True * -5I", True * -5I) PrintResult("True * 26UI", True * 26UI) PrintResult("True * -7L", True * -7L) PrintResult("True * 28UL", True * 28UL) PrintResult("True * -9D", True * -9D) PrintResult("True * 10.0F", True * 10.0F) PrintResult("True * -11.0R", True * -11.0R) PrintResult("True * ""12""", True * "12") PrintResult("True * TypeCode.Double", True * TypeCode.Double) PrintResult("System.SByte.MinValue * False", System.SByte.MinValue * False) PrintResult("System.SByte.MaxValue * True", System.SByte.MaxValue * True) PrintResult("System.SByte.MinValue * (-(System.SByte.MinValue + System.SByte.MaxValue))", System.SByte.MinValue * (-(System.SByte.MinValue + System.SByte.MaxValue))) PrintResult("System.SByte.MinValue * System.Byte.MaxValue", System.SByte.MinValue * System.Byte.MaxValue) PrintResult("System.SByte.MinValue * -3S", System.SByte.MinValue * -3S) PrintResult("System.SByte.MinValue * 24US", System.SByte.MinValue * 24US) PrintResult("System.SByte.MinValue * -5I", System.SByte.MinValue * -5I) PrintResult("System.SByte.MinValue * 26UI", System.SByte.MinValue * 26UI) PrintResult("System.SByte.MinValue * -7L", System.SByte.MinValue * -7L) PrintResult("System.SByte.MinValue * 28UL", System.SByte.MinValue * 28UL) PrintResult("System.SByte.MinValue * -9D", System.SByte.MinValue * -9D) PrintResult("System.SByte.MinValue * 10.0F", System.SByte.MinValue * 10.0F) PrintResult("System.SByte.MinValue * -11.0R", System.SByte.MinValue * -11.0R) PrintResult("System.SByte.MinValue * ""12""", System.SByte.MinValue * "12") PrintResult("System.SByte.MinValue * TypeCode.Double", System.SByte.MinValue * TypeCode.Double) PrintResult("System.Byte.MaxValue * False", System.Byte.MaxValue * False) PrintResult("System.Byte.MaxValue * True", System.Byte.MaxValue * True) PrintResult("System.Byte.MaxValue * System.SByte.MinValue", System.Byte.MaxValue * System.SByte.MinValue) PrintResult("System.Byte.MaxValue * -3S", System.Byte.MaxValue * -3S) PrintResult("System.Byte.MaxValue * 24US", System.Byte.MaxValue * 24US) PrintResult("System.Byte.MaxValue * -5I", System.Byte.MaxValue * -5I) PrintResult("System.Byte.MaxValue * 26UI", System.Byte.MaxValue * 26UI) PrintResult("System.Byte.MaxValue * -7L", System.Byte.MaxValue * -7L) PrintResult("System.Byte.MaxValue * 28UL", System.Byte.MaxValue * 28UL) PrintResult("System.Byte.MaxValue * -9D", System.Byte.MaxValue * -9D) PrintResult("System.Byte.MaxValue * 10.0F", System.Byte.MaxValue * 10.0F) PrintResult("System.Byte.MaxValue * -11.0R", System.Byte.MaxValue * -11.0R) PrintResult("System.Byte.MaxValue * ""12""", System.Byte.MaxValue * "12") PrintResult("System.Byte.MaxValue * TypeCode.Double", System.Byte.MaxValue * TypeCode.Double) PrintResult("-3S * False", -3S * False) PrintResult("-3S * True", -3S * True) PrintResult("-3S * System.SByte.MinValue", -3S * System.SByte.MinValue) PrintResult("-3S * System.Byte.MaxValue", -3S * System.Byte.MaxValue) PrintResult("-3S * -3S", -3S * -3S) PrintResult("-3S * 24US", -3S * 24US) PrintResult("-3S * -5I", -3S * -5I) PrintResult("-3S * 26UI", -3S * 26UI) PrintResult("-3S * -7L", -3S * -7L) PrintResult("-3S * 28UL", -3S * 28UL) PrintResult("-3S * -9D", -3S * -9D) PrintResult("-3S * 10.0F", -3S * 10.0F) PrintResult("-3S * -11.0R", -3S * -11.0R) PrintResult("-3S * ""12""", -3S * "12") PrintResult("-3S * TypeCode.Double", -3S * TypeCode.Double) PrintResult("24US * False", 24US * False) PrintResult("24US * True", 24US * True) PrintResult("24US * System.SByte.MinValue", 24US * System.SByte.MinValue) PrintResult("24US * System.Byte.MaxValue", 24US * System.Byte.MaxValue) PrintResult("24US * -3S", 24US * -3S) PrintResult("24US * 24US", 24US * 24US) PrintResult("24US * -5I", 24US * -5I) PrintResult("24US * 26UI", 24US * 26UI) PrintResult("24US * -7L", 24US * -7L) PrintResult("24US * 28UL", 24US * 28UL) PrintResult("24US * -9D", 24US * -9D) PrintResult("24US * 10.0F", 24US * 10.0F) PrintResult("24US * -11.0R", 24US * -11.0R) PrintResult("24US * ""12""", 24US * "12") PrintResult("24US * TypeCode.Double", 24US * TypeCode.Double) PrintResult("-5I * False", -5I * False) PrintResult("-5I * True", -5I * True) PrintResult("-5I * System.SByte.MinValue", -5I * System.SByte.MinValue) PrintResult("-5I * System.Byte.MaxValue", -5I * System.Byte.MaxValue) PrintResult("-5I * -3S", -5I * -3S) PrintResult("-5I * 24US", -5I * 24US) PrintResult("-5I * -5I", -5I * -5I) PrintResult("-5I * 26UI", -5I * 26UI) PrintResult("-5I * -7L", -5I * -7L) PrintResult("-5I * 28UL", -5I * 28UL) PrintResult("-5I * -9D", -5I * -9D) PrintResult("-5I * 10.0F", -5I * 10.0F) PrintResult("-5I * -11.0R", -5I * -11.0R) PrintResult("-5I * ""12""", -5I * "12") PrintResult("-5I * TypeCode.Double", -5I * TypeCode.Double) PrintResult("26UI * False", 26UI * False) PrintResult("26UI * True", 26UI * True) PrintResult("26UI * System.SByte.MinValue", 26UI * System.SByte.MinValue) PrintResult("26UI * System.Byte.MaxValue", 26UI * System.Byte.MaxValue) PrintResult("26UI * -3S", 26UI * -3S) PrintResult("26UI * 24US", 26UI * 24US) PrintResult("26UI * -5I", 26UI * -5I) PrintResult("26UI * 26UI", 26UI * 26UI) PrintResult("26UI * -7L", 26UI * -7L) PrintResult("26UI * 28UL", 26UI * 28UL) PrintResult("26UI * -9D", 26UI * -9D) PrintResult("26UI * 10.0F", 26UI * 10.0F) PrintResult("26UI * -11.0R", 26UI * -11.0R) PrintResult("26UI * ""12""", 26UI * "12") PrintResult("26UI * TypeCode.Double", 26UI * TypeCode.Double) PrintResult("-7L * False", -7L * False) PrintResult("-7L * True", -7L * True) PrintResult("-7L * System.SByte.MinValue", -7L * System.SByte.MinValue) PrintResult("-7L * System.Byte.MaxValue", -7L * System.Byte.MaxValue) PrintResult("-7L * -3S", -7L * -3S) PrintResult("-7L * 24US", -7L * 24US) PrintResult("-7L * -5I", -7L * -5I) PrintResult("-7L * 26UI", -7L * 26UI) PrintResult("-7L * -7L", -7L * -7L) PrintResult("-7L * 28UL", -7L * 28UL) PrintResult("-7L * -9D", -7L * -9D) PrintResult("-7L * 10.0F", -7L * 10.0F) PrintResult("-7L * -11.0R", -7L * -11.0R) PrintResult("-7L * ""12""", -7L * "12") PrintResult("-7L * TypeCode.Double", -7L * TypeCode.Double) PrintResult("28UL * False", 28UL * False) PrintResult("28UL * True", 28UL * True) PrintResult("28UL * System.SByte.MinValue", 28UL * System.SByte.MinValue) PrintResult("28UL * System.Byte.MaxValue", 28UL * System.Byte.MaxValue) PrintResult("28UL * -3S", 28UL * -3S) PrintResult("28UL * 24US", 28UL * 24US) PrintResult("28UL * -5I", 28UL * -5I) PrintResult("28UL * 26UI", 28UL * 26UI) PrintResult("28UL * -7L", 28UL * -7L) PrintResult("28UL * 28UL", 28UL * 28UL) PrintResult("28UL * -9D", 28UL * -9D) PrintResult("28UL * 10.0F", 28UL * 10.0F) PrintResult("28UL * -11.0R", 28UL * -11.0R) PrintResult("28UL * ""12""", 28UL * "12") PrintResult("28UL * TypeCode.Double", 28UL * TypeCode.Double) PrintResult("-9D * False", -9D * False) PrintResult("-9D * True", -9D * True) PrintResult("-9D * System.SByte.MinValue", -9D * System.SByte.MinValue) PrintResult("-9D * System.Byte.MaxValue", -9D * System.Byte.MaxValue) PrintResult("-9D * -3S", -9D * -3S) PrintResult("-9D * 24US", -9D * 24US) PrintResult("-9D * -5I", -9D * -5I) PrintResult("-9D * 26UI", -9D * 26UI) PrintResult("-9D * -7L", -9D * -7L) PrintResult("-9D * 28UL", -9D * 28UL) PrintResult("-9D * -9D", -9D * -9D) PrintResult("-9D * 10.0F", -9D * 10.0F) PrintResult("-9D * -11.0R", -9D * -11.0R) PrintResult("-9D * ""12""", -9D * "12") PrintResult("-9D * TypeCode.Double", -9D * TypeCode.Double) PrintResult("10.0F * False", 10.0F * False) PrintResult("10.0F * True", 10.0F * True) PrintResult("10.0F * System.SByte.MinValue", 10.0F * System.SByte.MinValue) PrintResult("10.0F * System.Byte.MaxValue", 10.0F * System.Byte.MaxValue) PrintResult("10.0F * -3S", 10.0F * -3S) PrintResult("10.0F * 24US", 10.0F * 24US) PrintResult("10.0F * -5I", 10.0F * -5I) PrintResult("10.0F * 26UI", 10.0F * 26UI) PrintResult("10.0F * -7L", 10.0F * -7L) PrintResult("10.0F * 28UL", 10.0F * 28UL) PrintResult("10.0F * -9D", 10.0F * -9D) PrintResult("10.0F * 10.0F", 10.0F * 10.0F) PrintResult("10.0F * -11.0R", 10.0F * -11.0R) PrintResult("10.0F * ""12""", 10.0F * "12") PrintResult("10.0F * TypeCode.Double", 10.0F * TypeCode.Double) PrintResult("-11.0R * False", -11.0R * False) PrintResult("-11.0R * True", -11.0R * True) PrintResult("-11.0R * System.SByte.MinValue", -11.0R * System.SByte.MinValue) PrintResult("-11.0R * System.Byte.MaxValue", -11.0R * System.Byte.MaxValue) PrintResult("-11.0R * -3S", -11.0R * -3S) PrintResult("-11.0R * 24US", -11.0R * 24US) PrintResult("-11.0R * -5I", -11.0R * -5I) PrintResult("-11.0R * 26UI", -11.0R * 26UI) PrintResult("-11.0R * -7L", -11.0R * -7L) PrintResult("-11.0R * 28UL", -11.0R * 28UL) PrintResult("-11.0R * -9D", -11.0R * -9D) PrintResult("-11.0R * 10.0F", -11.0R * 10.0F) PrintResult("-11.0R * -11.0R", -11.0R * -11.0R) PrintResult("-11.0R * ""12""", -11.0R * "12") PrintResult("-11.0R * TypeCode.Double", -11.0R * TypeCode.Double) PrintResult("""12"" * False", "12" * False) PrintResult("""12"" * True", "12" * True) PrintResult("""12"" * System.SByte.MinValue", "12" * System.SByte.MinValue) PrintResult("""12"" * System.Byte.MaxValue", "12" * System.Byte.MaxValue) PrintResult("""12"" * -3S", "12" * -3S) PrintResult("""12"" * 24US", "12" * 24US) PrintResult("""12"" * -5I", "12" * -5I) PrintResult("""12"" * 26UI", "12" * 26UI) PrintResult("""12"" * -7L", "12" * -7L) PrintResult("""12"" * 28UL", "12" * 28UL) PrintResult("""12"" * -9D", "12" * -9D) PrintResult("""12"" * 10.0F", "12" * 10.0F) PrintResult("""12"" * -11.0R", "12" * -11.0R) PrintResult("""12"" * ""12""", "12" * "12") PrintResult("""12"" * TypeCode.Double", "12" * TypeCode.Double) PrintResult("TypeCode.Double * False", TypeCode.Double * False) PrintResult("TypeCode.Double * True", TypeCode.Double * True) PrintResult("TypeCode.Double * System.SByte.MinValue", TypeCode.Double * System.SByte.MinValue) PrintResult("TypeCode.Double * System.Byte.MaxValue", TypeCode.Double * System.Byte.MaxValue) PrintResult("TypeCode.Double * -3S", TypeCode.Double * -3S) PrintResult("TypeCode.Double * 24US", TypeCode.Double * 24US) PrintResult("TypeCode.Double * -5I", TypeCode.Double * -5I) PrintResult("TypeCode.Double * 26UI", TypeCode.Double * 26UI) PrintResult("TypeCode.Double * -7L", TypeCode.Double * -7L) PrintResult("TypeCode.Double * 28UL", TypeCode.Double * 28UL) PrintResult("TypeCode.Double * -9D", TypeCode.Double * -9D) PrintResult("TypeCode.Double * 10.0F", TypeCode.Double * 10.0F) PrintResult("TypeCode.Double * -11.0R", TypeCode.Double * -11.0R) PrintResult("TypeCode.Double * ""12""", TypeCode.Double * "12") PrintResult("TypeCode.Double * TypeCode.Double", TypeCode.Double * TypeCode.Double) PrintResult("False / False", False / False) PrintResult("False / True", False / True) PrintResult("False / System.SByte.MinValue", False / System.SByte.MinValue) PrintResult("False / System.Byte.MaxValue", False / System.Byte.MaxValue) PrintResult("False / -3S", False / -3S) PrintResult("False / 24US", False / 24US) PrintResult("False / -5I", False / -5I) PrintResult("False / 26UI", False / 26UI) PrintResult("False / -7L", False / -7L) PrintResult("False / 28UL", False / 28UL) PrintResult("False / -9D", False / -9D) PrintResult("False / 10.0F", False / 10.0F) PrintResult("False / -11.0R", False / -11.0R) PrintResult("False / ""12""", False / "12") PrintResult("False / TypeCode.Double", False / TypeCode.Double) PrintResult("True / False", True / False) PrintResult("True / True", True / True) PrintResult("True / System.SByte.MinValue", True / System.SByte.MinValue) PrintResult("True / System.Byte.MaxValue", True / System.Byte.MaxValue) PrintResult("True / -3S", True / -3S) PrintResult("True / 24US", True / 24US) PrintResult("True / -5I", True / -5I) PrintResult("True / 26UI", True / 26UI) PrintResult("True / -7L", True / -7L) PrintResult("True / 28UL", True / 28UL) PrintResult("True / -9D", True / -9D) PrintResult("True / 10.0F", True / 10.0F) PrintResult("True / -11.0R", True / -11.0R) PrintResult("True / ""12""", True / "12") PrintResult("True / TypeCode.Double", True / TypeCode.Double) PrintResult("System.SByte.MinValue / False", System.SByte.MinValue / False) PrintResult("System.SByte.MinValue / True", System.SByte.MinValue / True) PrintResult("System.SByte.MinValue / System.SByte.MinValue", System.SByte.MinValue / System.SByte.MinValue) PrintResult("System.SByte.MinValue / System.Byte.MaxValue", System.SByte.MinValue / System.Byte.MaxValue) PrintResult("System.SByte.MinValue / -3S", System.SByte.MinValue / -3S) PrintResult("System.SByte.MinValue / 24US", System.SByte.MinValue / 24US) PrintResult("System.SByte.MinValue / -5I", System.SByte.MinValue / -5I) PrintResult("System.SByte.MinValue / 26UI", System.SByte.MinValue / 26UI) PrintResult("System.SByte.MinValue / -7L", System.SByte.MinValue / -7L) PrintResult("System.SByte.MinValue / 28UL", System.SByte.MinValue / 28UL) PrintResult("System.SByte.MinValue / -9D", System.SByte.MinValue / -9D) PrintResult("System.SByte.MinValue / 10.0F", System.SByte.MinValue / 10.0F) PrintResult("System.SByte.MinValue / -11.0R", System.SByte.MinValue / -11.0R) PrintResult("System.SByte.MinValue / ""12""", System.SByte.MinValue / "12") PrintResult("System.SByte.MinValue / TypeCode.Double", System.SByte.MinValue / TypeCode.Double) PrintResult("System.Byte.MaxValue / False", System.Byte.MaxValue / False) PrintResult("System.Byte.MaxValue / True", System.Byte.MaxValue / True) PrintResult("System.Byte.MaxValue / System.SByte.MinValue", System.Byte.MaxValue / System.SByte.MinValue) PrintResult("System.Byte.MaxValue / System.Byte.MaxValue", System.Byte.MaxValue / System.Byte.MaxValue) PrintResult("System.Byte.MaxValue / -3S", System.Byte.MaxValue / -3S) PrintResult("System.Byte.MaxValue / 24US", System.Byte.MaxValue / 24US) PrintResult("System.Byte.MaxValue / -5I", System.Byte.MaxValue / -5I) PrintResult("System.Byte.MaxValue / 26UI", System.Byte.MaxValue / 26UI) PrintResult("System.Byte.MaxValue / -7L", System.Byte.MaxValue / -7L) PrintResult("System.Byte.MaxValue / 28UL", System.Byte.MaxValue / 28UL) PrintResult("System.Byte.MaxValue / -9D", System.Byte.MaxValue / -9D) PrintResult("System.Byte.MaxValue / 10.0F", System.Byte.MaxValue / 10.0F) PrintResult("System.Byte.MaxValue / -11.0R", System.Byte.MaxValue / -11.0R) PrintResult("System.Byte.MaxValue / ""12""", System.Byte.MaxValue / "12") PrintResult("System.Byte.MaxValue / TypeCode.Double", System.Byte.MaxValue / TypeCode.Double) PrintResult("-3S / False", -3S / False) PrintResult("-3S / True", -3S / True) PrintResult("-3S / System.SByte.MinValue", -3S / System.SByte.MinValue) PrintResult("-3S / System.Byte.MaxValue", -3S / System.Byte.MaxValue) PrintResult("-3S / -3S", -3S / -3S) PrintResult("-3S / 24US", -3S / 24US) PrintResult("-3S / -5I", -3S / -5I) PrintResult("-3S / 26UI", -3S / 26UI) PrintResult("-3S / -7L", -3S / -7L) PrintResult("-3S / 28UL", -3S / 28UL) PrintResult("-3S / -9D", -3S / -9D) PrintResult("-3S / 10.0F", -3S / 10.0F) PrintResult("-3S / -11.0R", -3S / -11.0R) PrintResult("-3S / ""12""", -3S / "12") PrintResult("-3S / TypeCode.Double", -3S / TypeCode.Double) PrintResult("24US / False", 24US / False) PrintResult("24US / True", 24US / True) PrintResult("24US / System.SByte.MinValue", 24US / System.SByte.MinValue) PrintResult("24US / System.Byte.MaxValue", 24US / System.Byte.MaxValue) PrintResult("24US / -3S", 24US / -3S) PrintResult("24US / 24US", 24US / 24US) PrintResult("24US / -5I", 24US / -5I) PrintResult("24US / 26UI", 24US / 26UI) PrintResult("24US / -7L", 24US / -7L) PrintResult("24US / 28UL", 24US / 28UL) PrintResult("24US / -9D", 24US / -9D) PrintResult("24US / 10.0F", 24US / 10.0F) PrintResult("24US / -11.0R", 24US / -11.0R) PrintResult("24US / ""12""", 24US / "12") PrintResult("24US / TypeCode.Double", 24US / TypeCode.Double) PrintResult("-5I / False", -5I / False) PrintResult("-5I / True", -5I / True) PrintResult("-5I / System.SByte.MinValue", -5I / System.SByte.MinValue) PrintResult("-5I / System.Byte.MaxValue", -5I / System.Byte.MaxValue) PrintResult("-5I / -3S", -5I / -3S) PrintResult("-5I / 24US", -5I / 24US) PrintResult("-5I / -5I", -5I / -5I) PrintResult("-5I / 26UI", -5I / 26UI) PrintResult("-5I / -7L", -5I / -7L) PrintResult("-5I / 28UL", -5I / 28UL) PrintResult("-5I / -9D", -5I / -9D) PrintResult("-5I / 10.0F", -5I / 10.0F) PrintResult("-5I / -11.0R", -5I / -11.0R) PrintResult("-5I / ""12""", -5I / "12") PrintResult("-5I / TypeCode.Double", -5I / TypeCode.Double) PrintResult("26UI / False", 26UI / False) PrintResult("26UI / True", 26UI / True) PrintResult("26UI / System.SByte.MinValue", 26UI / System.SByte.MinValue) PrintResult("26UI / System.Byte.MaxValue", 26UI / System.Byte.MaxValue) PrintResult("26UI / -3S", 26UI / -3S) PrintResult("26UI / 24US", 26UI / 24US) PrintResult("26UI / -5I", 26UI / -5I) PrintResult("26UI / 26UI", 26UI / 26UI) PrintResult("26UI / -7L", 26UI / -7L) PrintResult("26UI / 28UL", 26UI / 28UL) PrintResult("26UI / -9D", 26UI / -9D) PrintResult("26UI / 10.0F", 26UI / 10.0F) PrintResult("26UI / -11.0R", 26UI / -11.0R) PrintResult("26UI / ""12""", 26UI / "12") PrintResult("26UI / TypeCode.Double", 26UI / TypeCode.Double) PrintResult("-7L / False", -7L / False) PrintResult("-7L / True", -7L / True) PrintResult("-7L / System.SByte.MinValue", -7L / System.SByte.MinValue) PrintResult("-7L / System.Byte.MaxValue", -7L / System.Byte.MaxValue) PrintResult("-7L / -3S", -7L / -3S) PrintResult("-7L / 24US", -7L / 24US) PrintResult("-7L / -5I", -7L / -5I) PrintResult("-7L / 26UI", -7L / 26UI) PrintResult("-7L / -7L", -7L / -7L) PrintResult("-7L / 28UL", -7L / 28UL) PrintResult("-7L / -9D", -7L / -9D) PrintResult("-7L / 10.0F", -7L / 10.0F) PrintResult("-7L / -11.0R", -7L / -11.0R) PrintResult("-7L / ""12""", -7L / "12") PrintResult("-7L / TypeCode.Double", -7L / TypeCode.Double) PrintResult("28UL / False", 28UL / False) PrintResult("28UL / True", 28UL / True) PrintResult("28UL / System.SByte.MinValue", 28UL / System.SByte.MinValue) PrintResult("28UL / System.Byte.MaxValue", 28UL / System.Byte.MaxValue) PrintResult("28UL / -3S", 28UL / -3S) PrintResult("28UL / 24US", 28UL / 24US) PrintResult("28UL / -5I", 28UL / -5I) PrintResult("28UL / 26UI", 28UL / 26UI) PrintResult("28UL / -7L", 28UL / -7L) PrintResult("28UL / 28UL", 28UL / 28UL) PrintResult("28UL / -9D", 28UL / -9D) PrintResult("28UL / 10.0F", 28UL / 10.0F) PrintResult("28UL / -11.0R", 28UL / -11.0R) PrintResult("28UL / ""12""", 28UL / "12") PrintResult("28UL / TypeCode.Double", 28UL / TypeCode.Double) PrintResult("-9D / True", -9D / True) PrintResult("-9D / System.SByte.MinValue", -9D / System.SByte.MinValue) PrintResult("-9D / System.Byte.MaxValue", -9D / System.Byte.MaxValue) PrintResult("-9D / -3S", -9D / -3S) PrintResult("-9D / 24US", -9D / 24US) PrintResult("-9D / -5I", -9D / -5I) PrintResult("-9D / 26UI", -9D / 26UI) PrintResult("-9D / -7L", -9D / -7L) PrintResult("-9D / 28UL", -9D / 28UL) PrintResult("-9D / -9D", -9D / -9D) PrintResult("-9D / 10.0F", -9D / 10.0F) PrintResult("-9D / -11.0R", -9D / -11.0R) PrintResult("-9D / ""12""", -9D / "12") PrintResult("-9D / TypeCode.Double", -9D / TypeCode.Double) PrintResult("10.0F / False", 10.0F / False) PrintResult("10.0F / True", 10.0F / True) PrintResult("10.0F / System.SByte.MinValue", 10.0F / System.SByte.MinValue) PrintResult("10.0F / System.Byte.MaxValue", 10.0F / System.Byte.MaxValue) PrintResult("10.0F / -3S", 10.0F / -3S) PrintResult("10.0F / 24US", 10.0F / 24US) PrintResult("10.0F / -5I", 10.0F / -5I) PrintResult("10.0F / 26UI", 10.0F / 26UI) PrintResult("10.0F / -7L", 10.0F / -7L) PrintResult("10.0F / 28UL", 10.0F / 28UL) PrintResult("10.0F / -9D", 10.0F / -9D) PrintResult("10.0F / 10.0F", 10.0F / 10.0F) PrintResult("10.0F / -11.0R", 10.0F / -11.0R) PrintResult("10.0F / ""12""", 10.0F / "12") PrintResult("10.0F / TypeCode.Double", 10.0F / TypeCode.Double) PrintResult("-11.0R / False", -11.0R / False) PrintResult("-11.0R / True", -11.0R / True) PrintResult("-11.0R / System.SByte.MinValue", -11.0R / System.SByte.MinValue) PrintResult("-11.0R / System.Byte.MaxValue", -11.0R / System.Byte.MaxValue) PrintResult("-11.0R / -3S", -11.0R / -3S) PrintResult("-11.0R / 24US", -11.0R / 24US) PrintResult("-11.0R / -5I", -11.0R / -5I) PrintResult("-11.0R / 26UI", -11.0R / 26UI) PrintResult("-11.0R / -7L", -11.0R / -7L) PrintResult("-11.0R / 28UL", -11.0R / 28UL) PrintResult("-11.0R / -9D", -11.0R / -9D) PrintResult("-11.0R / 10.0F", -11.0R / 10.0F) PrintResult("-11.0R / -11.0R", -11.0R / -11.0R) PrintResult("-11.0R / ""12""", -11.0R / "12") PrintResult("-11.0R / TypeCode.Double", -11.0R / TypeCode.Double) PrintResult("""12"" / False", "12" / False) PrintResult("""12"" / True", "12" / True) PrintResult("""12"" / System.SByte.MinValue", "12" / System.SByte.MinValue) PrintResult("""12"" / System.Byte.MaxValue", "12" / System.Byte.MaxValue) PrintResult("""12"" / -3S", "12" / -3S) PrintResult("""12"" / 24US", "12" / 24US) PrintResult("""12"" / -5I", "12" / -5I) PrintResult("""12"" / 26UI", "12" / 26UI) PrintResult("""12"" / -7L", "12" / -7L) PrintResult("""12"" / 28UL", "12" / 28UL) PrintResult("""12"" / -9D", "12" / -9D) PrintResult("""12"" / 10.0F", "12" / 10.0F) PrintResult("""12"" / -11.0R", "12" / -11.0R) PrintResult("""12"" / ""12""", "12" / "12") PrintResult("""12"" / TypeCode.Double", "12" / TypeCode.Double) PrintResult("TypeCode.Double / False", TypeCode.Double / False) PrintResult("TypeCode.Double / True", TypeCode.Double / True) PrintResult("TypeCode.Double / System.SByte.MinValue", TypeCode.Double / System.SByte.MinValue) PrintResult("TypeCode.Double / System.Byte.MaxValue", TypeCode.Double / System.Byte.MaxValue) PrintResult("TypeCode.Double / -3S", TypeCode.Double / -3S) PrintResult("TypeCode.Double / 24US", TypeCode.Double / 24US) PrintResult("TypeCode.Double / -5I", TypeCode.Double / -5I) PrintResult("TypeCode.Double / 26UI", TypeCode.Double / 26UI) PrintResult("TypeCode.Double / -7L", TypeCode.Double / -7L) PrintResult("TypeCode.Double / 28UL", TypeCode.Double / 28UL) PrintResult("TypeCode.Double / -9D", TypeCode.Double / -9D) PrintResult("TypeCode.Double / 10.0F", TypeCode.Double / 10.0F) PrintResult("TypeCode.Double / -11.0R", TypeCode.Double / -11.0R) PrintResult("TypeCode.Double / ""12""", TypeCode.Double / "12") PrintResult("TypeCode.Double / TypeCode.Double", TypeCode.Double / TypeCode.Double) PrintResult("False \ True", False \ True) PrintResult("False \ System.SByte.MinValue", False \ System.SByte.MinValue) PrintResult("False \ System.Byte.MaxValue", False \ System.Byte.MaxValue) PrintResult("False \ -3S", False \ -3S) PrintResult("False \ 24US", False \ 24US) PrintResult("False \ -5I", False \ -5I) PrintResult("False \ 26UI", False \ 26UI) PrintResult("False \ -7L", False \ -7L) PrintResult("False \ 28UL", False \ 28UL) PrintResult("False \ -9D", False \ -9D) PrintResult("False \ 10.0F", False \ 10.0F) PrintResult("False \ -11.0R", False \ -11.0R) PrintResult("False \ ""12""", False \ "12") PrintResult("False \ TypeCode.Double", False \ TypeCode.Double) PrintResult("True \ True", True \ True) PrintResult("True \ System.SByte.MinValue", True \ System.SByte.MinValue) PrintResult("True \ System.Byte.MaxValue", True \ System.Byte.MaxValue) PrintResult("True \ -3S", True \ -3S) PrintResult("True \ 24US", True \ 24US) PrintResult("True \ -5I", True \ -5I) PrintResult("True \ 26UI", True \ 26UI) PrintResult("True \ -7L", True \ -7L) PrintResult("True \ 28UL", True \ 28UL) PrintResult("True \ -9D", True \ -9D) PrintResult("True \ 10.0F", True \ 10.0F) PrintResult("True \ -11.0R", True \ -11.0R) PrintResult("True \ ""12""", True \ "12") PrintResult("True \ TypeCode.Double", True \ TypeCode.Double) PrintResult("System.SByte.MaxValue \ True", System.SByte.MaxValue \ True) PrintResult("System.SByte.MinValue \ System.SByte.MinValue", System.SByte.MinValue \ System.SByte.MinValue) PrintResult("System.SByte.MinValue \ System.Byte.MaxValue", System.SByte.MinValue \ System.Byte.MaxValue) PrintResult("System.SByte.MinValue \ -3S", System.SByte.MinValue \ -3S) PrintResult("System.SByte.MinValue \ 24US", System.SByte.MinValue \ 24US) PrintResult("System.SByte.MinValue \ -5I", System.SByte.MinValue \ -5I) PrintResult("System.SByte.MinValue \ 26UI", System.SByte.MinValue \ 26UI) PrintResult("System.SByte.MinValue \ -7L", System.SByte.MinValue \ -7L) PrintResult("System.SByte.MinValue \ 28UL", System.SByte.MinValue \ 28UL) PrintResult("System.SByte.MinValue \ -9D", System.SByte.MinValue \ -9D) PrintResult("System.SByte.MinValue \ 10.0F", System.SByte.MinValue \ 10.0F) PrintResult("System.SByte.MinValue \ -11.0R", System.SByte.MinValue \ -11.0R) PrintResult("System.SByte.MinValue \ ""12""", System.SByte.MinValue \ "12") PrintResult("System.SByte.MinValue \ TypeCode.Double", System.SByte.MinValue \ TypeCode.Double) PrintResult("System.Byte.MaxValue \ True", System.Byte.MaxValue \ True) PrintResult("System.Byte.MaxValue \ System.SByte.MinValue", System.Byte.MaxValue \ System.SByte.MinValue) PrintResult("System.Byte.MaxValue \ System.Byte.MaxValue", System.Byte.MaxValue \ System.Byte.MaxValue) PrintResult("System.Byte.MaxValue \ -3S", System.Byte.MaxValue \ -3S) PrintResult("System.Byte.MaxValue \ 24US", System.Byte.MaxValue \ 24US) PrintResult("System.Byte.MaxValue \ -5I", System.Byte.MaxValue \ -5I) PrintResult("System.Byte.MaxValue \ 26UI", System.Byte.MaxValue \ 26UI) PrintResult("System.Byte.MaxValue \ -7L", System.Byte.MaxValue \ -7L) PrintResult("System.Byte.MaxValue \ 28UL", System.Byte.MaxValue \ 28UL) PrintResult("System.Byte.MaxValue \ -9D", System.Byte.MaxValue \ -9D) PrintResult("System.Byte.MaxValue \ 10.0F", System.Byte.MaxValue \ 10.0F) PrintResult("System.Byte.MaxValue \ -11.0R", System.Byte.MaxValue \ -11.0R) PrintResult("System.Byte.MaxValue \ ""12""", System.Byte.MaxValue \ "12") PrintResult("System.Byte.MaxValue \ TypeCode.Double", System.Byte.MaxValue \ TypeCode.Double) PrintResult("-3S \ True", -3S \ True) PrintResult("-3S \ System.SByte.MinValue", -3S \ System.SByte.MinValue) PrintResult("-3S \ System.Byte.MaxValue", -3S \ System.Byte.MaxValue) PrintResult("-3S \ -3S", -3S \ -3S) PrintResult("-3S \ 24US", -3S \ 24US) PrintResult("-3S \ -5I", -3S \ -5I) PrintResult("-3S \ 26UI", -3S \ 26UI) PrintResult("-3S \ -7L", -3S \ -7L) PrintResult("-3S \ 28UL", -3S \ 28UL) PrintResult("-3S \ -9D", -3S \ -9D) PrintResult("-3S \ 10.0F", -3S \ 10.0F) PrintResult("-3S \ -11.0R", -3S \ -11.0R) PrintResult("-3S \ ""12""", -3S \ "12") PrintResult("-3S \ TypeCode.Double", -3S \ TypeCode.Double) PrintResult("24US \ True", 24US \ True) PrintResult("24US \ System.SByte.MinValue", 24US \ System.SByte.MinValue) PrintResult("24US \ System.Byte.MaxValue", 24US \ System.Byte.MaxValue) PrintResult("24US \ -3S", 24US \ -3S) PrintResult("24US \ 24US", 24US \ 24US) PrintResult("24US \ -5I", 24US \ -5I) PrintResult("24US \ 26UI", 24US \ 26UI) PrintResult("24US \ -7L", 24US \ -7L) PrintResult("24US \ 28UL", 24US \ 28UL) PrintResult("24US \ -9D", 24US \ -9D) PrintResult("24US \ 10.0F", 24US \ 10.0F) PrintResult("24US \ -11.0R", 24US \ -11.0R) PrintResult("24US \ ""12""", 24US \ "12") PrintResult("24US \ TypeCode.Double", 24US \ TypeCode.Double) PrintResult("-5I \ True", -5I \ True) PrintResult("-5I \ System.SByte.MinValue", -5I \ System.SByte.MinValue) PrintResult("-5I \ System.Byte.MaxValue", -5I \ System.Byte.MaxValue) PrintResult("-5I \ -3S", -5I \ -3S) PrintResult("-5I \ 24US", -5I \ 24US) PrintResult("-5I \ -5I", -5I \ -5I) PrintResult("-5I \ 26UI", -5I \ 26UI) PrintResult("-5I \ -7L", -5I \ -7L) PrintResult("-5I \ 28UL", -5I \ 28UL) PrintResult("-5I \ -9D", -5I \ -9D) PrintResult("-5I \ 10.0F", -5I \ 10.0F) PrintResult("-5I \ -11.0R", -5I \ -11.0R) PrintResult("-5I \ ""12""", -5I \ "12") PrintResult("-5I \ TypeCode.Double", -5I \ TypeCode.Double) PrintResult("26UI \ True", 26UI \ True) PrintResult("26UI \ System.SByte.MinValue", 26UI \ System.SByte.MinValue) PrintResult("26UI \ System.Byte.MaxValue", 26UI \ System.Byte.MaxValue) PrintResult("26UI \ -3S", 26UI \ -3S) PrintResult("26UI \ 24US", 26UI \ 24US) PrintResult("26UI \ -5I", 26UI \ -5I) PrintResult("26UI \ 26UI", 26UI \ 26UI) PrintResult("26UI \ -7L", 26UI \ -7L) PrintResult("26UI \ 28UL", 26UI \ 28UL) PrintResult("26UI \ -9D", 26UI \ -9D) PrintResult("26UI \ 10.0F", 26UI \ 10.0F) PrintResult("26UI \ -11.0R", 26UI \ -11.0R) PrintResult("26UI \ ""12""", 26UI \ "12") PrintResult("26UI \ TypeCode.Double", 26UI \ TypeCode.Double) PrintResult("-7L \ True", -7L \ True) PrintResult("-7L \ System.SByte.MinValue", -7L \ System.SByte.MinValue) PrintResult("-7L \ System.Byte.MaxValue", -7L \ System.Byte.MaxValue) PrintResult("-7L \ -3S", -7L \ -3S) PrintResult("-7L \ 24US", -7L \ 24US) PrintResult("-7L \ -5I", -7L \ -5I) PrintResult("-7L \ 26UI", -7L \ 26UI) PrintResult("-7L \ -7L", -7L \ -7L) PrintResult("-7L \ 28UL", -7L \ 28UL) PrintResult("-7L \ -9D", -7L \ -9D) PrintResult("-7L \ 10.0F", -7L \ 10.0F) PrintResult("-7L \ -11.0R", -7L \ -11.0R) PrintResult("-7L \ ""12""", -7L \ "12") PrintResult("-7L \ TypeCode.Double", -7L \ TypeCode.Double) PrintResult("28UL \ True", 28UL \ True) PrintResult("28UL \ System.SByte.MinValue", 28UL \ System.SByte.MinValue) PrintResult("28UL \ System.Byte.MaxValue", 28UL \ System.Byte.MaxValue) PrintResult("28UL \ -3S", 28UL \ -3S) PrintResult("28UL \ 24US", 28UL \ 24US) PrintResult("28UL \ -5I", 28UL \ -5I) PrintResult("28UL \ 26UI", 28UL \ 26UI) PrintResult("28UL \ -7L", 28UL \ -7L) PrintResult("28UL \ 28UL", 28UL \ 28UL) PrintResult("28UL \ -9D", 28UL \ -9D) PrintResult("28UL \ 10.0F", 28UL \ 10.0F) PrintResult("28UL \ -11.0R", 28UL \ -11.0R) PrintResult("28UL \ ""12""", 28UL \ "12") PrintResult("28UL \ TypeCode.Double", 28UL \ TypeCode.Double) PrintResult("-9D \ True", -9D \ True) PrintResult("-9D \ System.SByte.MinValue", -9D \ System.SByte.MinValue) PrintResult("-9D \ System.Byte.MaxValue", -9D \ System.Byte.MaxValue) PrintResult("-9D \ -3S", -9D \ -3S) PrintResult("-9D \ 24US", -9D \ 24US) PrintResult("-9D \ -5I", -9D \ -5I) PrintResult("-9D \ 26UI", -9D \ 26UI) PrintResult("-9D \ -7L", -9D \ -7L) PrintResult("-9D \ 28UL", -9D \ 28UL) PrintResult("-9D \ -9D", -9D \ -9D) PrintResult("-9D \ 10.0F", -9D \ 10.0F) PrintResult("-9D \ -11.0R", -9D \ -11.0R) PrintResult("-9D \ ""12""", -9D \ "12") PrintResult("-9D \ TypeCode.Double", -9D \ TypeCode.Double) PrintResult("10.0F \ True", 10.0F \ True) PrintResult("10.0F \ System.SByte.MinValue", 10.0F \ System.SByte.MinValue) PrintResult("10.0F \ System.Byte.MaxValue", 10.0F \ System.Byte.MaxValue) PrintResult("10.0F \ -3S", 10.0F \ -3S) PrintResult("10.0F \ 24US", 10.0F \ 24US) PrintResult("10.0F \ -5I", 10.0F \ -5I) PrintResult("10.0F \ 26UI", 10.0F \ 26UI) PrintResult("10.0F \ -7L", 10.0F \ -7L) PrintResult("10.0F \ 28UL", 10.0F \ 28UL) PrintResult("10.0F \ -9D", 10.0F \ -9D) PrintResult("10.0F \ 10.0F", 10.0F \ 10.0F) PrintResult("10.0F \ -11.0R", 10.0F \ -11.0R) PrintResult("10.0F \ ""12""", 10.0F \ "12") PrintResult("10.0F \ TypeCode.Double", 10.0F \ TypeCode.Double) PrintResult("-11.0R \ True", -11.0R \ True) PrintResult("-11.0R \ System.SByte.MinValue", -11.0R \ System.SByte.MinValue) PrintResult("-11.0R \ System.Byte.MaxValue", -11.0R \ System.Byte.MaxValue) PrintResult("-11.0R \ -3S", -11.0R \ -3S) PrintResult("-11.0R \ 24US", -11.0R \ 24US) PrintResult("-11.0R \ -5I", -11.0R \ -5I) PrintResult("-11.0R \ 26UI", -11.0R \ 26UI) PrintResult("-11.0R \ -7L", -11.0R \ -7L) PrintResult("-11.0R \ 28UL", -11.0R \ 28UL) PrintResult("-11.0R \ -9D", -11.0R \ -9D) PrintResult("-11.0R \ 10.0F", -11.0R \ 10.0F) PrintResult("-11.0R \ -11.0R", -11.0R \ -11.0R) PrintResult("-11.0R \ ""12""", -11.0R \ "12") PrintResult("-11.0R \ TypeCode.Double", -11.0R \ TypeCode.Double) PrintResult("""12"" \ True", "12" \ True) PrintResult("""12"" \ System.SByte.MinValue", "12" \ System.SByte.MinValue) PrintResult("""12"" \ System.Byte.MaxValue", "12" \ System.Byte.MaxValue) PrintResult("""12"" \ -3S", "12" \ -3S) PrintResult("""12"" \ 24US", "12" \ 24US) PrintResult("""12"" \ -5I", "12" \ -5I) PrintResult("""12"" \ 26UI", "12" \ 26UI) PrintResult("""12"" \ -7L", "12" \ -7L) PrintResult("""12"" \ 28UL", "12" \ 28UL) PrintResult("""12"" \ -9D", "12" \ -9D) PrintResult("""12"" \ 10.0F", "12" \ 10.0F) PrintResult("""12"" \ -11.0R", "12" \ -11.0R) PrintResult("""12"" \ ""12""", "12" \ "12") PrintResult("""12"" \ TypeCode.Double", "12" \ TypeCode.Double) PrintResult("TypeCode.Double \ True", TypeCode.Double \ True) PrintResult("TypeCode.Double \ System.SByte.MinValue", TypeCode.Double \ System.SByte.MinValue) PrintResult("TypeCode.Double \ System.Byte.MaxValue", TypeCode.Double \ System.Byte.MaxValue) PrintResult("TypeCode.Double \ -3S", TypeCode.Double \ -3S) PrintResult("TypeCode.Double \ 24US", TypeCode.Double \ 24US) PrintResult("TypeCode.Double \ -5I", TypeCode.Double \ -5I) PrintResult("TypeCode.Double \ 26UI", TypeCode.Double \ 26UI) PrintResult("TypeCode.Double \ -7L", TypeCode.Double \ -7L) PrintResult("TypeCode.Double \ 28UL", TypeCode.Double \ 28UL) PrintResult("TypeCode.Double \ -9D", TypeCode.Double \ -9D) PrintResult("TypeCode.Double \ 10.0F", TypeCode.Double \ 10.0F) PrintResult("TypeCode.Double \ -11.0R", TypeCode.Double \ -11.0R) PrintResult("TypeCode.Double \ ""12""", TypeCode.Double \ "12") PrintResult("TypeCode.Double \ TypeCode.Double", TypeCode.Double \ TypeCode.Double) PrintResult("False Mod True", False Mod True) PrintResult("False Mod System.SByte.MinValue", False Mod System.SByte.MinValue) PrintResult("False Mod System.Byte.MaxValue", False Mod System.Byte.MaxValue) PrintResult("False Mod -3S", False Mod -3S) PrintResult("False Mod 24US", False Mod 24US) PrintResult("False Mod -5I", False Mod -5I) PrintResult("False Mod 26UI", False Mod 26UI) PrintResult("False Mod -7L", False Mod -7L) PrintResult("False Mod 28UL", False Mod 28UL) PrintResult("False Mod -9D", False Mod -9D) PrintResult("False Mod 10.0F", False Mod 10.0F) PrintResult("False Mod -11.0R", False Mod -11.0R) PrintResult("False Mod ""12""", False Mod "12") PrintResult("False Mod TypeCode.Double", False Mod TypeCode.Double) PrintResult("True Mod True", True Mod True) PrintResult("True Mod System.SByte.MinValue", True Mod System.SByte.MinValue) PrintResult("True Mod System.Byte.MaxValue", True Mod System.Byte.MaxValue) PrintResult("True Mod -3S", True Mod -3S) PrintResult("True Mod 24US", True Mod 24US) PrintResult("True Mod -5I", True Mod -5I) PrintResult("True Mod 26UI", True Mod 26UI) PrintResult("True Mod -7L", True Mod -7L) PrintResult("True Mod 28UL", True Mod 28UL) PrintResult("True Mod -9D", True Mod -9D) PrintResult("True Mod 10.0F", True Mod 10.0F) PrintResult("True Mod -11.0R", True Mod -11.0R) PrintResult("True Mod ""12""", True Mod "12") PrintResult("True Mod TypeCode.Double", True Mod TypeCode.Double) PrintResult("System.SByte.MinValue Mod True", System.SByte.MinValue Mod True) PrintResult("System.SByte.MinValue Mod System.SByte.MinValue", System.SByte.MinValue Mod System.SByte.MinValue) PrintResult("System.SByte.MinValue Mod System.Byte.MaxValue", System.SByte.MinValue Mod System.Byte.MaxValue) PrintResult("System.SByte.MinValue Mod -3S", System.SByte.MinValue Mod -3S) PrintResult("System.SByte.MinValue Mod 24US", System.SByte.MinValue Mod 24US) PrintResult("System.SByte.MinValue Mod -5I", System.SByte.MinValue Mod -5I) PrintResult("System.SByte.MinValue Mod 26UI", System.SByte.MinValue Mod 26UI) PrintResult("System.SByte.MinValue Mod -7L", System.SByte.MinValue Mod -7L) PrintResult("System.SByte.MinValue Mod 28UL", System.SByte.MinValue Mod 28UL) PrintResult("System.SByte.MinValue Mod -9D", System.SByte.MinValue Mod -9D) PrintResult("System.SByte.MinValue Mod 10.0F", System.SByte.MinValue Mod 10.0F) PrintResult("System.SByte.MinValue Mod -11.0R", System.SByte.MinValue Mod -11.0R) PrintResult("System.SByte.MinValue Mod ""12""", System.SByte.MinValue Mod "12") PrintResult("System.SByte.MinValue Mod TypeCode.Double", System.SByte.MinValue Mod TypeCode.Double) PrintResult("System.Byte.MaxValue Mod True", System.Byte.MaxValue Mod True) PrintResult("System.Byte.MaxValue Mod System.SByte.MinValue", System.Byte.MaxValue Mod System.SByte.MinValue) PrintResult("System.Byte.MaxValue Mod System.Byte.MaxValue", System.Byte.MaxValue Mod System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Mod -3S", System.Byte.MaxValue Mod -3S) PrintResult("System.Byte.MaxValue Mod 24US", System.Byte.MaxValue Mod 24US) PrintResult("System.Byte.MaxValue Mod -5I", System.Byte.MaxValue Mod -5I) PrintResult("System.Byte.MaxValue Mod 26UI", System.Byte.MaxValue Mod 26UI) PrintResult("System.Byte.MaxValue Mod -7L", System.Byte.MaxValue Mod -7L) PrintResult("System.Byte.MaxValue Mod 28UL", System.Byte.MaxValue Mod 28UL) PrintResult("System.Byte.MaxValue Mod -9D", System.Byte.MaxValue Mod -9D) PrintResult("System.Byte.MaxValue Mod 10.0F", System.Byte.MaxValue Mod 10.0F) PrintResult("System.Byte.MaxValue Mod -11.0R", System.Byte.MaxValue Mod -11.0R) PrintResult("System.Byte.MaxValue Mod ""12""", System.Byte.MaxValue Mod "12") PrintResult("System.Byte.MaxValue Mod TypeCode.Double", System.Byte.MaxValue Mod TypeCode.Double) PrintResult("-3S Mod True", -3S Mod True) PrintResult("-3S Mod System.SByte.MinValue", -3S Mod System.SByte.MinValue) PrintResult("-3S Mod System.Byte.MaxValue", -3S Mod System.Byte.MaxValue) PrintResult("-3S Mod -3S", -3S Mod -3S) PrintResult("-3S Mod 24US", -3S Mod 24US) PrintResult("-3S Mod -5I", -3S Mod -5I) PrintResult("-3S Mod 26UI", -3S Mod 26UI) PrintResult("-3S Mod -7L", -3S Mod -7L) PrintResult("-3S Mod 28UL", -3S Mod 28UL) PrintResult("-3S Mod -9D", -3S Mod -9D) PrintResult("-3S Mod 10.0F", -3S Mod 10.0F) PrintResult("-3S Mod -11.0R", -3S Mod -11.0R) PrintResult("-3S Mod ""12""", -3S Mod "12") PrintResult("-3S Mod TypeCode.Double", -3S Mod TypeCode.Double) PrintResult("24US Mod True", 24US Mod True) PrintResult("24US Mod System.SByte.MinValue", 24US Mod System.SByte.MinValue) PrintResult("24US Mod System.Byte.MaxValue", 24US Mod System.Byte.MaxValue) PrintResult("24US Mod -3S", 24US Mod -3S) PrintResult("24US Mod 24US", 24US Mod 24US) PrintResult("24US Mod -5I", 24US Mod -5I) PrintResult("24US Mod 26UI", 24US Mod 26UI) PrintResult("24US Mod -7L", 24US Mod -7L) PrintResult("24US Mod 28UL", 24US Mod 28UL) PrintResult("24US Mod -9D", 24US Mod -9D) PrintResult("24US Mod 10.0F", 24US Mod 10.0F) PrintResult("24US Mod -11.0R", 24US Mod -11.0R) PrintResult("24US Mod ""12""", 24US Mod "12") PrintResult("24US Mod TypeCode.Double", 24US Mod TypeCode.Double) PrintResult("-5I Mod True", -5I Mod True) PrintResult("-5I Mod System.SByte.MinValue", -5I Mod System.SByte.MinValue) PrintResult("-5I Mod System.Byte.MaxValue", -5I Mod System.Byte.MaxValue) PrintResult("-5I Mod -3S", -5I Mod -3S) PrintResult("-5I Mod 24US", -5I Mod 24US) PrintResult("-5I Mod -5I", -5I Mod -5I) PrintResult("-5I Mod 26UI", -5I Mod 26UI) PrintResult("-5I Mod -7L", -5I Mod -7L) PrintResult("-5I Mod 28UL", -5I Mod 28UL) PrintResult("-5I Mod -9D", -5I Mod -9D) PrintResult("-5I Mod 10.0F", -5I Mod 10.0F) PrintResult("-5I Mod -11.0R", -5I Mod -11.0R) PrintResult("-5I Mod ""12""", -5I Mod "12") PrintResult("-5I Mod TypeCode.Double", -5I Mod TypeCode.Double) PrintResult("26UI Mod True", 26UI Mod True) PrintResult("26UI Mod System.SByte.MinValue", 26UI Mod System.SByte.MinValue) PrintResult("26UI Mod System.Byte.MaxValue", 26UI Mod System.Byte.MaxValue) PrintResult("26UI Mod -3S", 26UI Mod -3S) PrintResult("26UI Mod 24US", 26UI Mod 24US) PrintResult("26UI Mod -5I", 26UI Mod -5I) PrintResult("26UI Mod 26UI", 26UI Mod 26UI) PrintResult("26UI Mod -7L", 26UI Mod -7L) PrintResult("26UI Mod 28UL", 26UI Mod 28UL) PrintResult("26UI Mod -9D", 26UI Mod -9D) PrintResult("26UI Mod 10.0F", 26UI Mod 10.0F) PrintResult("26UI Mod -11.0R", 26UI Mod -11.0R) PrintResult("26UI Mod ""12""", 26UI Mod "12") PrintResult("26UI Mod TypeCode.Double", 26UI Mod TypeCode.Double) PrintResult("-7L Mod True", -7L Mod True) PrintResult("-7L Mod System.SByte.MinValue", -7L Mod System.SByte.MinValue) PrintResult("-7L Mod System.Byte.MaxValue", -7L Mod System.Byte.MaxValue) PrintResult("-7L Mod -3S", -7L Mod -3S) PrintResult("-7L Mod 24US", -7L Mod 24US) PrintResult("-7L Mod -5I", -7L Mod -5I) PrintResult("-7L Mod 26UI", -7L Mod 26UI) PrintResult("-7L Mod -7L", -7L Mod -7L) PrintResult("-7L Mod 28UL", -7L Mod 28UL) PrintResult("-7L Mod -9D", -7L Mod -9D) PrintResult("-7L Mod 10.0F", -7L Mod 10.0F) PrintResult("-7L Mod -11.0R", -7L Mod -11.0R) PrintResult("-7L Mod ""12""", -7L Mod "12") PrintResult("-7L Mod TypeCode.Double", -7L Mod TypeCode.Double) PrintResult("28UL Mod True", 28UL Mod True) PrintResult("28UL Mod System.SByte.MinValue", 28UL Mod System.SByte.MinValue) PrintResult("28UL Mod System.Byte.MaxValue", 28UL Mod System.Byte.MaxValue) PrintResult("28UL Mod -3S", 28UL Mod -3S) PrintResult("28UL Mod 24US", 28UL Mod 24US) PrintResult("28UL Mod -5I", 28UL Mod -5I) PrintResult("28UL Mod 26UI", 28UL Mod 26UI) PrintResult("28UL Mod -7L", 28UL Mod -7L) PrintResult("28UL Mod 28UL", 28UL Mod 28UL) PrintResult("28UL Mod -9D", 28UL Mod -9D) PrintResult("28UL Mod 10.0F", 28UL Mod 10.0F) PrintResult("28UL Mod -11.0R", 28UL Mod -11.0R) PrintResult("28UL Mod ""12""", 28UL Mod "12") PrintResult("28UL Mod TypeCode.Double", 28UL Mod TypeCode.Double) PrintResult("-9D Mod True", -9D Mod True) PrintResult("-9D Mod System.SByte.MinValue", -9D Mod System.SByte.MinValue) PrintResult("-9D Mod System.Byte.MaxValue", -9D Mod System.Byte.MaxValue) PrintResult("-9D Mod -3S", -9D Mod -3S) PrintResult("-9D Mod 24US", -9D Mod 24US) PrintResult("-9D Mod -5I", -9D Mod -5I) PrintResult("-9D Mod 26UI", -9D Mod 26UI) PrintResult("-9D Mod -7L", -9D Mod -7L) PrintResult("-9D Mod 28UL", -9D Mod 28UL) PrintResult("-9D Mod -9D", -9D Mod -9D) PrintResult("-9D Mod 10.0F", -9D Mod 10.0F) PrintResult("-9D Mod -11.0R", -9D Mod -11.0R) PrintResult("-9D Mod ""12""", -9D Mod "12") PrintResult("-9D Mod TypeCode.Double", -9D Mod TypeCode.Double) PrintResult("10.0F Mod True", 10.0F Mod True) PrintResult("10.0F Mod System.SByte.MinValue", 10.0F Mod System.SByte.MinValue) PrintResult("10.0F Mod System.Byte.MaxValue", 10.0F Mod System.Byte.MaxValue) PrintResult("10.0F Mod -3S", 10.0F Mod -3S) PrintResult("10.0F Mod 24US", 10.0F Mod 24US) PrintResult("10.0F Mod -5I", 10.0F Mod -5I) PrintResult("10.0F Mod 26UI", 10.0F Mod 26UI) PrintResult("10.0F Mod -7L", 10.0F Mod -7L) PrintResult("10.0F Mod 28UL", 10.0F Mod 28UL) PrintResult("10.0F Mod -9D", 10.0F Mod -9D) PrintResult("10.0F Mod 10.0F", 10.0F Mod 10.0F) PrintResult("10.0F Mod -11.0R", 10.0F Mod -11.0R) PrintResult("10.0F Mod ""12""", 10.0F Mod "12") PrintResult("10.0F Mod TypeCode.Double", 10.0F Mod TypeCode.Double) PrintResult("-11.0R Mod True", -11.0R Mod True) PrintResult("-11.0R Mod System.SByte.MinValue", -11.0R Mod System.SByte.MinValue) PrintResult("-11.0R Mod System.Byte.MaxValue", -11.0R Mod System.Byte.MaxValue) PrintResult("-11.0R Mod -3S", -11.0R Mod -3S) PrintResult("-11.0R Mod 24US", -11.0R Mod 24US) PrintResult("-11.0R Mod -5I", -11.0R Mod -5I) PrintResult("-11.0R Mod 26UI", -11.0R Mod 26UI) PrintResult("-11.0R Mod -7L", -11.0R Mod -7L) PrintResult("-11.0R Mod 28UL", -11.0R Mod 28UL) PrintResult("-11.0R Mod -9D", -11.0R Mod -9D) PrintResult("-11.0R Mod 10.0F", -11.0R Mod 10.0F) PrintResult("-11.0R Mod -11.0R", -11.0R Mod -11.0R) PrintResult("-11.0R Mod ""12""", -11.0R Mod "12") PrintResult("-11.0R Mod TypeCode.Double", -11.0R Mod TypeCode.Double) PrintResult("""12"" Mod True", "12" Mod True) PrintResult("""12"" Mod System.SByte.MinValue", "12" Mod System.SByte.MinValue) PrintResult("""12"" Mod System.Byte.MaxValue", "12" Mod System.Byte.MaxValue) PrintResult("""12"" Mod -3S", "12" Mod -3S) PrintResult("""12"" Mod 24US", "12" Mod 24US) PrintResult("""12"" Mod -5I", "12" Mod -5I) PrintResult("""12"" Mod 26UI", "12" Mod 26UI) PrintResult("""12"" Mod -7L", "12" Mod -7L) PrintResult("""12"" Mod 28UL", "12" Mod 28UL) PrintResult("""12"" Mod -9D", "12" Mod -9D) PrintResult("""12"" Mod 10.0F", "12" Mod 10.0F) PrintResult("""12"" Mod -11.0R", "12" Mod -11.0R) PrintResult("""12"" Mod ""12""", "12" Mod "12") PrintResult("""12"" Mod TypeCode.Double", "12" Mod TypeCode.Double) PrintResult("TypeCode.Double Mod True", TypeCode.Double Mod True) PrintResult("TypeCode.Double Mod System.SByte.MinValue", TypeCode.Double Mod System.SByte.MinValue) PrintResult("TypeCode.Double Mod System.Byte.MaxValue", TypeCode.Double Mod System.Byte.MaxValue) PrintResult("TypeCode.Double Mod -3S", TypeCode.Double Mod -3S) PrintResult("TypeCode.Double Mod 24US", TypeCode.Double Mod 24US) PrintResult("TypeCode.Double Mod -5I", TypeCode.Double Mod -5I) PrintResult("TypeCode.Double Mod 26UI", TypeCode.Double Mod 26UI) PrintResult("TypeCode.Double Mod -7L", TypeCode.Double Mod -7L) PrintResult("TypeCode.Double Mod 28UL", TypeCode.Double Mod 28UL) PrintResult("TypeCode.Double Mod -9D", TypeCode.Double Mod -9D) PrintResult("TypeCode.Double Mod 10.0F", TypeCode.Double Mod 10.0F) PrintResult("TypeCode.Double Mod -11.0R", TypeCode.Double Mod -11.0R) PrintResult("TypeCode.Double Mod ""12""", TypeCode.Double Mod "12") PrintResult("TypeCode.Double Mod TypeCode.Double", TypeCode.Double Mod TypeCode.Double) PrintResult("False ^ False", False ^ False) PrintResult("False ^ True", False ^ True) PrintResult("False ^ System.SByte.MinValue", False ^ System.SByte.MinValue) PrintResult("False ^ System.Byte.MaxValue", False ^ System.Byte.MaxValue) PrintResult("False ^ -3S", False ^ -3S) PrintResult("False ^ 24US", False ^ 24US) PrintResult("False ^ -5I", False ^ -5I) PrintResult("False ^ 26UI", False ^ 26UI) PrintResult("False ^ -7L", False ^ -7L) PrintResult("False ^ 28UL", False ^ 28UL) PrintResult("False ^ -9D", False ^ -9D) PrintResult("False ^ 10.0F", False ^ 10.0F) PrintResult("False ^ -11.0R", False ^ -11.0R) PrintResult("False ^ ""12""", False ^ "12") PrintResult("False ^ TypeCode.Double", False ^ TypeCode.Double) PrintResult("True ^ False", True ^ False) PrintResult("True ^ True", True ^ True) PrintResult("True ^ System.SByte.MinValue", True ^ System.SByte.MinValue) PrintResult("True ^ System.Byte.MaxValue", True ^ System.Byte.MaxValue) PrintResult("True ^ -3S", True ^ -3S) PrintResult("True ^ 24US", True ^ 24US) PrintResult("True ^ -5I", True ^ -5I) PrintResult("True ^ 26UI", True ^ 26UI) PrintResult("True ^ -7L", True ^ -7L) PrintResult("True ^ 28UL", True ^ 28UL) PrintResult("True ^ -9D", True ^ -9D) PrintResult("True ^ 10.0F", True ^ 10.0F) PrintResult("True ^ -11.0R", True ^ -11.0R) PrintResult("True ^ ""12""", True ^ "12") PrintResult("True ^ TypeCode.Double", True ^ TypeCode.Double) PrintResult("System.SByte.MinValue ^ False", System.SByte.MinValue ^ False) PrintResult("System.SByte.MinValue ^ True", System.SByte.MinValue ^ True) PrintResult("System.SByte.MinValue ^ System.SByte.MinValue", System.SByte.MinValue ^ System.SByte.MinValue) PrintResult("System.SByte.MinValue ^ System.Byte.MaxValue", System.SByte.MinValue ^ System.Byte.MaxValue) PrintResult("System.SByte.MinValue ^ -3S", System.SByte.MinValue ^ -3S) PrintResult("System.SByte.MinValue ^ 24US", System.SByte.MinValue ^ 24US) PrintResult("System.SByte.MinValue ^ -5I", System.SByte.MinValue ^ -5I) PrintResult("System.SByte.MinValue ^ 26UI", System.SByte.MinValue ^ 26UI) PrintResult("System.SByte.MinValue ^ -7L", System.SByte.MinValue ^ -7L) PrintResult("System.SByte.MinValue ^ 28UL", System.SByte.MinValue ^ 28UL) PrintResult("System.SByte.MinValue ^ -9D", System.SByte.MinValue ^ -9D) PrintResult("System.SByte.MinValue ^ 10.0F", System.SByte.MinValue ^ 10.0F) PrintResult("System.SByte.MinValue ^ -11.0R", System.SByte.MinValue ^ -11.0R) PrintResult("System.SByte.MinValue ^ ""12""", System.SByte.MinValue ^ "12") PrintResult("System.SByte.MinValue ^ TypeCode.Double", System.SByte.MinValue ^ TypeCode.Double) PrintResult("System.Byte.MaxValue ^ False", System.Byte.MaxValue ^ False) PrintResult("System.Byte.MaxValue ^ True", System.Byte.MaxValue ^ True) PrintResult("System.Byte.MaxValue ^ System.SByte.MinValue", System.Byte.MaxValue ^ System.SByte.MinValue) PrintResult("System.Byte.MaxValue ^ System.Byte.MaxValue", System.Byte.MaxValue ^ System.Byte.MaxValue) PrintResult("System.Byte.MaxValue ^ -3S", System.Byte.MaxValue ^ -3S) PrintResult("System.Byte.MaxValue ^ 24US", System.Byte.MaxValue ^ 24US) PrintResult("System.Byte.MaxValue ^ -5I", System.Byte.MaxValue ^ -5I) PrintResult("System.Byte.MaxValue ^ 26UI", System.Byte.MaxValue ^ 26UI) PrintResult("System.Byte.MaxValue ^ -7L", System.Byte.MaxValue ^ -7L) PrintResult("System.Byte.MaxValue ^ 28UL", System.Byte.MaxValue ^ 28UL) PrintResult("System.Byte.MaxValue ^ -9D", System.Byte.MaxValue ^ -9D) PrintResult("System.Byte.MaxValue ^ 10.0F", System.Byte.MaxValue ^ 10.0F) PrintResult("System.Byte.MaxValue ^ -11.0R", System.Byte.MaxValue ^ -11.0R) PrintResult("System.Byte.MaxValue ^ ""12""", System.Byte.MaxValue ^ "12") PrintResult("System.Byte.MaxValue ^ TypeCode.Double", System.Byte.MaxValue ^ TypeCode.Double) PrintResult("-3S ^ False", -3S ^ False) PrintResult("-3S ^ True", -3S ^ True) PrintResult("-3S ^ System.SByte.MinValue", -3S ^ System.SByte.MinValue) PrintResult("-3S ^ System.Byte.MaxValue", -3S ^ System.Byte.MaxValue) PrintResult("-3S ^ -3S", -3S ^ -3S) PrintResult("-3S ^ 24US", -3S ^ 24US) PrintResult("-3S ^ -5I", -3S ^ -5I) PrintResult("-3S ^ 26UI", -3S ^ 26UI) PrintResult("-3S ^ -7L", -3S ^ -7L) PrintResult("-3S ^ 28UL", -3S ^ 28UL) PrintResult("-3S ^ -9D", -3S ^ -9D) PrintResult("-3S ^ 10.0F", -3S ^ 10.0F) PrintResult("-3S ^ -11.0R", -3S ^ -11.0R) PrintResult("-3S ^ ""12""", -3S ^ "12") PrintResult("-3S ^ TypeCode.Double", -3S ^ TypeCode.Double) PrintResult("24US ^ False", 24US ^ False) PrintResult("24US ^ True", 24US ^ True) PrintResult("24US ^ System.SByte.MinValue", 24US ^ System.SByte.MinValue) PrintResult("24US ^ System.Byte.MaxValue", 24US ^ System.Byte.MaxValue) PrintResult("24US ^ -3S", 24US ^ -3S) PrintResult("24US ^ 24US", 24US ^ 24US) PrintResult("24US ^ -5I", 24US ^ -5I) PrintResult("24US ^ 26UI", 24US ^ 26UI) PrintResult("24US ^ -7L", 24US ^ -7L) PrintResult("24US ^ 28UL", 24US ^ 28UL) PrintResult("24US ^ -9D", 24US ^ -9D) PrintResult("24US ^ 10.0F", 24US ^ 10.0F) PrintResult("24US ^ -11.0R", 24US ^ -11.0R) PrintResult("24US ^ ""12""", 24US ^ "12") PrintResult("24US ^ TypeCode.Double", 24US ^ TypeCode.Double) PrintResult("-5I ^ False", -5I ^ False) PrintResult("-5I ^ True", -5I ^ True) PrintResult("-5I ^ System.SByte.MinValue", -5I ^ System.SByte.MinValue) PrintResult("-5I ^ System.Byte.MaxValue", -5I ^ System.Byte.MaxValue) PrintResult("-5I ^ -3S", -5I ^ -3S) PrintResult("-5I ^ 24US", -5I ^ 24US) PrintResult("-5I ^ -5I", -5I ^ -5I) PrintResult("-5I ^ 26UI", -5I ^ 26UI) PrintResult("-5I ^ -7L", -5I ^ -7L) PrintResult("-5I ^ 28UL", -5I ^ 28UL) PrintResult("-5I ^ -9D", -5I ^ -9D) PrintResult("-5I ^ 10.0F", -5I ^ 10.0F) PrintResult("-5I ^ -11.0R", -5I ^ -11.0R) PrintResult("-5I ^ ""12""", -5I ^ "12") PrintResult("-5I ^ TypeCode.Double", -5I ^ TypeCode.Double) PrintResult("26UI ^ False", 26UI ^ False) PrintResult("26UI ^ True", 26UI ^ True) PrintResult("26UI ^ System.SByte.MinValue", 26UI ^ System.SByte.MinValue) PrintResult("26UI ^ System.Byte.MaxValue", 26UI ^ System.Byte.MaxValue) PrintResult("26UI ^ -3S", 26UI ^ -3S) PrintResult("26UI ^ 24US", 26UI ^ 24US) PrintResult("26UI ^ -5I", 26UI ^ -5I) PrintResult("26UI ^ 26UI", 26UI ^ 26UI) PrintResult("26UI ^ -7L", 26UI ^ -7L) PrintResult("26UI ^ 28UL", 26UI ^ 28UL) PrintResult("26UI ^ -9D", 26UI ^ -9D) PrintResult("26UI ^ 10.0F", 26UI ^ 10.0F) PrintResult("26UI ^ -11.0R", 26UI ^ -11.0R) PrintResult("26UI ^ ""12""", 26UI ^ "12") PrintResult("26UI ^ TypeCode.Double", 26UI ^ TypeCode.Double) PrintResult("-7L ^ False", -7L ^ False) PrintResult("-7L ^ True", -7L ^ True) PrintResult("-7L ^ System.SByte.MinValue", -7L ^ System.SByte.MinValue) PrintResult("-7L ^ System.Byte.MaxValue", -7L ^ System.Byte.MaxValue) PrintResult("-7L ^ -3S", -7L ^ -3S) PrintResult("-7L ^ 24US", -7L ^ 24US) PrintResult("-7L ^ -5I", -7L ^ -5I) PrintResult("-7L ^ 26UI", -7L ^ 26UI) PrintResult("-7L ^ -7L", -7L ^ -7L) PrintResult("-7L ^ 28UL", -7L ^ 28UL) PrintResult("-7L ^ -9D", -7L ^ -9D) PrintResult("-7L ^ 10.0F", -7L ^ 10.0F) PrintResult("-7L ^ -11.0R", -7L ^ -11.0R) PrintResult("-7L ^ ""12""", -7L ^ "12") PrintResult("-7L ^ TypeCode.Double", -7L ^ TypeCode.Double) PrintResult("28UL ^ False", 28UL ^ False) PrintResult("28UL ^ True", 28UL ^ True) PrintResult("28UL ^ System.SByte.MinValue", 28UL ^ System.SByte.MinValue) PrintResult("28UL ^ System.Byte.MaxValue", 28UL ^ System.Byte.MaxValue) PrintResult("28UL ^ -3S", 28UL ^ -3S) PrintResult("28UL ^ 24US", 28UL ^ 24US) PrintResult("28UL ^ -5I", 28UL ^ -5I) PrintResult("28UL ^ 26UI", 28UL ^ 26UI) PrintResult("28UL ^ -7L", 28UL ^ -7L) PrintResult("28UL ^ 28UL", 28UL ^ 28UL) PrintResult("28UL ^ -9D", 28UL ^ -9D) PrintResult("28UL ^ 10.0F", 28UL ^ 10.0F) PrintResult("28UL ^ -11.0R", 28UL ^ -11.0R) PrintResult("28UL ^ ""12""", 28UL ^ "12") PrintResult("28UL ^ TypeCode.Double", 28UL ^ TypeCode.Double) PrintResult("-9D ^ False", -9D ^ False) PrintResult("-9D ^ True", -9D ^ True) PrintResult("-9D ^ System.SByte.MinValue", -9D ^ System.SByte.MinValue) PrintResult("-9D ^ System.Byte.MaxValue", -9D ^ System.Byte.MaxValue) PrintResult("-9D ^ -3S", -9D ^ -3S) PrintResult("-9D ^ 24US", -9D ^ 24US) PrintResult("-9D ^ -5I", -9D ^ -5I) PrintResult("-9D ^ 26UI", -9D ^ 26UI) PrintResult("-9D ^ -7L", -9D ^ -7L) PrintResult("-9D ^ 28UL", -9D ^ 28UL) PrintResult("-9D ^ -9D", -9D ^ -9D) PrintResult("-9D ^ 10.0F", -9D ^ 10.0F) PrintResult("-9D ^ -11.0R", -9D ^ -11.0R) PrintResult("-9D ^ ""12""", -9D ^ "12") PrintResult("-9D ^ TypeCode.Double", -9D ^ TypeCode.Double) PrintResult("10.0F ^ False", 10.0F ^ False) PrintResult("10.0F ^ True", 10.0F ^ True) PrintResult("10.0F ^ System.SByte.MinValue", 10.0F ^ System.SByte.MinValue) PrintResult("10.0F ^ System.Byte.MaxValue", 10.0F ^ System.Byte.MaxValue) PrintResult("10.0F ^ -3S", 10.0F ^ -3S) PrintResult("10.0F ^ 24US", 10.0F ^ 24US) PrintResult("10.0F ^ -5I", 10.0F ^ -5I) PrintResult("10.0F ^ 26UI", 10.0F ^ 26UI) PrintResult("10.0F ^ -7L", 10.0F ^ -7L) PrintResult("10.0F ^ 28UL", 10.0F ^ 28UL) PrintResult("10.0F ^ -9D", 10.0F ^ -9D) PrintResult("10.0F ^ 10.0F", 10.0F ^ 10.0F) PrintResult("10.0F ^ -11.0R", 10.0F ^ -11.0R) PrintResult("10.0F ^ ""12""", 10.0F ^ "12") PrintResult("10.0F ^ TypeCode.Double", 10.0F ^ TypeCode.Double) PrintResult("-11.0R ^ False", -11.0R ^ False) PrintResult("-11.0R ^ True", -11.0R ^ True) PrintResult("-11.0R ^ System.SByte.MinValue", -11.0R ^ System.SByte.MinValue) PrintResult("-11.0R ^ System.Byte.MaxValue", -11.0R ^ System.Byte.MaxValue) PrintResult("-11.0R ^ -3S", -11.0R ^ -3S) PrintResult("-11.0R ^ 24US", -11.0R ^ 24US) PrintResult("-11.0R ^ -5I", -11.0R ^ -5I) PrintResult("-11.0R ^ 26UI", -11.0R ^ 26UI) PrintResult("-11.0R ^ -7L", -11.0R ^ -7L) PrintResult("-11.0R ^ 28UL", -11.0R ^ 28UL) PrintResult("-11.0R ^ -9D", -11.0R ^ -9D) PrintResult("-11.0R ^ 10.0F", -11.0R ^ 10.0F) PrintResult("-11.0R ^ -11.0R", -11.0R ^ -11.0R) PrintResult("-11.0R ^ ""12""", -11.0R ^ "12") PrintResult("-11.0R ^ TypeCode.Double", -11.0R ^ TypeCode.Double) PrintResult("""12"" ^ False", "12" ^ False) PrintResult("""12"" ^ True", "12" ^ True) PrintResult("""12"" ^ System.SByte.MinValue", "12" ^ System.SByte.MinValue) PrintResult("""12"" ^ System.Byte.MaxValue", "12" ^ System.Byte.MaxValue) PrintResult("""12"" ^ -3S", "12" ^ -3S) PrintResult("""12"" ^ 24US", "12" ^ 24US) PrintResult("""12"" ^ -5I", "12" ^ -5I) PrintResult("""12"" ^ 26UI", "12" ^ 26UI) PrintResult("""12"" ^ -7L", "12" ^ -7L) PrintResult("""12"" ^ 28UL", "12" ^ 28UL) PrintResult("""12"" ^ -9D", "12" ^ -9D) PrintResult("""12"" ^ 10.0F", "12" ^ 10.0F) PrintResult("""12"" ^ -11.0R", "12" ^ -11.0R) PrintResult("""12"" ^ ""12""", "12" ^ "12") PrintResult("""12"" ^ TypeCode.Double", "12" ^ TypeCode.Double) PrintResult("TypeCode.Double ^ False", TypeCode.Double ^ False) PrintResult("TypeCode.Double ^ True", TypeCode.Double ^ True) PrintResult("TypeCode.Double ^ System.SByte.MinValue", TypeCode.Double ^ System.SByte.MinValue) PrintResult("TypeCode.Double ^ System.Byte.MaxValue", TypeCode.Double ^ System.Byte.MaxValue) PrintResult("TypeCode.Double ^ -3S", TypeCode.Double ^ -3S) PrintResult("TypeCode.Double ^ 24US", TypeCode.Double ^ 24US) PrintResult("TypeCode.Double ^ -5I", TypeCode.Double ^ -5I) PrintResult("TypeCode.Double ^ 26UI", TypeCode.Double ^ 26UI) PrintResult("TypeCode.Double ^ -7L", TypeCode.Double ^ -7L) PrintResult("TypeCode.Double ^ 28UL", TypeCode.Double ^ 28UL) PrintResult("TypeCode.Double ^ -9D", TypeCode.Double ^ -9D) PrintResult("TypeCode.Double ^ 10.0F", TypeCode.Double ^ 10.0F) PrintResult("TypeCode.Double ^ -11.0R", TypeCode.Double ^ -11.0R) PrintResult("TypeCode.Double ^ ""12""", TypeCode.Double ^ "12") PrintResult("TypeCode.Double ^ TypeCode.Double", TypeCode.Double ^ TypeCode.Double) PrintResult("False << False", False << False) PrintResult("False << True", False << True) PrintResult("False << System.SByte.MinValue", False << System.SByte.MinValue) PrintResult("False << System.Byte.MaxValue", False << System.Byte.MaxValue) PrintResult("False << -3S", False << -3S) PrintResult("False << 24US", False << 24US) PrintResult("False << -5I", False << -5I) PrintResult("False << 26UI", False << 26UI) PrintResult("False << -7L", False << -7L) PrintResult("False << 28UL", False << 28UL) PrintResult("False << -9D", False << -9D) PrintResult("False << 10.0F", False << 10.0F) PrintResult("False << -11.0R", False << -11.0R) PrintResult("False << ""12""", False << "12") PrintResult("False << TypeCode.Double", False << TypeCode.Double) PrintResult("True << False", True << False) PrintResult("True << True", True << True) PrintResult("True << System.SByte.MinValue", True << System.SByte.MinValue) PrintResult("True << System.Byte.MaxValue", True << System.Byte.MaxValue) PrintResult("True << -3S", True << -3S) PrintResult("True << 24US", True << 24US) PrintResult("True << -5I", True << -5I) PrintResult("True << 26UI", True << 26UI) PrintResult("True << -7L", True << -7L) PrintResult("True << 28UL", True << 28UL) PrintResult("True << -9D", True << -9D) PrintResult("True << 10.0F", True << 10.0F) PrintResult("True << -11.0R", True << -11.0R) PrintResult("True << ""12""", True << "12") PrintResult("True << TypeCode.Double", True << TypeCode.Double) PrintResult("System.SByte.MinValue << False", System.SByte.MinValue << False) PrintResult("System.SByte.MinValue << True", System.SByte.MinValue << True) PrintResult("System.SByte.MinValue << System.SByte.MinValue", System.SByte.MinValue << System.SByte.MinValue) PrintResult("System.SByte.MinValue << System.Byte.MaxValue", System.SByte.MinValue << System.Byte.MaxValue) PrintResult("System.SByte.MinValue << -3S", System.SByte.MinValue << -3S) PrintResult("System.SByte.MinValue << 24US", System.SByte.MinValue << 24US) PrintResult("System.SByte.MinValue << -5I", System.SByte.MinValue << -5I) PrintResult("System.SByte.MinValue << 26UI", System.SByte.MinValue << 26UI) PrintResult("System.SByte.MinValue << -7L", System.SByte.MinValue << -7L) PrintResult("System.SByte.MinValue << 28UL", System.SByte.MinValue << 28UL) PrintResult("System.SByte.MinValue << -9D", System.SByte.MinValue << -9D) PrintResult("System.SByte.MinValue << 10.0F", System.SByte.MinValue << 10.0F) PrintResult("System.SByte.MinValue << -11.0R", System.SByte.MinValue << -11.0R) PrintResult("System.SByte.MinValue << ""12""", System.SByte.MinValue << "12") PrintResult("System.SByte.MinValue << TypeCode.Double", System.SByte.MinValue << TypeCode.Double) PrintResult("System.Byte.MaxValue << False", System.Byte.MaxValue << False) PrintResult("System.Byte.MaxValue << True", System.Byte.MaxValue << True) PrintResult("System.Byte.MaxValue << System.SByte.MinValue", System.Byte.MaxValue << System.SByte.MinValue) PrintResult("System.Byte.MaxValue << System.Byte.MaxValue", System.Byte.MaxValue << System.Byte.MaxValue) PrintResult("System.Byte.MaxValue << -3S", System.Byte.MaxValue << -3S) PrintResult("System.Byte.MaxValue << 24US", System.Byte.MaxValue << 24US) PrintResult("System.Byte.MaxValue << -5I", System.Byte.MaxValue << -5I) PrintResult("System.Byte.MaxValue << 26UI", System.Byte.MaxValue << 26UI) PrintResult("System.Byte.MaxValue << -7L", System.Byte.MaxValue << -7L) PrintResult("System.Byte.MaxValue << 28UL", System.Byte.MaxValue << 28UL) PrintResult("System.Byte.MaxValue << -9D", System.Byte.MaxValue << -9D) PrintResult("System.Byte.MaxValue << 10.0F", System.Byte.MaxValue << 10.0F) PrintResult("System.Byte.MaxValue << -11.0R", System.Byte.MaxValue << -11.0R) PrintResult("System.Byte.MaxValue << ""12""", System.Byte.MaxValue << "12") PrintResult("System.Byte.MaxValue << TypeCode.Double", System.Byte.MaxValue << TypeCode.Double) PrintResult("-3S << False", -3S << False) PrintResult("-3S << True", -3S << True) PrintResult("-3S << System.SByte.MinValue", -3S << System.SByte.MinValue) PrintResult("-3S << System.Byte.MaxValue", -3S << System.Byte.MaxValue) PrintResult("-3S << -3S", -3S << -3S) PrintResult("-3S << 24US", -3S << 24US) PrintResult("-3S << -5I", -3S << -5I) PrintResult("-3S << 26UI", -3S << 26UI) PrintResult("-3S << -7L", -3S << -7L) PrintResult("-3S << 28UL", -3S << 28UL) PrintResult("-3S << -9D", -3S << -9D) PrintResult("-3S << 10.0F", -3S << 10.0F) PrintResult("-3S << -11.0R", -3S << -11.0R) PrintResult("-3S << ""12""", -3S << "12") PrintResult("-3S << TypeCode.Double", -3S << TypeCode.Double) PrintResult("24US << False", 24US << False) PrintResult("24US << True", 24US << True) PrintResult("24US << System.SByte.MinValue", 24US << System.SByte.MinValue) PrintResult("24US << System.Byte.MaxValue", 24US << System.Byte.MaxValue) PrintResult("24US << -3S", 24US << -3S) PrintResult("24US << 24US", 24US << 24US) PrintResult("24US << -5I", 24US << -5I) PrintResult("24US << 26UI", 24US << 26UI) PrintResult("24US << -7L", 24US << -7L) PrintResult("24US << 28UL", 24US << 28UL) PrintResult("24US << -9D", 24US << -9D) PrintResult("24US << 10.0F", 24US << 10.0F) PrintResult("24US << -11.0R", 24US << -11.0R) PrintResult("24US << ""12""", 24US << "12") PrintResult("24US << TypeCode.Double", 24US << TypeCode.Double) PrintResult("-5I << False", -5I << False) PrintResult("-5I << True", -5I << True) PrintResult("-5I << System.SByte.MinValue", -5I << System.SByte.MinValue) PrintResult("-5I << System.Byte.MaxValue", -5I << System.Byte.MaxValue) PrintResult("-5I << -3S", -5I << -3S) PrintResult("-5I << 24US", -5I << 24US) PrintResult("-5I << -5I", -5I << -5I) PrintResult("-5I << 26UI", -5I << 26UI) PrintResult("-5I << -7L", -5I << -7L) PrintResult("-5I << 28UL", -5I << 28UL) PrintResult("-5I << -9D", -5I << -9D) PrintResult("-5I << 10.0F", -5I << 10.0F) PrintResult("-5I << -11.0R", -5I << -11.0R) PrintResult("-5I << ""12""", -5I << "12") PrintResult("-5I << TypeCode.Double", -5I << TypeCode.Double) PrintResult("26UI << False", 26UI << False) PrintResult("26UI << True", 26UI << True) PrintResult("26UI << System.SByte.MinValue", 26UI << System.SByte.MinValue) PrintResult("26UI << System.Byte.MaxValue", 26UI << System.Byte.MaxValue) PrintResult("26UI << -3S", 26UI << -3S) PrintResult("26UI << 24US", 26UI << 24US) PrintResult("26UI << -5I", 26UI << -5I) PrintResult("26UI << 26UI", 26UI << 26UI) PrintResult("26UI << -7L", 26UI << -7L) PrintResult("26UI << 28UL", 26UI << 28UL) PrintResult("26UI << -9D", 26UI << -9D) PrintResult("26UI << 10.0F", 26UI << 10.0F) PrintResult("26UI << -11.0R", 26UI << -11.0R) PrintResult("26UI << ""12""", 26UI << "12") PrintResult("26UI << TypeCode.Double", 26UI << TypeCode.Double) PrintResult("-7L << False", -7L << False) PrintResult("-7L << True", -7L << True) PrintResult("-7L << System.SByte.MinValue", -7L << System.SByte.MinValue) PrintResult("-7L << System.Byte.MaxValue", -7L << System.Byte.MaxValue) PrintResult("-7L << -3S", -7L << -3S) PrintResult("-7L << 24US", -7L << 24US) PrintResult("-7L << -5I", -7L << -5I) PrintResult("-7L << 26UI", -7L << 26UI) PrintResult("-7L << -7L", -7L << -7L) PrintResult("-7L << 28UL", -7L << 28UL) PrintResult("-7L << -9D", -7L << -9D) PrintResult("-7L << 10.0F", -7L << 10.0F) PrintResult("-7L << -11.0R", -7L << -11.0R) PrintResult("-7L << ""12""", -7L << "12") PrintResult("-7L << TypeCode.Double", -7L << TypeCode.Double) PrintResult("28UL << False", 28UL << False) PrintResult("28UL << True", 28UL << True) PrintResult("28UL << System.SByte.MinValue", 28UL << System.SByte.MinValue) PrintResult("28UL << System.Byte.MaxValue", 28UL << System.Byte.MaxValue) PrintResult("28UL << -3S", 28UL << -3S) PrintResult("28UL << 24US", 28UL << 24US) PrintResult("28UL << -5I", 28UL << -5I) PrintResult("28UL << 26UI", 28UL << 26UI) PrintResult("28UL << -7L", 28UL << -7L) PrintResult("28UL << 28UL", 28UL << 28UL) PrintResult("28UL << -9D", 28UL << -9D) PrintResult("28UL << 10.0F", 28UL << 10.0F) PrintResult("28UL << -11.0R", 28UL << -11.0R) PrintResult("28UL << ""12""", 28UL << "12") PrintResult("28UL << TypeCode.Double", 28UL << TypeCode.Double) PrintResult("-9D << False", -9D << False) PrintResult("-9D << True", -9D << True) PrintResult("-9D << System.SByte.MinValue", -9D << System.SByte.MinValue) PrintResult("-9D << System.Byte.MaxValue", -9D << System.Byte.MaxValue) PrintResult("-9D << -3S", -9D << -3S) PrintResult("-9D << 24US", -9D << 24US) PrintResult("-9D << -5I", -9D << -5I) PrintResult("-9D << 26UI", -9D << 26UI) PrintResult("-9D << -7L", -9D << -7L) PrintResult("-9D << 28UL", -9D << 28UL) PrintResult("-9D << -9D", -9D << -9D) PrintResult("-9D << 10.0F", -9D << 10.0F) PrintResult("-9D << -11.0R", -9D << -11.0R) PrintResult("-9D << ""12""", -9D << "12") PrintResult("-9D << TypeCode.Double", -9D << TypeCode.Double) PrintResult("10.0F << False", 10.0F << False) PrintResult("10.0F << True", 10.0F << True) PrintResult("10.0F << System.SByte.MinValue", 10.0F << System.SByte.MinValue) PrintResult("10.0F << System.Byte.MaxValue", 10.0F << System.Byte.MaxValue) PrintResult("10.0F << -3S", 10.0F << -3S) PrintResult("10.0F << 24US", 10.0F << 24US) PrintResult("10.0F << -5I", 10.0F << -5I) PrintResult("10.0F << 26UI", 10.0F << 26UI) PrintResult("10.0F << -7L", 10.0F << -7L) PrintResult("10.0F << 28UL", 10.0F << 28UL) PrintResult("10.0F << -9D", 10.0F << -9D) PrintResult("10.0F << 10.0F", 10.0F << 10.0F) PrintResult("10.0F << -11.0R", 10.0F << -11.0R) PrintResult("10.0F << ""12""", 10.0F << "12") PrintResult("10.0F << TypeCode.Double", 10.0F << TypeCode.Double) PrintResult("-11.0R << False", -11.0R << False) PrintResult("-11.0R << True", -11.0R << True) PrintResult("-11.0R << System.SByte.MinValue", -11.0R << System.SByte.MinValue) PrintResult("-11.0R << System.Byte.MaxValue", -11.0R << System.Byte.MaxValue) PrintResult("-11.0R << -3S", -11.0R << -3S) PrintResult("-11.0R << 24US", -11.0R << 24US) PrintResult("-11.0R << -5I", -11.0R << -5I) PrintResult("-11.0R << 26UI", -11.0R << 26UI) PrintResult("-11.0R << -7L", -11.0R << -7L) PrintResult("-11.0R << 28UL", -11.0R << 28UL) PrintResult("-11.0R << -9D", -11.0R << -9D) PrintResult("-11.0R << 10.0F", -11.0R << 10.0F) PrintResult("-11.0R << -11.0R", -11.0R << -11.0R) PrintResult("-11.0R << ""12""", -11.0R << "12") PrintResult("-11.0R << TypeCode.Double", -11.0R << TypeCode.Double) PrintResult("""12"" << False", "12" << False) PrintResult("""12"" << True", "12" << True) PrintResult("""12"" << System.SByte.MinValue", "12" << System.SByte.MinValue) PrintResult("""12"" << System.Byte.MaxValue", "12" << System.Byte.MaxValue) PrintResult("""12"" << -3S", "12" << -3S) PrintResult("""12"" << 24US", "12" << 24US) PrintResult("""12"" << -5I", "12" << -5I) PrintResult("""12"" << 26UI", "12" << 26UI) PrintResult("""12"" << -7L", "12" << -7L) PrintResult("""12"" << 28UL", "12" << 28UL) PrintResult("""12"" << -9D", "12" << -9D) PrintResult("""12"" << 10.0F", "12" << 10.0F) PrintResult("""12"" << -11.0R", "12" << -11.0R) PrintResult("""12"" << ""12""", "12" << "12") PrintResult("""12"" << TypeCode.Double", "12" << TypeCode.Double) PrintResult("TypeCode.Double << False", TypeCode.Double << False) PrintResult("TypeCode.Double << True", TypeCode.Double << True) PrintResult("TypeCode.Double << System.SByte.MinValue", TypeCode.Double << System.SByte.MinValue) PrintResult("TypeCode.Double << System.Byte.MaxValue", TypeCode.Double << System.Byte.MaxValue) PrintResult("TypeCode.Double << -3S", TypeCode.Double << -3S) PrintResult("TypeCode.Double << 24US", TypeCode.Double << 24US) PrintResult("TypeCode.Double << -5I", TypeCode.Double << -5I) PrintResult("TypeCode.Double << 26UI", TypeCode.Double << 26UI) PrintResult("TypeCode.Double << -7L", TypeCode.Double << -7L) PrintResult("TypeCode.Double << 28UL", TypeCode.Double << 28UL) PrintResult("TypeCode.Double << -9D", TypeCode.Double << -9D) PrintResult("TypeCode.Double << 10.0F", TypeCode.Double << 10.0F) PrintResult("TypeCode.Double << -11.0R", TypeCode.Double << -11.0R) PrintResult("TypeCode.Double << ""12""", TypeCode.Double << "12") PrintResult("TypeCode.Double << TypeCode.Double", TypeCode.Double << TypeCode.Double) PrintResult("False >> False", False >> False) PrintResult("False >> True", False >> True) PrintResult("False >> System.SByte.MinValue", False >> System.SByte.MinValue) PrintResult("False >> System.Byte.MaxValue", False >> System.Byte.MaxValue) PrintResult("False >> -3S", False >> -3S) PrintResult("False >> 24US", False >> 24US) PrintResult("False >> -5I", False >> -5I) PrintResult("False >> 26UI", False >> 26UI) PrintResult("False >> -7L", False >> -7L) PrintResult("False >> 28UL", False >> 28UL) PrintResult("False >> -9D", False >> -9D) PrintResult("False >> 10.0F", False >> 10.0F) PrintResult("False >> -11.0R", False >> -11.0R) PrintResult("False >> ""12""", False >> "12") PrintResult("False >> TypeCode.Double", False >> TypeCode.Double) PrintResult("True >> False", True >> False) PrintResult("True >> True", True >> True) PrintResult("True >> System.SByte.MinValue", True >> System.SByte.MinValue) PrintResult("True >> System.Byte.MaxValue", True >> System.Byte.MaxValue) PrintResult("True >> -3S", True >> -3S) PrintResult("True >> 24US", True >> 24US) PrintResult("True >> -5I", True >> -5I) PrintResult("True >> 26UI", True >> 26UI) PrintResult("True >> -7L", True >> -7L) PrintResult("True >> 28UL", True >> 28UL) PrintResult("True >> -9D", True >> -9D) PrintResult("True >> 10.0F", True >> 10.0F) PrintResult("True >> -11.0R", True >> -11.0R) PrintResult("True >> ""12""", True >> "12") PrintResult("True >> TypeCode.Double", True >> TypeCode.Double) PrintResult("System.SByte.MinValue >> False", System.SByte.MinValue >> False) PrintResult("System.SByte.MinValue >> True", System.SByte.MinValue >> True) PrintResult("System.SByte.MinValue >> System.SByte.MinValue", System.SByte.MinValue >> System.SByte.MinValue) PrintResult("System.SByte.MinValue >> System.Byte.MaxValue", System.SByte.MinValue >> System.Byte.MaxValue) PrintResult("System.SByte.MinValue >> -3S", System.SByte.MinValue >> -3S) PrintResult("System.SByte.MinValue >> 24US", System.SByte.MinValue >> 24US) PrintResult("System.SByte.MinValue >> -5I", System.SByte.MinValue >> -5I) PrintResult("System.SByte.MinValue >> 26UI", System.SByte.MinValue >> 26UI) PrintResult("System.SByte.MinValue >> -7L", System.SByte.MinValue >> -7L) PrintResult("System.SByte.MinValue >> 28UL", System.SByte.MinValue >> 28UL) PrintResult("System.SByte.MinValue >> -9D", System.SByte.MinValue >> -9D) PrintResult("System.SByte.MinValue >> 10.0F", System.SByte.MinValue >> 10.0F) PrintResult("System.SByte.MinValue >> -11.0R", System.SByte.MinValue >> -11.0R) PrintResult("System.SByte.MinValue >> ""12""", System.SByte.MinValue >> "12") PrintResult("System.SByte.MinValue >> TypeCode.Double", System.SByte.MinValue >> TypeCode.Double) PrintResult("System.Byte.MaxValue >> False", System.Byte.MaxValue >> False) PrintResult("System.Byte.MaxValue >> True", System.Byte.MaxValue >> True) PrintResult("System.Byte.MaxValue >> System.SByte.MinValue", System.Byte.MaxValue >> System.SByte.MinValue) PrintResult("System.Byte.MaxValue >> System.Byte.MaxValue", System.Byte.MaxValue >> System.Byte.MaxValue) PrintResult("System.Byte.MaxValue >> -3S", System.Byte.MaxValue >> -3S) PrintResult("System.Byte.MaxValue >> 24US", System.Byte.MaxValue >> 24US) PrintResult("System.Byte.MaxValue >> -5I", System.Byte.MaxValue >> -5I) PrintResult("System.Byte.MaxValue >> 26UI", System.Byte.MaxValue >> 26UI) PrintResult("System.Byte.MaxValue >> -7L", System.Byte.MaxValue >> -7L) PrintResult("System.Byte.MaxValue >> 28UL", System.Byte.MaxValue >> 28UL) PrintResult("System.Byte.MaxValue >> -9D", System.Byte.MaxValue >> -9D) PrintResult("System.Byte.MaxValue >> 10.0F", System.Byte.MaxValue >> 10.0F) PrintResult("System.Byte.MaxValue >> -11.0R", System.Byte.MaxValue >> -11.0R) PrintResult("System.Byte.MaxValue >> ""12""", System.Byte.MaxValue >> "12") PrintResult("System.Byte.MaxValue >> TypeCode.Double", System.Byte.MaxValue >> TypeCode.Double) PrintResult("-3S >> False", -3S >> False) PrintResult("-3S >> True", -3S >> True) PrintResult("-3S >> System.SByte.MinValue", -3S >> System.SByte.MinValue) PrintResult("-3S >> System.Byte.MaxValue", -3S >> System.Byte.MaxValue) PrintResult("-3S >> -3S", -3S >> -3S) PrintResult("-3S >> 24US", -3S >> 24US) PrintResult("-3S >> -5I", -3S >> -5I) PrintResult("-3S >> 26UI", -3S >> 26UI) PrintResult("-3S >> -7L", -3S >> -7L) PrintResult("-3S >> 28UL", -3S >> 28UL) PrintResult("-3S >> -9D", -3S >> -9D) PrintResult("-3S >> 10.0F", -3S >> 10.0F) PrintResult("-3S >> -11.0R", -3S >> -11.0R) PrintResult("-3S >> ""12""", -3S >> "12") PrintResult("-3S >> TypeCode.Double", -3S >> TypeCode.Double) PrintResult("24US >> False", 24US >> False) PrintResult("24US >> True", 24US >> True) PrintResult("24US >> System.SByte.MinValue", 24US >> System.SByte.MinValue) PrintResult("24US >> System.Byte.MaxValue", 24US >> System.Byte.MaxValue) PrintResult("24US >> -3S", 24US >> -3S) PrintResult("24US >> 24US", 24US >> 24US) PrintResult("24US >> -5I", 24US >> -5I) PrintResult("24US >> 26UI", 24US >> 26UI) PrintResult("24US >> -7L", 24US >> -7L) PrintResult("24US >> 28UL", 24US >> 28UL) PrintResult("24US >> -9D", 24US >> -9D) PrintResult("24US >> 10.0F", 24US >> 10.0F) PrintResult("24US >> -11.0R", 24US >> -11.0R) PrintResult("24US >> ""12""", 24US >> "12") PrintResult("24US >> TypeCode.Double", 24US >> TypeCode.Double) PrintResult("-5I >> False", -5I >> False) PrintResult("-5I >> True", -5I >> True) PrintResult("-5I >> System.SByte.MinValue", -5I >> System.SByte.MinValue) PrintResult("-5I >> System.Byte.MaxValue", -5I >> System.Byte.MaxValue) PrintResult("-5I >> -3S", -5I >> -3S) PrintResult("-5I >> 24US", -5I >> 24US) PrintResult("-5I >> -5I", -5I >> -5I) PrintResult("-5I >> 26UI", -5I >> 26UI) PrintResult("-5I >> -7L", -5I >> -7L) PrintResult("-5I >> 28UL", -5I >> 28UL) PrintResult("-5I >> -9D", -5I >> -9D) PrintResult("-5I >> 10.0F", -5I >> 10.0F) PrintResult("-5I >> -11.0R", -5I >> -11.0R) PrintResult("-5I >> ""12""", -5I >> "12") PrintResult("-5I >> TypeCode.Double", -5I >> TypeCode.Double) PrintResult("26UI >> False", 26UI >> False) PrintResult("26UI >> True", 26UI >> True) PrintResult("26UI >> System.SByte.MinValue", 26UI >> System.SByte.MinValue) PrintResult("26UI >> System.Byte.MaxValue", 26UI >> System.Byte.MaxValue) PrintResult("26UI >> -3S", 26UI >> -3S) PrintResult("26UI >> 24US", 26UI >> 24US) PrintResult("26UI >> -5I", 26UI >> -5I) PrintResult("26UI >> 26UI", 26UI >> 26UI) PrintResult("26UI >> -7L", 26UI >> -7L) PrintResult("26UI >> 28UL", 26UI >> 28UL) PrintResult("26UI >> -9D", 26UI >> -9D) PrintResult("26UI >> 10.0F", 26UI >> 10.0F) PrintResult("26UI >> -11.0R", 26UI >> -11.0R) PrintResult("26UI >> ""12""", 26UI >> "12") PrintResult("26UI >> TypeCode.Double", 26UI >> TypeCode.Double) PrintResult("-7L >> False", -7L >> False) PrintResult("-7L >> True", -7L >> True) PrintResult("-7L >> System.SByte.MinValue", -7L >> System.SByte.MinValue) PrintResult("-7L >> System.Byte.MaxValue", -7L >> System.Byte.MaxValue) PrintResult("-7L >> -3S", -7L >> -3S) PrintResult("-7L >> 24US", -7L >> 24US) PrintResult("-7L >> -5I", -7L >> -5I) PrintResult("-7L >> 26UI", -7L >> 26UI) PrintResult("-7L >> -7L", -7L >> -7L) PrintResult("-7L >> 28UL", -7L >> 28UL) PrintResult("-7L >> -9D", -7L >> -9D) PrintResult("-7L >> 10.0F", -7L >> 10.0F) PrintResult("-7L >> -11.0R", -7L >> -11.0R) PrintResult("-7L >> ""12""", -7L >> "12") PrintResult("-7L >> TypeCode.Double", -7L >> TypeCode.Double) PrintResult("28UL >> False", 28UL >> False) PrintResult("28UL >> True", 28UL >> True) PrintResult("28UL >> System.SByte.MinValue", 28UL >> System.SByte.MinValue) PrintResult("28UL >> System.Byte.MaxValue", 28UL >> System.Byte.MaxValue) PrintResult("28UL >> -3S", 28UL >> -3S) PrintResult("28UL >> 24US", 28UL >> 24US) PrintResult("28UL >> -5I", 28UL >> -5I) PrintResult("28UL >> 26UI", 28UL >> 26UI) PrintResult("28UL >> -7L", 28UL >> -7L) PrintResult("28UL >> 28UL", 28UL >> 28UL) PrintResult("28UL >> -9D", 28UL >> -9D) PrintResult("28UL >> 10.0F", 28UL >> 10.0F) PrintResult("28UL >> -11.0R", 28UL >> -11.0R) PrintResult("28UL >> ""12""", 28UL >> "12") PrintResult("28UL >> TypeCode.Double", 28UL >> TypeCode.Double) PrintResult("-9D >> False", -9D >> False) PrintResult("-9D >> True", -9D >> True) PrintResult("-9D >> System.SByte.MinValue", -9D >> System.SByte.MinValue) PrintResult("-9D >> System.Byte.MaxValue", -9D >> System.Byte.MaxValue) PrintResult("-9D >> -3S", -9D >> -3S) PrintResult("-9D >> 24US", -9D >> 24US) PrintResult("-9D >> -5I", -9D >> -5I) PrintResult("-9D >> 26UI", -9D >> 26UI) PrintResult("-9D >> -7L", -9D >> -7L) PrintResult("-9D >> 28UL", -9D >> 28UL) PrintResult("-9D >> -9D", -9D >> -9D) PrintResult("-9D >> 10.0F", -9D >> 10.0F) PrintResult("-9D >> -11.0R", -9D >> -11.0R) PrintResult("-9D >> ""12""", -9D >> "12") PrintResult("-9D >> TypeCode.Double", -9D >> TypeCode.Double) PrintResult("10.0F >> False", 10.0F >> False) PrintResult("10.0F >> True", 10.0F >> True) PrintResult("10.0F >> System.SByte.MinValue", 10.0F >> System.SByte.MinValue) PrintResult("10.0F >> System.Byte.MaxValue", 10.0F >> System.Byte.MaxValue) PrintResult("10.0F >> -3S", 10.0F >> -3S) PrintResult("10.0F >> 24US", 10.0F >> 24US) PrintResult("10.0F >> -5I", 10.0F >> -5I) PrintResult("10.0F >> 26UI", 10.0F >> 26UI) PrintResult("10.0F >> -7L", 10.0F >> -7L) PrintResult("10.0F >> 28UL", 10.0F >> 28UL) PrintResult("10.0F >> -9D", 10.0F >> -9D) PrintResult("10.0F >> 10.0F", 10.0F >> 10.0F) PrintResult("10.0F >> -11.0R", 10.0F >> -11.0R) PrintResult("10.0F >> ""12""", 10.0F >> "12") PrintResult("10.0F >> TypeCode.Double", 10.0F >> TypeCode.Double) PrintResult("-11.0R >> False", -11.0R >> False) PrintResult("-11.0R >> True", -11.0R >> True) PrintResult("-11.0R >> System.SByte.MinValue", -11.0R >> System.SByte.MinValue) PrintResult("-11.0R >> System.Byte.MaxValue", -11.0R >> System.Byte.MaxValue) PrintResult("-11.0R >> -3S", -11.0R >> -3S) PrintResult("-11.0R >> 24US", -11.0R >> 24US) PrintResult("-11.0R >> -5I", -11.0R >> -5I) PrintResult("-11.0R >> 26UI", -11.0R >> 26UI) PrintResult("-11.0R >> -7L", -11.0R >> -7L) PrintResult("-11.0R >> 28UL", -11.0R >> 28UL) PrintResult("-11.0R >> -9D", -11.0R >> -9D) PrintResult("-11.0R >> 10.0F", -11.0R >> 10.0F) PrintResult("-11.0R >> -11.0R", -11.0R >> -11.0R) PrintResult("-11.0R >> ""12""", -11.0R >> "12") PrintResult("-11.0R >> TypeCode.Double", -11.0R >> TypeCode.Double) PrintResult("""12"" >> False", "12" >> False) PrintResult("""12"" >> True", "12" >> True) PrintResult("""12"" >> System.SByte.MinValue", "12" >> System.SByte.MinValue) PrintResult("""12"" >> System.Byte.MaxValue", "12" >> System.Byte.MaxValue) PrintResult("""12"" >> -3S", "12" >> -3S) PrintResult("""12"" >> 24US", "12" >> 24US) PrintResult("""12"" >> -5I", "12" >> -5I) PrintResult("""12"" >> 26UI", "12" >> 26UI) PrintResult("""12"" >> -7L", "12" >> -7L) PrintResult("""12"" >> 28UL", "12" >> 28UL) PrintResult("""12"" >> -9D", "12" >> -9D) PrintResult("""12"" >> 10.0F", "12" >> 10.0F) PrintResult("""12"" >> -11.0R", "12" >> -11.0R) PrintResult("""12"" >> ""12""", "12" >> "12") PrintResult("""12"" >> TypeCode.Double", "12" >> TypeCode.Double) PrintResult("TypeCode.Double >> False", TypeCode.Double >> False) PrintResult("TypeCode.Double >> True", TypeCode.Double >> True) PrintResult("TypeCode.Double >> System.SByte.MinValue", TypeCode.Double >> System.SByte.MinValue) PrintResult("TypeCode.Double >> System.Byte.MaxValue", TypeCode.Double >> System.Byte.MaxValue) PrintResult("TypeCode.Double >> -3S", TypeCode.Double >> -3S) PrintResult("TypeCode.Double >> 24US", TypeCode.Double >> 24US) PrintResult("TypeCode.Double >> -5I", TypeCode.Double >> -5I) PrintResult("TypeCode.Double >> 26UI", TypeCode.Double >> 26UI) PrintResult("TypeCode.Double >> -7L", TypeCode.Double >> -7L) PrintResult("TypeCode.Double >> 28UL", TypeCode.Double >> 28UL) PrintResult("TypeCode.Double >> -9D", TypeCode.Double >> -9D) PrintResult("TypeCode.Double >> 10.0F", TypeCode.Double >> 10.0F) PrintResult("TypeCode.Double >> -11.0R", TypeCode.Double >> -11.0R) PrintResult("TypeCode.Double >> ""12""", TypeCode.Double >> "12") PrintResult("TypeCode.Double >> TypeCode.Double", TypeCode.Double >> TypeCode.Double) PrintResult("False OrElse False", False OrElse False) PrintResult("False OrElse True", False OrElse True) PrintResult("False OrElse System.SByte.MinValue", False OrElse System.SByte.MinValue) PrintResult("False OrElse System.Byte.MaxValue", False OrElse System.Byte.MaxValue) PrintResult("False OrElse -3S", False OrElse -3S) PrintResult("False OrElse 24US", False OrElse 24US) PrintResult("False OrElse -5I", False OrElse -5I) PrintResult("False OrElse 26UI", False OrElse 26UI) PrintResult("False OrElse -7L", False OrElse -7L) PrintResult("False OrElse 28UL", False OrElse 28UL) PrintResult("False OrElse -9D", False OrElse -9D) PrintResult("False OrElse 10.0F", False OrElse 10.0F) PrintResult("False OrElse -11.0R", False OrElse -11.0R) PrintResult("False OrElse ""12""", False OrElse "12") PrintResult("False OrElse TypeCode.Double", False OrElse TypeCode.Double) PrintResult("True OrElse False", True OrElse False) PrintResult("True OrElse True", True OrElse True) PrintResult("True OrElse System.SByte.MinValue", True OrElse System.SByte.MinValue) PrintResult("True OrElse System.Byte.MaxValue", True OrElse System.Byte.MaxValue) PrintResult("True OrElse -3S", True OrElse -3S) PrintResult("True OrElse 24US", True OrElse 24US) PrintResult("True OrElse -5I", True OrElse -5I) PrintResult("True OrElse 26UI", True OrElse 26UI) PrintResult("True OrElse -7L", True OrElse -7L) PrintResult("True OrElse 28UL", True OrElse 28UL) PrintResult("True OrElse -9D", True OrElse -9D) PrintResult("True OrElse 10.0F", True OrElse 10.0F) PrintResult("True OrElse -11.0R", True OrElse -11.0R) PrintResult("True OrElse ""12""", True OrElse "12") PrintResult("True OrElse TypeCode.Double", True OrElse TypeCode.Double) PrintResult("System.SByte.MinValue OrElse False", System.SByte.MinValue OrElse False) PrintResult("System.SByte.MinValue OrElse True", System.SByte.MinValue OrElse True) PrintResult("System.SByte.MinValue OrElse System.SByte.MinValue", System.SByte.MinValue OrElse System.SByte.MinValue) PrintResult("System.SByte.MinValue OrElse System.Byte.MaxValue", System.SByte.MinValue OrElse System.Byte.MaxValue) PrintResult("System.SByte.MinValue OrElse -3S", System.SByte.MinValue OrElse -3S) PrintResult("System.SByte.MinValue OrElse 24US", System.SByte.MinValue OrElse 24US) PrintResult("System.SByte.MinValue OrElse -5I", System.SByte.MinValue OrElse -5I) PrintResult("System.SByte.MinValue OrElse 26UI", System.SByte.MinValue OrElse 26UI) PrintResult("System.SByte.MinValue OrElse -7L", System.SByte.MinValue OrElse -7L) PrintResult("System.SByte.MinValue OrElse 28UL", System.SByte.MinValue OrElse 28UL) PrintResult("System.SByte.MinValue OrElse -9D", System.SByte.MinValue OrElse -9D) PrintResult("System.SByte.MinValue OrElse 10.0F", System.SByte.MinValue OrElse 10.0F) PrintResult("System.SByte.MinValue OrElse -11.0R", System.SByte.MinValue OrElse -11.0R) PrintResult("System.SByte.MinValue OrElse ""12""", System.SByte.MinValue OrElse "12") PrintResult("System.SByte.MinValue OrElse TypeCode.Double", System.SByte.MinValue OrElse TypeCode.Double) PrintResult("System.Byte.MaxValue OrElse False", System.Byte.MaxValue OrElse False) PrintResult("System.Byte.MaxValue OrElse True", System.Byte.MaxValue OrElse True) PrintResult("System.Byte.MaxValue OrElse System.SByte.MinValue", System.Byte.MaxValue OrElse System.SByte.MinValue) PrintResult("System.Byte.MaxValue OrElse System.Byte.MaxValue", System.Byte.MaxValue OrElse System.Byte.MaxValue) PrintResult("System.Byte.MaxValue OrElse -3S", System.Byte.MaxValue OrElse -3S) PrintResult("System.Byte.MaxValue OrElse 24US", System.Byte.MaxValue OrElse 24US) PrintResult("System.Byte.MaxValue OrElse -5I", System.Byte.MaxValue OrElse -5I) PrintResult("System.Byte.MaxValue OrElse 26UI", System.Byte.MaxValue OrElse 26UI) PrintResult("System.Byte.MaxValue OrElse -7L", System.Byte.MaxValue OrElse -7L) PrintResult("System.Byte.MaxValue OrElse 28UL", System.Byte.MaxValue OrElse 28UL) PrintResult("System.Byte.MaxValue OrElse -9D", System.Byte.MaxValue OrElse -9D) PrintResult("System.Byte.MaxValue OrElse 10.0F", System.Byte.MaxValue OrElse 10.0F) PrintResult("System.Byte.MaxValue OrElse -11.0R", System.Byte.MaxValue OrElse -11.0R) PrintResult("System.Byte.MaxValue OrElse ""12""", System.Byte.MaxValue OrElse "12") PrintResult("System.Byte.MaxValue OrElse TypeCode.Double", System.Byte.MaxValue OrElse TypeCode.Double) PrintResult("-3S OrElse False", -3S OrElse False) PrintResult("-3S OrElse True", -3S OrElse True) PrintResult("-3S OrElse System.SByte.MinValue", -3S OrElse System.SByte.MinValue) PrintResult("-3S OrElse System.Byte.MaxValue", -3S OrElse System.Byte.MaxValue) PrintResult("-3S OrElse -3S", -3S OrElse -3S) PrintResult("-3S OrElse 24US", -3S OrElse 24US) PrintResult("-3S OrElse -5I", -3S OrElse -5I) PrintResult("-3S OrElse 26UI", -3S OrElse 26UI) PrintResult("-3S OrElse -7L", -3S OrElse -7L) PrintResult("-3S OrElse 28UL", -3S OrElse 28UL) PrintResult("-3S OrElse -9D", -3S OrElse -9D) PrintResult("-3S OrElse 10.0F", -3S OrElse 10.0F) PrintResult("-3S OrElse -11.0R", -3S OrElse -11.0R) PrintResult("-3S OrElse ""12""", -3S OrElse "12") PrintResult("-3S OrElse TypeCode.Double", -3S OrElse TypeCode.Double) PrintResult("24US OrElse False", 24US OrElse False) PrintResult("24US OrElse True", 24US OrElse True) PrintResult("24US OrElse System.SByte.MinValue", 24US OrElse System.SByte.MinValue) PrintResult("24US OrElse System.Byte.MaxValue", 24US OrElse System.Byte.MaxValue) PrintResult("24US OrElse -3S", 24US OrElse -3S) PrintResult("24US OrElse 24US", 24US OrElse 24US) PrintResult("24US OrElse -5I", 24US OrElse -5I) PrintResult("24US OrElse 26UI", 24US OrElse 26UI) PrintResult("24US OrElse -7L", 24US OrElse -7L) PrintResult("24US OrElse 28UL", 24US OrElse 28UL) PrintResult("24US OrElse -9D", 24US OrElse -9D) PrintResult("24US OrElse 10.0F", 24US OrElse 10.0F) PrintResult("24US OrElse -11.0R", 24US OrElse -11.0R) PrintResult("24US OrElse ""12""", 24US OrElse "12") PrintResult("24US OrElse TypeCode.Double", 24US OrElse TypeCode.Double) PrintResult("-5I OrElse False", -5I OrElse False) PrintResult("-5I OrElse True", -5I OrElse True) PrintResult("-5I OrElse System.SByte.MinValue", -5I OrElse System.SByte.MinValue) PrintResult("-5I OrElse System.Byte.MaxValue", -5I OrElse System.Byte.MaxValue) PrintResult("-5I OrElse -3S", -5I OrElse -3S) PrintResult("-5I OrElse 24US", -5I OrElse 24US) PrintResult("-5I OrElse -5I", -5I OrElse -5I) PrintResult("-5I OrElse 26UI", -5I OrElse 26UI) PrintResult("-5I OrElse -7L", -5I OrElse -7L) PrintResult("-5I OrElse 28UL", -5I OrElse 28UL) PrintResult("-5I OrElse -9D", -5I OrElse -9D) PrintResult("-5I OrElse 10.0F", -5I OrElse 10.0F) PrintResult("-5I OrElse -11.0R", -5I OrElse -11.0R) PrintResult("-5I OrElse ""12""", -5I OrElse "12") PrintResult("-5I OrElse TypeCode.Double", -5I OrElse TypeCode.Double) PrintResult("26UI OrElse False", 26UI OrElse False) PrintResult("26UI OrElse True", 26UI OrElse True) PrintResult("26UI OrElse System.SByte.MinValue", 26UI OrElse System.SByte.MinValue) PrintResult("26UI OrElse System.Byte.MaxValue", 26UI OrElse System.Byte.MaxValue) PrintResult("26UI OrElse -3S", 26UI OrElse -3S) PrintResult("26UI OrElse 24US", 26UI OrElse 24US) PrintResult("26UI OrElse -5I", 26UI OrElse -5I) PrintResult("26UI OrElse 26UI", 26UI OrElse 26UI) PrintResult("26UI OrElse -7L", 26UI OrElse -7L) PrintResult("26UI OrElse 28UL", 26UI OrElse 28UL) PrintResult("26UI OrElse -9D", 26UI OrElse -9D) PrintResult("26UI OrElse 10.0F", 26UI OrElse 10.0F) PrintResult("26UI OrElse -11.0R", 26UI OrElse -11.0R) PrintResult("26UI OrElse ""12""", 26UI OrElse "12") PrintResult("26UI OrElse TypeCode.Double", 26UI OrElse TypeCode.Double) PrintResult("-7L OrElse False", -7L OrElse False) PrintResult("-7L OrElse True", -7L OrElse True) PrintResult("-7L OrElse System.SByte.MinValue", -7L OrElse System.SByte.MinValue) PrintResult("-7L OrElse System.Byte.MaxValue", -7L OrElse System.Byte.MaxValue) PrintResult("-7L OrElse -3S", -7L OrElse -3S) PrintResult("-7L OrElse 24US", -7L OrElse 24US) PrintResult("-7L OrElse -5I", -7L OrElse -5I) PrintResult("-7L OrElse 26UI", -7L OrElse 26UI) PrintResult("-7L OrElse -7L", -7L OrElse -7L) PrintResult("-7L OrElse 28UL", -7L OrElse 28UL) PrintResult("-7L OrElse -9D", -7L OrElse -9D) PrintResult("-7L OrElse 10.0F", -7L OrElse 10.0F) PrintResult("-7L OrElse -11.0R", -7L OrElse -11.0R) PrintResult("-7L OrElse ""12""", -7L OrElse "12") PrintResult("-7L OrElse TypeCode.Double", -7L OrElse TypeCode.Double) PrintResult("28UL OrElse False", 28UL OrElse False) PrintResult("28UL OrElse True", 28UL OrElse True) PrintResult("28UL OrElse System.SByte.MinValue", 28UL OrElse System.SByte.MinValue) PrintResult("28UL OrElse System.Byte.MaxValue", 28UL OrElse System.Byte.MaxValue) PrintResult("28UL OrElse -3S", 28UL OrElse -3S) PrintResult("28UL OrElse 24US", 28UL OrElse 24US) PrintResult("28UL OrElse -5I", 28UL OrElse -5I) PrintResult("28UL OrElse 26UI", 28UL OrElse 26UI) PrintResult("28UL OrElse -7L", 28UL OrElse -7L) PrintResult("28UL OrElse 28UL", 28UL OrElse 28UL) PrintResult("28UL OrElse -9D", 28UL OrElse -9D) PrintResult("28UL OrElse 10.0F", 28UL OrElse 10.0F) PrintResult("28UL OrElse -11.0R", 28UL OrElse -11.0R) PrintResult("28UL OrElse ""12""", 28UL OrElse "12") PrintResult("28UL OrElse TypeCode.Double", 28UL OrElse TypeCode.Double) PrintResult("-9D OrElse False", -9D OrElse False) PrintResult("-9D OrElse True", -9D OrElse True) PrintResult("-9D OrElse System.SByte.MinValue", -9D OrElse System.SByte.MinValue) PrintResult("-9D OrElse System.Byte.MaxValue", -9D OrElse System.Byte.MaxValue) PrintResult("-9D OrElse -3S", -9D OrElse -3S) PrintResult("-9D OrElse 24US", -9D OrElse 24US) PrintResult("-9D OrElse -5I", -9D OrElse -5I) PrintResult("-9D OrElse 26UI", -9D OrElse 26UI) PrintResult("-9D OrElse -7L", -9D OrElse -7L) PrintResult("-9D OrElse 28UL", -9D OrElse 28UL) PrintResult("-9D OrElse -9D", -9D OrElse -9D) PrintResult("-9D OrElse 10.0F", -9D OrElse 10.0F) PrintResult("-9D OrElse -11.0R", -9D OrElse -11.0R) PrintResult("-9D OrElse ""12""", -9D OrElse "12") PrintResult("-9D OrElse TypeCode.Double", -9D OrElse TypeCode.Double) PrintResult("10.0F OrElse False", 10.0F OrElse False) PrintResult("10.0F OrElse True", 10.0F OrElse True) PrintResult("10.0F OrElse System.SByte.MinValue", 10.0F OrElse System.SByte.MinValue) PrintResult("10.0F OrElse System.Byte.MaxValue", 10.0F OrElse System.Byte.MaxValue) PrintResult("10.0F OrElse -3S", 10.0F OrElse -3S) PrintResult("10.0F OrElse 24US", 10.0F OrElse 24US) PrintResult("10.0F OrElse -5I", 10.0F OrElse -5I) PrintResult("10.0F OrElse 26UI", 10.0F OrElse 26UI) PrintResult("10.0F OrElse -7L", 10.0F OrElse -7L) PrintResult("10.0F OrElse 28UL", 10.0F OrElse 28UL) PrintResult("10.0F OrElse -9D", 10.0F OrElse -9D) PrintResult("10.0F OrElse 10.0F", 10.0F OrElse 10.0F) PrintResult("10.0F OrElse -11.0R", 10.0F OrElse -11.0R) PrintResult("10.0F OrElse ""12""", 10.0F OrElse "12") PrintResult("10.0F OrElse TypeCode.Double", 10.0F OrElse TypeCode.Double) PrintResult("-11.0R OrElse False", -11.0R OrElse False) PrintResult("-11.0R OrElse True", -11.0R OrElse True) PrintResult("-11.0R OrElse System.SByte.MinValue", -11.0R OrElse System.SByte.MinValue) PrintResult("-11.0R OrElse System.Byte.MaxValue", -11.0R OrElse System.Byte.MaxValue) PrintResult("-11.0R OrElse -3S", -11.0R OrElse -3S) PrintResult("-11.0R OrElse 24US", -11.0R OrElse 24US) PrintResult("-11.0R OrElse -5I", -11.0R OrElse -5I) PrintResult("-11.0R OrElse 26UI", -11.0R OrElse 26UI) PrintResult("-11.0R OrElse -7L", -11.0R OrElse -7L) PrintResult("-11.0R OrElse 28UL", -11.0R OrElse 28UL) PrintResult("-11.0R OrElse -9D", -11.0R OrElse -9D) PrintResult("-11.0R OrElse 10.0F", -11.0R OrElse 10.0F) PrintResult("-11.0R OrElse -11.0R", -11.0R OrElse -11.0R) PrintResult("-11.0R OrElse ""12""", -11.0R OrElse "12") PrintResult("-11.0R OrElse TypeCode.Double", -11.0R OrElse TypeCode.Double) PrintResult("""12"" OrElse False", "12" OrElse False) PrintResult("""12"" OrElse True", "12" OrElse True) PrintResult("""12"" OrElse System.SByte.MinValue", "12" OrElse System.SByte.MinValue) PrintResult("""12"" OrElse System.Byte.MaxValue", "12" OrElse System.Byte.MaxValue) PrintResult("""12"" OrElse -3S", "12" OrElse -3S) PrintResult("""12"" OrElse 24US", "12" OrElse 24US) PrintResult("""12"" OrElse -5I", "12" OrElse -5I) PrintResult("""12"" OrElse 26UI", "12" OrElse 26UI) PrintResult("""12"" OrElse -7L", "12" OrElse -7L) PrintResult("""12"" OrElse 28UL", "12" OrElse 28UL) PrintResult("""12"" OrElse -9D", "12" OrElse -9D) PrintResult("""12"" OrElse 10.0F", "12" OrElse 10.0F) PrintResult("""12"" OrElse -11.0R", "12" OrElse -11.0R) PrintResult("""12"" OrElse ""12""", "12" OrElse "12") PrintResult("""12"" OrElse TypeCode.Double", "12" OrElse TypeCode.Double) PrintResult("TypeCode.Double OrElse False", TypeCode.Double OrElse False) PrintResult("TypeCode.Double OrElse True", TypeCode.Double OrElse True) PrintResult("TypeCode.Double OrElse System.SByte.MinValue", TypeCode.Double OrElse System.SByte.MinValue) PrintResult("TypeCode.Double OrElse System.Byte.MaxValue", TypeCode.Double OrElse System.Byte.MaxValue) PrintResult("TypeCode.Double OrElse -3S", TypeCode.Double OrElse -3S) PrintResult("TypeCode.Double OrElse 24US", TypeCode.Double OrElse 24US) PrintResult("TypeCode.Double OrElse -5I", TypeCode.Double OrElse -5I) PrintResult("TypeCode.Double OrElse 26UI", TypeCode.Double OrElse 26UI) PrintResult("TypeCode.Double OrElse -7L", TypeCode.Double OrElse -7L) PrintResult("TypeCode.Double OrElse 28UL", TypeCode.Double OrElse 28UL) PrintResult("TypeCode.Double OrElse -9D", TypeCode.Double OrElse -9D) PrintResult("TypeCode.Double OrElse 10.0F", TypeCode.Double OrElse 10.0F) PrintResult("TypeCode.Double OrElse -11.0R", TypeCode.Double OrElse -11.0R) PrintResult("TypeCode.Double OrElse ""12""", TypeCode.Double OrElse "12") PrintResult("TypeCode.Double OrElse TypeCode.Double", TypeCode.Double OrElse TypeCode.Double) PrintResult("False AndAlso False", False AndAlso False) PrintResult("False AndAlso True", False AndAlso True) PrintResult("False AndAlso System.SByte.MinValue", False AndAlso System.SByte.MinValue) PrintResult("False AndAlso System.Byte.MaxValue", False AndAlso System.Byte.MaxValue) PrintResult("False AndAlso -3S", False AndAlso -3S) PrintResult("False AndAlso 24US", False AndAlso 24US) PrintResult("False AndAlso -5I", False AndAlso -5I) PrintResult("False AndAlso 26UI", False AndAlso 26UI) PrintResult("False AndAlso -7L", False AndAlso -7L) PrintResult("False AndAlso 28UL", False AndAlso 28UL) PrintResult("False AndAlso -9D", False AndAlso -9D) PrintResult("False AndAlso 10.0F", False AndAlso 10.0F) PrintResult("False AndAlso -11.0R", False AndAlso -11.0R) PrintResult("False AndAlso ""12""", False AndAlso "12") PrintResult("False AndAlso TypeCode.Double", False AndAlso TypeCode.Double) PrintResult("True AndAlso False", True AndAlso False) PrintResult("True AndAlso True", True AndAlso True) PrintResult("True AndAlso System.SByte.MinValue", True AndAlso System.SByte.MinValue) PrintResult("True AndAlso System.Byte.MaxValue", True AndAlso System.Byte.MaxValue) PrintResult("True AndAlso -3S", True AndAlso -3S) PrintResult("True AndAlso 24US", True AndAlso 24US) PrintResult("True AndAlso -5I", True AndAlso -5I) PrintResult("True AndAlso 26UI", True AndAlso 26UI) PrintResult("True AndAlso -7L", True AndAlso -7L) PrintResult("True AndAlso 28UL", True AndAlso 28UL) PrintResult("True AndAlso -9D", True AndAlso -9D) PrintResult("True AndAlso 10.0F", True AndAlso 10.0F) PrintResult("True AndAlso -11.0R", True AndAlso -11.0R) PrintResult("True AndAlso ""12""", True AndAlso "12") PrintResult("True AndAlso TypeCode.Double", True AndAlso TypeCode.Double) PrintResult("System.SByte.MinValue AndAlso False", System.SByte.MinValue AndAlso False) PrintResult("System.SByte.MinValue AndAlso True", System.SByte.MinValue AndAlso True) PrintResult("System.SByte.MinValue AndAlso System.SByte.MinValue", System.SByte.MinValue AndAlso System.SByte.MinValue) PrintResult("System.SByte.MinValue AndAlso System.Byte.MaxValue", System.SByte.MinValue AndAlso System.Byte.MaxValue) PrintResult("System.SByte.MinValue AndAlso -3S", System.SByte.MinValue AndAlso -3S) PrintResult("System.SByte.MinValue AndAlso 24US", System.SByte.MinValue AndAlso 24US) PrintResult("System.SByte.MinValue AndAlso -5I", System.SByte.MinValue AndAlso -5I) PrintResult("System.SByte.MinValue AndAlso 26UI", System.SByte.MinValue AndAlso 26UI) PrintResult("System.SByte.MinValue AndAlso -7L", System.SByte.MinValue AndAlso -7L) PrintResult("System.SByte.MinValue AndAlso 28UL", System.SByte.MinValue AndAlso 28UL) PrintResult("System.SByte.MinValue AndAlso -9D", System.SByte.MinValue AndAlso -9D) PrintResult("System.SByte.MinValue AndAlso 10.0F", System.SByte.MinValue AndAlso 10.0F) PrintResult("System.SByte.MinValue AndAlso -11.0R", System.SByte.MinValue AndAlso -11.0R) PrintResult("System.SByte.MinValue AndAlso ""12""", System.SByte.MinValue AndAlso "12") PrintResult("System.SByte.MinValue AndAlso TypeCode.Double", System.SByte.MinValue AndAlso TypeCode.Double) PrintResult("System.Byte.MaxValue AndAlso False", System.Byte.MaxValue AndAlso False) PrintResult("System.Byte.MaxValue AndAlso True", System.Byte.MaxValue AndAlso True) PrintResult("System.Byte.MaxValue AndAlso System.SByte.MinValue", System.Byte.MaxValue AndAlso System.SByte.MinValue) PrintResult("System.Byte.MaxValue AndAlso System.Byte.MaxValue", System.Byte.MaxValue AndAlso System.Byte.MaxValue) PrintResult("System.Byte.MaxValue AndAlso -3S", System.Byte.MaxValue AndAlso -3S) PrintResult("System.Byte.MaxValue AndAlso 24US", System.Byte.MaxValue AndAlso 24US) PrintResult("System.Byte.MaxValue AndAlso -5I", System.Byte.MaxValue AndAlso -5I) PrintResult("System.Byte.MaxValue AndAlso 26UI", System.Byte.MaxValue AndAlso 26UI) PrintResult("System.Byte.MaxValue AndAlso -7L", System.Byte.MaxValue AndAlso -7L) PrintResult("System.Byte.MaxValue AndAlso 28UL", System.Byte.MaxValue AndAlso 28UL) PrintResult("System.Byte.MaxValue AndAlso -9D", System.Byte.MaxValue AndAlso -9D) PrintResult("System.Byte.MaxValue AndAlso 10.0F", System.Byte.MaxValue AndAlso 10.0F) PrintResult("System.Byte.MaxValue AndAlso -11.0R", System.Byte.MaxValue AndAlso -11.0R) PrintResult("System.Byte.MaxValue AndAlso ""12""", System.Byte.MaxValue AndAlso "12") PrintResult("System.Byte.MaxValue AndAlso TypeCode.Double", System.Byte.MaxValue AndAlso TypeCode.Double) PrintResult("-3S AndAlso False", -3S AndAlso False) PrintResult("-3S AndAlso True", -3S AndAlso True) PrintResult("-3S AndAlso System.SByte.MinValue", -3S AndAlso System.SByte.MinValue) PrintResult("-3S AndAlso System.Byte.MaxValue", -3S AndAlso System.Byte.MaxValue) PrintResult("-3S AndAlso -3S", -3S AndAlso -3S) PrintResult("-3S AndAlso 24US", -3S AndAlso 24US) PrintResult("-3S AndAlso -5I", -3S AndAlso -5I) PrintResult("-3S AndAlso 26UI", -3S AndAlso 26UI) PrintResult("-3S AndAlso -7L", -3S AndAlso -7L) PrintResult("-3S AndAlso 28UL", -3S AndAlso 28UL) PrintResult("-3S AndAlso -9D", -3S AndAlso -9D) PrintResult("-3S AndAlso 10.0F", -3S AndAlso 10.0F) PrintResult("-3S AndAlso -11.0R", -3S AndAlso -11.0R) PrintResult("-3S AndAlso ""12""", -3S AndAlso "12") PrintResult("-3S AndAlso TypeCode.Double", -3S AndAlso TypeCode.Double) PrintResult("24US AndAlso False", 24US AndAlso False) PrintResult("24US AndAlso True", 24US AndAlso True) PrintResult("24US AndAlso System.SByte.MinValue", 24US AndAlso System.SByte.MinValue) PrintResult("24US AndAlso System.Byte.MaxValue", 24US AndAlso System.Byte.MaxValue) PrintResult("24US AndAlso -3S", 24US AndAlso -3S) PrintResult("24US AndAlso 24US", 24US AndAlso 24US) PrintResult("24US AndAlso -5I", 24US AndAlso -5I) PrintResult("24US AndAlso 26UI", 24US AndAlso 26UI) PrintResult("24US AndAlso -7L", 24US AndAlso -7L) PrintResult("24US AndAlso 28UL", 24US AndAlso 28UL) PrintResult("24US AndAlso -9D", 24US AndAlso -9D) PrintResult("24US AndAlso 10.0F", 24US AndAlso 10.0F) PrintResult("24US AndAlso -11.0R", 24US AndAlso -11.0R) PrintResult("24US AndAlso ""12""", 24US AndAlso "12") PrintResult("24US AndAlso TypeCode.Double", 24US AndAlso TypeCode.Double) PrintResult("-5I AndAlso False", -5I AndAlso False) PrintResult("-5I AndAlso True", -5I AndAlso True) PrintResult("-5I AndAlso System.SByte.MinValue", -5I AndAlso System.SByte.MinValue) PrintResult("-5I AndAlso System.Byte.MaxValue", -5I AndAlso System.Byte.MaxValue) PrintResult("-5I AndAlso -3S", -5I AndAlso -3S) PrintResult("-5I AndAlso 24US", -5I AndAlso 24US) PrintResult("-5I AndAlso -5I", -5I AndAlso -5I) PrintResult("-5I AndAlso 26UI", -5I AndAlso 26UI) PrintResult("-5I AndAlso -7L", -5I AndAlso -7L) PrintResult("-5I AndAlso 28UL", -5I AndAlso 28UL) PrintResult("-5I AndAlso -9D", -5I AndAlso -9D) PrintResult("-5I AndAlso 10.0F", -5I AndAlso 10.0F) PrintResult("-5I AndAlso -11.0R", -5I AndAlso -11.0R) PrintResult("-5I AndAlso ""12""", -5I AndAlso "12") PrintResult("-5I AndAlso TypeCode.Double", -5I AndAlso TypeCode.Double) PrintResult("26UI AndAlso False", 26UI AndAlso False) PrintResult("26UI AndAlso True", 26UI AndAlso True) PrintResult("26UI AndAlso System.SByte.MinValue", 26UI AndAlso System.SByte.MinValue) PrintResult("26UI AndAlso System.Byte.MaxValue", 26UI AndAlso System.Byte.MaxValue) PrintResult("26UI AndAlso -3S", 26UI AndAlso -3S) PrintResult("26UI AndAlso 24US", 26UI AndAlso 24US) PrintResult("26UI AndAlso -5I", 26UI AndAlso -5I) PrintResult("26UI AndAlso 26UI", 26UI AndAlso 26UI) PrintResult("26UI AndAlso -7L", 26UI AndAlso -7L) PrintResult("26UI AndAlso 28UL", 26UI AndAlso 28UL) PrintResult("26UI AndAlso -9D", 26UI AndAlso -9D) PrintResult("26UI AndAlso 10.0F", 26UI AndAlso 10.0F) PrintResult("26UI AndAlso -11.0R", 26UI AndAlso -11.0R) PrintResult("26UI AndAlso ""12""", 26UI AndAlso "12") PrintResult("26UI AndAlso TypeCode.Double", 26UI AndAlso TypeCode.Double) PrintResult("-7L AndAlso False", -7L AndAlso False) PrintResult("-7L AndAlso True", -7L AndAlso True) PrintResult("-7L AndAlso System.SByte.MinValue", -7L AndAlso System.SByte.MinValue) PrintResult("-7L AndAlso System.Byte.MaxValue", -7L AndAlso System.Byte.MaxValue) PrintResult("-7L AndAlso -3S", -7L AndAlso -3S) PrintResult("-7L AndAlso 24US", -7L AndAlso 24US) PrintResult("-7L AndAlso -5I", -7L AndAlso -5I) PrintResult("-7L AndAlso 26UI", -7L AndAlso 26UI) PrintResult("-7L AndAlso -7L", -7L AndAlso -7L) PrintResult("-7L AndAlso 28UL", -7L AndAlso 28UL) PrintResult("-7L AndAlso -9D", -7L AndAlso -9D) PrintResult("-7L AndAlso 10.0F", -7L AndAlso 10.0F) PrintResult("-7L AndAlso -11.0R", -7L AndAlso -11.0R) PrintResult("-7L AndAlso ""12""", -7L AndAlso "12") PrintResult("-7L AndAlso TypeCode.Double", -7L AndAlso TypeCode.Double) PrintResult("28UL AndAlso False", 28UL AndAlso False) PrintResult("28UL AndAlso True", 28UL AndAlso True) PrintResult("28UL AndAlso System.SByte.MinValue", 28UL AndAlso System.SByte.MinValue) PrintResult("28UL AndAlso System.Byte.MaxValue", 28UL AndAlso System.Byte.MaxValue) PrintResult("28UL AndAlso -3S", 28UL AndAlso -3S) PrintResult("28UL AndAlso 24US", 28UL AndAlso 24US) PrintResult("28UL AndAlso -5I", 28UL AndAlso -5I) PrintResult("28UL AndAlso 26UI", 28UL AndAlso 26UI) PrintResult("28UL AndAlso -7L", 28UL AndAlso -7L) PrintResult("28UL AndAlso 28UL", 28UL AndAlso 28UL) PrintResult("28UL AndAlso -9D", 28UL AndAlso -9D) PrintResult("28UL AndAlso 10.0F", 28UL AndAlso 10.0F) PrintResult("28UL AndAlso -11.0R", 28UL AndAlso -11.0R) PrintResult("28UL AndAlso ""12""", 28UL AndAlso "12") PrintResult("28UL AndAlso TypeCode.Double", 28UL AndAlso TypeCode.Double) PrintResult("-9D AndAlso False", -9D AndAlso False) PrintResult("-9D AndAlso True", -9D AndAlso True) PrintResult("-9D AndAlso System.SByte.MinValue", -9D AndAlso System.SByte.MinValue) PrintResult("-9D AndAlso System.Byte.MaxValue", -9D AndAlso System.Byte.MaxValue) PrintResult("-9D AndAlso -3S", -9D AndAlso -3S) PrintResult("-9D AndAlso 24US", -9D AndAlso 24US) PrintResult("-9D AndAlso -5I", -9D AndAlso -5I) PrintResult("-9D AndAlso 26UI", -9D AndAlso 26UI) PrintResult("-9D AndAlso -7L", -9D AndAlso -7L) PrintResult("-9D AndAlso 28UL", -9D AndAlso 28UL) PrintResult("-9D AndAlso -9D", -9D AndAlso -9D) PrintResult("-9D AndAlso 10.0F", -9D AndAlso 10.0F) PrintResult("-9D AndAlso -11.0R", -9D AndAlso -11.0R) PrintResult("-9D AndAlso ""12""", -9D AndAlso "12") PrintResult("-9D AndAlso TypeCode.Double", -9D AndAlso TypeCode.Double) PrintResult("10.0F AndAlso False", 10.0F AndAlso False) PrintResult("10.0F AndAlso True", 10.0F AndAlso True) PrintResult("10.0F AndAlso System.SByte.MinValue", 10.0F AndAlso System.SByte.MinValue) PrintResult("10.0F AndAlso System.Byte.MaxValue", 10.0F AndAlso System.Byte.MaxValue) PrintResult("10.0F AndAlso -3S", 10.0F AndAlso -3S) PrintResult("10.0F AndAlso 24US", 10.0F AndAlso 24US) PrintResult("10.0F AndAlso -5I", 10.0F AndAlso -5I) PrintResult("10.0F AndAlso 26UI", 10.0F AndAlso 26UI) PrintResult("10.0F AndAlso -7L", 10.0F AndAlso -7L) PrintResult("10.0F AndAlso 28UL", 10.0F AndAlso 28UL) PrintResult("10.0F AndAlso -9D", 10.0F AndAlso -9D) PrintResult("10.0F AndAlso 10.0F", 10.0F AndAlso 10.0F) PrintResult("10.0F AndAlso -11.0R", 10.0F AndAlso -11.0R) PrintResult("10.0F AndAlso ""12""", 10.0F AndAlso "12") PrintResult("10.0F AndAlso TypeCode.Double", 10.0F AndAlso TypeCode.Double) PrintResult("-11.0R AndAlso False", -11.0R AndAlso False) PrintResult("-11.0R AndAlso True", -11.0R AndAlso True) PrintResult("-11.0R AndAlso System.SByte.MinValue", -11.0R AndAlso System.SByte.MinValue) PrintResult("-11.0R AndAlso System.Byte.MaxValue", -11.0R AndAlso System.Byte.MaxValue) PrintResult("-11.0R AndAlso -3S", -11.0R AndAlso -3S) PrintResult("-11.0R AndAlso 24US", -11.0R AndAlso 24US) PrintResult("-11.0R AndAlso -5I", -11.0R AndAlso -5I) PrintResult("-11.0R AndAlso 26UI", -11.0R AndAlso 26UI) PrintResult("-11.0R AndAlso -7L", -11.0R AndAlso -7L) PrintResult("-11.0R AndAlso 28UL", -11.0R AndAlso 28UL) PrintResult("-11.0R AndAlso -9D", -11.0R AndAlso -9D) PrintResult("-11.0R AndAlso 10.0F", -11.0R AndAlso 10.0F) PrintResult("-11.0R AndAlso -11.0R", -11.0R AndAlso -11.0R) PrintResult("-11.0R AndAlso ""12""", -11.0R AndAlso "12") PrintResult("-11.0R AndAlso TypeCode.Double", -11.0R AndAlso TypeCode.Double) PrintResult("""12"" AndAlso False", "12" AndAlso False) PrintResult("""12"" AndAlso True", "12" AndAlso True) PrintResult("""12"" AndAlso System.SByte.MinValue", "12" AndAlso System.SByte.MinValue) PrintResult("""12"" AndAlso System.Byte.MaxValue", "12" AndAlso System.Byte.MaxValue) PrintResult("""12"" AndAlso -3S", "12" AndAlso -3S) PrintResult("""12"" AndAlso 24US", "12" AndAlso 24US) PrintResult("""12"" AndAlso -5I", "12" AndAlso -5I) PrintResult("""12"" AndAlso 26UI", "12" AndAlso 26UI) PrintResult("""12"" AndAlso -7L", "12" AndAlso -7L) PrintResult("""12"" AndAlso 28UL", "12" AndAlso 28UL) PrintResult("""12"" AndAlso -9D", "12" AndAlso -9D) PrintResult("""12"" AndAlso 10.0F", "12" AndAlso 10.0F) PrintResult("""12"" AndAlso -11.0R", "12" AndAlso -11.0R) PrintResult("""12"" AndAlso ""12""", "12" AndAlso "12") PrintResult("""12"" AndAlso TypeCode.Double", "12" AndAlso TypeCode.Double) PrintResult("TypeCode.Double AndAlso False", TypeCode.Double AndAlso False) PrintResult("TypeCode.Double AndAlso True", TypeCode.Double AndAlso True) PrintResult("TypeCode.Double AndAlso System.SByte.MinValue", TypeCode.Double AndAlso System.SByte.MinValue) PrintResult("TypeCode.Double AndAlso System.Byte.MaxValue", TypeCode.Double AndAlso System.Byte.MaxValue) PrintResult("TypeCode.Double AndAlso -3S", TypeCode.Double AndAlso -3S) PrintResult("TypeCode.Double AndAlso 24US", TypeCode.Double AndAlso 24US) PrintResult("TypeCode.Double AndAlso -5I", TypeCode.Double AndAlso -5I) PrintResult("TypeCode.Double AndAlso 26UI", TypeCode.Double AndAlso 26UI) PrintResult("TypeCode.Double AndAlso -7L", TypeCode.Double AndAlso -7L) PrintResult("TypeCode.Double AndAlso 28UL", TypeCode.Double AndAlso 28UL) PrintResult("TypeCode.Double AndAlso -9D", TypeCode.Double AndAlso -9D) PrintResult("TypeCode.Double AndAlso 10.0F", TypeCode.Double AndAlso 10.0F) PrintResult("TypeCode.Double AndAlso -11.0R", TypeCode.Double AndAlso -11.0R) PrintResult("TypeCode.Double AndAlso ""12""", TypeCode.Double AndAlso "12") PrintResult("TypeCode.Double AndAlso TypeCode.Double", TypeCode.Double AndAlso TypeCode.Double) PrintResult("False & False", False & False) PrintResult("False & True", False & True) PrintResult("False & System.SByte.MinValue", False & System.SByte.MinValue) PrintResult("False & System.Byte.MaxValue", False & System.Byte.MaxValue) PrintResult("False & -3S", False & -3S) PrintResult("False & 24US", False & 24US) PrintResult("False & -5I", False & -5I) PrintResult("False & 26UI", False & 26UI) PrintResult("False & -7L", False & -7L) PrintResult("False & 28UL", False & 28UL) PrintResult("False & -9D", False & -9D) PrintResult("False & 10.0F", False & 10.0F) PrintResult("False & -11.0R", False & -11.0R) PrintResult("False & ""12""", False & "12") PrintResult("False & TypeCode.Double", False & TypeCode.Double) PrintResult("True & False", True & False) PrintResult("True & True", True & True) PrintResult("True & System.SByte.MinValue", True & System.SByte.MinValue) PrintResult("True & System.Byte.MaxValue", True & System.Byte.MaxValue) PrintResult("True & -3S", True & -3S) PrintResult("True & 24US", True & 24US) PrintResult("True & -5I", True & -5I) PrintResult("True & 26UI", True & 26UI) PrintResult("True & -7L", True & -7L) PrintResult("True & 28UL", True & 28UL) PrintResult("True & -9D", True & -9D) PrintResult("True & 10.0F", True & 10.0F) PrintResult("True & -11.0R", True & -11.0R) PrintResult("True & ""12""", True & "12") PrintResult("True & TypeCode.Double", True & TypeCode.Double) PrintResult("System.SByte.MinValue & False", System.SByte.MinValue & False) PrintResult("System.SByte.MinValue & True", System.SByte.MinValue & True) PrintResult("System.SByte.MinValue & System.SByte.MinValue", System.SByte.MinValue & System.SByte.MinValue) PrintResult("System.SByte.MinValue & System.Byte.MaxValue", System.SByte.MinValue & System.Byte.MaxValue) PrintResult("System.SByte.MinValue & -3S", System.SByte.MinValue & -3S) PrintResult("System.SByte.MinValue & 24US", System.SByte.MinValue & 24US) PrintResult("System.SByte.MinValue & -5I", System.SByte.MinValue & -5I) PrintResult("System.SByte.MinValue & 26UI", System.SByte.MinValue & 26UI) PrintResult("System.SByte.MinValue & -7L", System.SByte.MinValue & -7L) PrintResult("System.SByte.MinValue & 28UL", System.SByte.MinValue & 28UL) PrintResult("System.SByte.MinValue & -9D", System.SByte.MinValue & -9D) PrintResult("System.SByte.MinValue & 10.0F", System.SByte.MinValue & 10.0F) PrintResult("System.SByte.MinValue & -11.0R", System.SByte.MinValue & -11.0R) PrintResult("System.SByte.MinValue & ""12""", System.SByte.MinValue & "12") PrintResult("System.SByte.MinValue & TypeCode.Double", System.SByte.MinValue & TypeCode.Double) PrintResult("System.Byte.MaxValue & False", System.Byte.MaxValue & False) PrintResult("System.Byte.MaxValue & True", System.Byte.MaxValue & True) PrintResult("System.Byte.MaxValue & System.SByte.MinValue", System.Byte.MaxValue & System.SByte.MinValue) PrintResult("System.Byte.MaxValue & System.Byte.MaxValue", System.Byte.MaxValue & System.Byte.MaxValue) PrintResult("System.Byte.MaxValue & -3S", System.Byte.MaxValue & -3S) PrintResult("System.Byte.MaxValue & 24US", System.Byte.MaxValue & 24US) PrintResult("System.Byte.MaxValue & -5I", System.Byte.MaxValue & -5I) PrintResult("System.Byte.MaxValue & 26UI", System.Byte.MaxValue & 26UI) PrintResult("System.Byte.MaxValue & -7L", System.Byte.MaxValue & -7L) PrintResult("System.Byte.MaxValue & 28UL", System.Byte.MaxValue & 28UL) PrintResult("System.Byte.MaxValue & -9D", System.Byte.MaxValue & -9D) PrintResult("System.Byte.MaxValue & 10.0F", System.Byte.MaxValue & 10.0F) PrintResult("System.Byte.MaxValue & -11.0R", System.Byte.MaxValue & -11.0R) PrintResult("System.Byte.MaxValue & ""12""", System.Byte.MaxValue & "12") PrintResult("System.Byte.MaxValue & TypeCode.Double", System.Byte.MaxValue & TypeCode.Double) PrintResult("-3S & False", -3S & False) PrintResult("-3S & True", -3S & True) PrintResult("-3S & System.SByte.MinValue", -3S & System.SByte.MinValue) PrintResult("-3S & System.Byte.MaxValue", -3S & System.Byte.MaxValue) PrintResult("-3S & -3S", -3S & -3S) PrintResult("-3S & 24US", -3S & 24US) PrintResult("-3S & -5I", -3S & -5I) PrintResult("-3S & 26UI", -3S & 26UI) PrintResult("-3S & -7L", -3S & -7L) PrintResult("-3S & 28UL", -3S & 28UL) PrintResult("-3S & -9D", -3S & -9D) PrintResult("-3S & 10.0F", -3S & 10.0F) PrintResult("-3S & -11.0R", -3S & -11.0R) PrintResult("-3S & ""12""", -3S & "12") PrintResult("-3S & TypeCode.Double", -3S & TypeCode.Double) PrintResult("24US & False", 24US & False) PrintResult("24US & True", 24US & True) PrintResult("24US & System.SByte.MinValue", 24US & System.SByte.MinValue) PrintResult("24US & System.Byte.MaxValue", 24US & System.Byte.MaxValue) PrintResult("24US & -3S", 24US & -3S) PrintResult("24US & 24US", 24US & 24US) PrintResult("24US & -5I", 24US & -5I) PrintResult("24US & 26UI", 24US & 26UI) PrintResult("24US & -7L", 24US & -7L) PrintResult("24US & 28UL", 24US & 28UL) PrintResult("24US & -9D", 24US & -9D) PrintResult("24US & 10.0F", 24US & 10.0F) PrintResult("24US & -11.0R", 24US & -11.0R) PrintResult("24US & ""12""", 24US & "12") PrintResult("24US & TypeCode.Double", 24US & TypeCode.Double) PrintResult("-5I & False", -5I & False) PrintResult("-5I & True", -5I & True) PrintResult("-5I & System.SByte.MinValue", -5I & System.SByte.MinValue) PrintResult("-5I & System.Byte.MaxValue", -5I & System.Byte.MaxValue) PrintResult("-5I & -3S", -5I & -3S) PrintResult("-5I & 24US", -5I & 24US) PrintResult("-5I & -5I", -5I & -5I) PrintResult("-5I & 26UI", -5I & 26UI) PrintResult("-5I & -7L", -5I & -7L) PrintResult("-5I & 28UL", -5I & 28UL) PrintResult("-5I & -9D", -5I & -9D) PrintResult("-5I & 10.0F", -5I & 10.0F) PrintResult("-5I & -11.0R", -5I & -11.0R) PrintResult("-5I & ""12""", -5I & "12") PrintResult("-5I & TypeCode.Double", -5I & TypeCode.Double) PrintResult("26UI & False", 26UI & False) PrintResult("26UI & True", 26UI & True) PrintResult("26UI & System.SByte.MinValue", 26UI & System.SByte.MinValue) PrintResult("26UI & System.Byte.MaxValue", 26UI & System.Byte.MaxValue) PrintResult("26UI & -3S", 26UI & -3S) PrintResult("26UI & 24US", 26UI & 24US) PrintResult("26UI & -5I", 26UI & -5I) PrintResult("26UI & 26UI", 26UI & 26UI) PrintResult("26UI & -7L", 26UI & -7L) PrintResult("26UI & 28UL", 26UI & 28UL) PrintResult("26UI & -9D", 26UI & -9D) PrintResult("26UI & 10.0F", 26UI & 10.0F) PrintResult("26UI & -11.0R", 26UI & -11.0R) PrintResult("26UI & ""12""", 26UI & "12") PrintResult("26UI & TypeCode.Double", 26UI & TypeCode.Double) PrintResult("-7L & False", -7L & False) PrintResult("-7L & True", -7L & True) PrintResult("-7L & System.SByte.MinValue", -7L & System.SByte.MinValue) PrintResult("-7L & System.Byte.MaxValue", -7L & System.Byte.MaxValue) PrintResult("-7L & -3S", -7L & -3S) PrintResult("-7L & 24US", -7L & 24US) PrintResult("-7L & -5I", -7L & -5I) PrintResult("-7L & 26UI", -7L & 26UI) PrintResult("-7L & -7L", -7L & -7L) PrintResult("-7L & 28UL", -7L & 28UL) PrintResult("-7L & -9D", -7L & -9D) PrintResult("-7L & 10.0F", -7L & 10.0F) PrintResult("-7L & -11.0R", -7L & -11.0R) PrintResult("-7L & ""12""", -7L & "12") PrintResult("-7L & TypeCode.Double", -7L & TypeCode.Double) PrintResult("28UL & False", 28UL & False) PrintResult("28UL & True", 28UL & True) PrintResult("28UL & System.SByte.MinValue", 28UL & System.SByte.MinValue) PrintResult("28UL & System.Byte.MaxValue", 28UL & System.Byte.MaxValue) PrintResult("28UL & -3S", 28UL & -3S) PrintResult("28UL & 24US", 28UL & 24US) PrintResult("28UL & -5I", 28UL & -5I) PrintResult("28UL & 26UI", 28UL & 26UI) PrintResult("28UL & -7L", 28UL & -7L) PrintResult("28UL & 28UL", 28UL & 28UL) PrintResult("28UL & -9D", 28UL & -9D) PrintResult("28UL & 10.0F", 28UL & 10.0F) PrintResult("28UL & -11.0R", 28UL & -11.0R) PrintResult("28UL & ""12""", 28UL & "12") PrintResult("28UL & TypeCode.Double", 28UL & TypeCode.Double) PrintResult("-9D & False", -9D & False) PrintResult("-9D & True", -9D & True) PrintResult("-9D & System.SByte.MinValue", -9D & System.SByte.MinValue) PrintResult("-9D & System.Byte.MaxValue", -9D & System.Byte.MaxValue) PrintResult("-9D & -3S", -9D & -3S) PrintResult("-9D & 24US", -9D & 24US) PrintResult("-9D & -5I", -9D & -5I) PrintResult("-9D & 26UI", -9D & 26UI) PrintResult("-9D & -7L", -9D & -7L) PrintResult("-9D & 28UL", -9D & 28UL) PrintResult("-9D & -9D", -9D & -9D) PrintResult("-9D & 10.0F", -9D & 10.0F) PrintResult("-9D & -11.0R", -9D & -11.0R) PrintResult("-9D & ""12""", -9D & "12") PrintResult("-9D & TypeCode.Double", -9D & TypeCode.Double) PrintResult("10.0F & False", 10.0F & False) PrintResult("10.0F & True", 10.0F & True) PrintResult("10.0F & System.SByte.MinValue", 10.0F & System.SByte.MinValue) PrintResult("10.0F & System.Byte.MaxValue", 10.0F & System.Byte.MaxValue) PrintResult("10.0F & -3S", 10.0F & -3S) PrintResult("10.0F & 24US", 10.0F & 24US) PrintResult("10.0F & -5I", 10.0F & -5I) PrintResult("10.0F & 26UI", 10.0F & 26UI) PrintResult("10.0F & -7L", 10.0F & -7L) PrintResult("10.0F & 28UL", 10.0F & 28UL) PrintResult("10.0F & -9D", 10.0F & -9D) PrintResult("10.0F & 10.0F", 10.0F & 10.0F) PrintResult("10.0F & -11.0R", 10.0F & -11.0R) PrintResult("10.0F & ""12""", 10.0F & "12") PrintResult("10.0F & TypeCode.Double", 10.0F & TypeCode.Double) PrintResult("-11.0R & False", -11.0R & False) PrintResult("-11.0R & True", -11.0R & True) PrintResult("-11.0R & System.SByte.MinValue", -11.0R & System.SByte.MinValue) PrintResult("-11.0R & System.Byte.MaxValue", -11.0R & System.Byte.MaxValue) PrintResult("-11.0R & -3S", -11.0R & -3S) PrintResult("-11.0R & 24US", -11.0R & 24US) PrintResult("-11.0R & -5I", -11.0R & -5I) PrintResult("-11.0R & 26UI", -11.0R & 26UI) PrintResult("-11.0R & -7L", -11.0R & -7L) PrintResult("-11.0R & 28UL", -11.0R & 28UL) PrintResult("-11.0R & -9D", -11.0R & -9D) PrintResult("-11.0R & 10.0F", -11.0R & 10.0F) PrintResult("-11.0R & -11.0R", -11.0R & -11.0R) PrintResult("-11.0R & ""12""", -11.0R & "12") PrintResult("-11.0R & TypeCode.Double", -11.0R & TypeCode.Double) PrintResult("""12"" & False", "12" & False) PrintResult("""12"" & True", "12" & True) PrintResult("""12"" & System.SByte.MinValue", "12" & System.SByte.MinValue) PrintResult("""12"" & System.Byte.MaxValue", "12" & System.Byte.MaxValue) PrintResult("""12"" & -3S", "12" & -3S) PrintResult("""12"" & 24US", "12" & 24US) PrintResult("""12"" & -5I", "12" & -5I) PrintResult("""12"" & 26UI", "12" & 26UI) PrintResult("""12"" & -7L", "12" & -7L) PrintResult("""12"" & 28UL", "12" & 28UL) PrintResult("""12"" & -9D", "12" & -9D) PrintResult("""12"" & 10.0F", "12" & 10.0F) PrintResult("""12"" & -11.0R", "12" & -11.0R) PrintResult("""12"" & ""12""", "12" & "12") PrintResult("""12"" & TypeCode.Double", "12" & TypeCode.Double) PrintResult("TypeCode.Double & False", TypeCode.Double & False) PrintResult("TypeCode.Double & True", TypeCode.Double & True) PrintResult("TypeCode.Double & System.SByte.MinValue", TypeCode.Double & System.SByte.MinValue) PrintResult("TypeCode.Double & System.Byte.MaxValue", TypeCode.Double & System.Byte.MaxValue) PrintResult("TypeCode.Double & -3S", TypeCode.Double & -3S) PrintResult("TypeCode.Double & 24US", TypeCode.Double & 24US) PrintResult("TypeCode.Double & -5I", TypeCode.Double & -5I) PrintResult("TypeCode.Double & 26UI", TypeCode.Double & 26UI) PrintResult("TypeCode.Double & -7L", TypeCode.Double & -7L) PrintResult("TypeCode.Double & 28UL", TypeCode.Double & 28UL) PrintResult("TypeCode.Double & -9D", TypeCode.Double & -9D) PrintResult("TypeCode.Double & 10.0F", TypeCode.Double & 10.0F) PrintResult("TypeCode.Double & -11.0R", TypeCode.Double & -11.0R) PrintResult("TypeCode.Double & ""12""", TypeCode.Double & "12") PrintResult("TypeCode.Double & TypeCode.Double", TypeCode.Double & TypeCode.Double) PrintResult("False Like False", False Like False) PrintResult("False Like True", False Like True) PrintResult("False Like System.SByte.MinValue", False Like System.SByte.MinValue) PrintResult("False Like System.Byte.MaxValue", False Like System.Byte.MaxValue) PrintResult("False Like -3S", False Like -3S) PrintResult("False Like 24US", False Like 24US) PrintResult("False Like -5I", False Like -5I) PrintResult("False Like 26UI", False Like 26UI) PrintResult("False Like -7L", False Like -7L) PrintResult("False Like 28UL", False Like 28UL) PrintResult("False Like -9D", False Like -9D) PrintResult("False Like 10.0F", False Like 10.0F) PrintResult("False Like -11.0R", False Like -11.0R) PrintResult("False Like ""12""", False Like "12") PrintResult("False Like TypeCode.Double", False Like TypeCode.Double) PrintResult("True Like False", True Like False) PrintResult("True Like True", True Like True) PrintResult("True Like System.SByte.MinValue", True Like System.SByte.MinValue) PrintResult("True Like System.Byte.MaxValue", True Like System.Byte.MaxValue) PrintResult("True Like -3S", True Like -3S) PrintResult("True Like 24US", True Like 24US) PrintResult("True Like -5I", True Like -5I) PrintResult("True Like 26UI", True Like 26UI) PrintResult("True Like -7L", True Like -7L) PrintResult("True Like 28UL", True Like 28UL) PrintResult("True Like -9D", True Like -9D) PrintResult("True Like 10.0F", True Like 10.0F) PrintResult("True Like -11.0R", True Like -11.0R) PrintResult("True Like ""12""", True Like "12") PrintResult("True Like TypeCode.Double", True Like TypeCode.Double) PrintResult("System.SByte.MinValue Like False", System.SByte.MinValue Like False) PrintResult("System.SByte.MinValue Like True", System.SByte.MinValue Like True) PrintResult("System.SByte.MinValue Like System.SByte.MinValue", System.SByte.MinValue Like System.SByte.MinValue) PrintResult("System.SByte.MinValue Like System.Byte.MaxValue", System.SByte.MinValue Like System.Byte.MaxValue) PrintResult("System.SByte.MinValue Like -3S", System.SByte.MinValue Like -3S) PrintResult("System.SByte.MinValue Like 24US", System.SByte.MinValue Like 24US) PrintResult("System.SByte.MinValue Like -5I", System.SByte.MinValue Like -5I) PrintResult("System.SByte.MinValue Like 26UI", System.SByte.MinValue Like 26UI) PrintResult("System.SByte.MinValue Like -7L", System.SByte.MinValue Like -7L) PrintResult("System.SByte.MinValue Like 28UL", System.SByte.MinValue Like 28UL) PrintResult("System.SByte.MinValue Like -9D", System.SByte.MinValue Like -9D) PrintResult("System.SByte.MinValue Like 10.0F", System.SByte.MinValue Like 10.0F) PrintResult("System.SByte.MinValue Like -11.0R", System.SByte.MinValue Like -11.0R) PrintResult("System.SByte.MinValue Like ""12""", System.SByte.MinValue Like "12") PrintResult("System.SByte.MinValue Like TypeCode.Double", System.SByte.MinValue Like TypeCode.Double) PrintResult("System.Byte.MaxValue Like False", System.Byte.MaxValue Like False) PrintResult("System.Byte.MaxValue Like True", System.Byte.MaxValue Like True) PrintResult("System.Byte.MaxValue Like System.SByte.MinValue", System.Byte.MaxValue Like System.SByte.MinValue) PrintResult("System.Byte.MaxValue Like System.Byte.MaxValue", System.Byte.MaxValue Like System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Like -3S", System.Byte.MaxValue Like -3S) PrintResult("System.Byte.MaxValue Like 24US", System.Byte.MaxValue Like 24US) PrintResult("System.Byte.MaxValue Like -5I", System.Byte.MaxValue Like -5I) PrintResult("System.Byte.MaxValue Like 26UI", System.Byte.MaxValue Like 26UI) PrintResult("System.Byte.MaxValue Like -7L", System.Byte.MaxValue Like -7L) PrintResult("System.Byte.MaxValue Like 28UL", System.Byte.MaxValue Like 28UL) PrintResult("System.Byte.MaxValue Like -9D", System.Byte.MaxValue Like -9D) PrintResult("System.Byte.MaxValue Like 10.0F", System.Byte.MaxValue Like 10.0F) PrintResult("System.Byte.MaxValue Like -11.0R", System.Byte.MaxValue Like -11.0R) PrintResult("System.Byte.MaxValue Like ""12""", System.Byte.MaxValue Like "12") PrintResult("System.Byte.MaxValue Like TypeCode.Double", System.Byte.MaxValue Like TypeCode.Double) PrintResult("-3S Like False", -3S Like False) PrintResult("-3S Like True", -3S Like True) PrintResult("-3S Like System.SByte.MinValue", -3S Like System.SByte.MinValue) PrintResult("-3S Like System.Byte.MaxValue", -3S Like System.Byte.MaxValue) PrintResult("-3S Like -3S", -3S Like -3S) PrintResult("-3S Like 24US", -3S Like 24US) PrintResult("-3S Like -5I", -3S Like -5I) PrintResult("-3S Like 26UI", -3S Like 26UI) PrintResult("-3S Like -7L", -3S Like -7L) PrintResult("-3S Like 28UL", -3S Like 28UL) PrintResult("-3S Like -9D", -3S Like -9D) PrintResult("-3S Like 10.0F", -3S Like 10.0F) PrintResult("-3S Like -11.0R", -3S Like -11.0R) PrintResult("-3S Like ""12""", -3S Like "12") PrintResult("-3S Like TypeCode.Double", -3S Like TypeCode.Double) PrintResult("24US Like False", 24US Like False) PrintResult("24US Like True", 24US Like True) PrintResult("24US Like System.SByte.MinValue", 24US Like System.SByte.MinValue) PrintResult("24US Like System.Byte.MaxValue", 24US Like System.Byte.MaxValue) PrintResult("24US Like -3S", 24US Like -3S) PrintResult("24US Like 24US", 24US Like 24US) PrintResult("24US Like -5I", 24US Like -5I) PrintResult("24US Like 26UI", 24US Like 26UI) PrintResult("24US Like -7L", 24US Like -7L) PrintResult("24US Like 28UL", 24US Like 28UL) PrintResult("24US Like -9D", 24US Like -9D) PrintResult("24US Like 10.0F", 24US Like 10.0F) PrintResult("24US Like -11.0R", 24US Like -11.0R) PrintResult("24US Like ""12""", 24US Like "12") PrintResult("24US Like TypeCode.Double", 24US Like TypeCode.Double) PrintResult("-5I Like False", -5I Like False) PrintResult("-5I Like True", -5I Like True) PrintResult("-5I Like System.SByte.MinValue", -5I Like System.SByte.MinValue) PrintResult("-5I Like System.Byte.MaxValue", -5I Like System.Byte.MaxValue) PrintResult("-5I Like -3S", -5I Like -3S) PrintResult("-5I Like 24US", -5I Like 24US) PrintResult("-5I Like -5I", -5I Like -5I) PrintResult("-5I Like 26UI", -5I Like 26UI) PrintResult("-5I Like -7L", -5I Like -7L) PrintResult("-5I Like 28UL", -5I Like 28UL) PrintResult("-5I Like -9D", -5I Like -9D) PrintResult("-5I Like 10.0F", -5I Like 10.0F) PrintResult("-5I Like -11.0R", -5I Like -11.0R) PrintResult("-5I Like ""12""", -5I Like "12") PrintResult("-5I Like TypeCode.Double", -5I Like TypeCode.Double) PrintResult("26UI Like False", 26UI Like False) PrintResult("26UI Like True", 26UI Like True) PrintResult("26UI Like System.SByte.MinValue", 26UI Like System.SByte.MinValue) PrintResult("26UI Like System.Byte.MaxValue", 26UI Like System.Byte.MaxValue) PrintResult("26UI Like -3S", 26UI Like -3S) PrintResult("26UI Like 24US", 26UI Like 24US) PrintResult("26UI Like -5I", 26UI Like -5I) PrintResult("26UI Like 26UI", 26UI Like 26UI) PrintResult("26UI Like -7L", 26UI Like -7L) PrintResult("26UI Like 28UL", 26UI Like 28UL) PrintResult("26UI Like -9D", 26UI Like -9D) PrintResult("26UI Like 10.0F", 26UI Like 10.0F) PrintResult("26UI Like -11.0R", 26UI Like -11.0R) PrintResult("26UI Like ""12""", 26UI Like "12") PrintResult("26UI Like TypeCode.Double", 26UI Like TypeCode.Double) PrintResult("-7L Like False", -7L Like False) PrintResult("-7L Like True", -7L Like True) PrintResult("-7L Like System.SByte.MinValue", -7L Like System.SByte.MinValue) PrintResult("-7L Like System.Byte.MaxValue", -7L Like System.Byte.MaxValue) PrintResult("-7L Like -3S", -7L Like -3S) PrintResult("-7L Like 24US", -7L Like 24US) PrintResult("-7L Like -5I", -7L Like -5I) PrintResult("-7L Like 26UI", -7L Like 26UI) PrintResult("-7L Like -7L", -7L Like -7L) PrintResult("-7L Like 28UL", -7L Like 28UL) PrintResult("-7L Like -9D", -7L Like -9D) PrintResult("-7L Like 10.0F", -7L Like 10.0F) PrintResult("-7L Like -11.0R", -7L Like -11.0R) PrintResult("-7L Like ""12""", -7L Like "12") PrintResult("-7L Like TypeCode.Double", -7L Like TypeCode.Double) PrintResult("28UL Like False", 28UL Like False) PrintResult("28UL Like True", 28UL Like True) PrintResult("28UL Like System.SByte.MinValue", 28UL Like System.SByte.MinValue) PrintResult("28UL Like System.Byte.MaxValue", 28UL Like System.Byte.MaxValue) PrintResult("28UL Like -3S", 28UL Like -3S) PrintResult("28UL Like 24US", 28UL Like 24US) PrintResult("28UL Like -5I", 28UL Like -5I) PrintResult("28UL Like 26UI", 28UL Like 26UI) PrintResult("28UL Like -7L", 28UL Like -7L) PrintResult("28UL Like 28UL", 28UL Like 28UL) PrintResult("28UL Like -9D", 28UL Like -9D) PrintResult("28UL Like 10.0F", 28UL Like 10.0F) PrintResult("28UL Like -11.0R", 28UL Like -11.0R) PrintResult("28UL Like ""12""", 28UL Like "12") PrintResult("28UL Like TypeCode.Double", 28UL Like TypeCode.Double) PrintResult("-9D Like False", -9D Like False) PrintResult("-9D Like True", -9D Like True) PrintResult("-9D Like System.SByte.MinValue", -9D Like System.SByte.MinValue) PrintResult("-9D Like System.Byte.MaxValue", -9D Like System.Byte.MaxValue) PrintResult("-9D Like -3S", -9D Like -3S) PrintResult("-9D Like 24US", -9D Like 24US) PrintResult("-9D Like -5I", -9D Like -5I) PrintResult("-9D Like 26UI", -9D Like 26UI) PrintResult("-9D Like -7L", -9D Like -7L) PrintResult("-9D Like 28UL", -9D Like 28UL) PrintResult("-9D Like -9D", -9D Like -9D) PrintResult("-9D Like 10.0F", -9D Like 10.0F) PrintResult("-9D Like -11.0R", -9D Like -11.0R) PrintResult("-9D Like ""12""", -9D Like "12") PrintResult("-9D Like TypeCode.Double", -9D Like TypeCode.Double) PrintResult("10.0F Like False", 10.0F Like False) PrintResult("10.0F Like True", 10.0F Like True) PrintResult("10.0F Like System.SByte.MinValue", 10.0F Like System.SByte.MinValue) PrintResult("10.0F Like System.Byte.MaxValue", 10.0F Like System.Byte.MaxValue) PrintResult("10.0F Like -3S", 10.0F Like -3S) PrintResult("10.0F Like 24US", 10.0F Like 24US) PrintResult("10.0F Like -5I", 10.0F Like -5I) PrintResult("10.0F Like 26UI", 10.0F Like 26UI) PrintResult("10.0F Like -7L", 10.0F Like -7L) PrintResult("10.0F Like 28UL", 10.0F Like 28UL) PrintResult("10.0F Like -9D", 10.0F Like -9D) PrintResult("10.0F Like 10.0F", 10.0F Like 10.0F) PrintResult("10.0F Like -11.0R", 10.0F Like -11.0R) PrintResult("10.0F Like ""12""", 10.0F Like "12") PrintResult("10.0F Like TypeCode.Double", 10.0F Like TypeCode.Double) PrintResult("-11.0R Like False", -11.0R Like False) PrintResult("-11.0R Like True", -11.0R Like True) PrintResult("-11.0R Like System.SByte.MinValue", -11.0R Like System.SByte.MinValue) PrintResult("-11.0R Like System.Byte.MaxValue", -11.0R Like System.Byte.MaxValue) PrintResult("-11.0R Like -3S", -11.0R Like -3S) PrintResult("-11.0R Like 24US", -11.0R Like 24US) PrintResult("-11.0R Like -5I", -11.0R Like -5I) PrintResult("-11.0R Like 26UI", -11.0R Like 26UI) PrintResult("-11.0R Like -7L", -11.0R Like -7L) PrintResult("-11.0R Like 28UL", -11.0R Like 28UL) PrintResult("-11.0R Like -9D", -11.0R Like -9D) PrintResult("-11.0R Like 10.0F", -11.0R Like 10.0F) PrintResult("-11.0R Like -11.0R", -11.0R Like -11.0R) PrintResult("-11.0R Like ""12""", -11.0R Like "12") PrintResult("-11.0R Like TypeCode.Double", -11.0R Like TypeCode.Double) PrintResult("""12"" Like False", "12" Like False) PrintResult("""12"" Like True", "12" Like True) PrintResult("""12"" Like System.SByte.MinValue", "12" Like System.SByte.MinValue) PrintResult("""12"" Like System.Byte.MaxValue", "12" Like System.Byte.MaxValue) PrintResult("""12"" Like -3S", "12" Like -3S) PrintResult("""12"" Like 24US", "12" Like 24US) PrintResult("""12"" Like -5I", "12" Like -5I) PrintResult("""12"" Like 26UI", "12" Like 26UI) PrintResult("""12"" Like -7L", "12" Like -7L) PrintResult("""12"" Like 28UL", "12" Like 28UL) PrintResult("""12"" Like -9D", "12" Like -9D) PrintResult("""12"" Like 10.0F", "12" Like 10.0F) PrintResult("""12"" Like -11.0R", "12" Like -11.0R) PrintResult("""12"" Like ""12""", "12" Like "12") PrintResult("""12"" Like TypeCode.Double", "12" Like TypeCode.Double) PrintResult("TypeCode.Double Like False", TypeCode.Double Like False) PrintResult("TypeCode.Double Like True", TypeCode.Double Like True) PrintResult("TypeCode.Double Like System.SByte.MinValue", TypeCode.Double Like System.SByte.MinValue) PrintResult("TypeCode.Double Like System.Byte.MaxValue", TypeCode.Double Like System.Byte.MaxValue) PrintResult("TypeCode.Double Like -3S", TypeCode.Double Like -3S) PrintResult("TypeCode.Double Like 24US", TypeCode.Double Like 24US) PrintResult("TypeCode.Double Like -5I", TypeCode.Double Like -5I) PrintResult("TypeCode.Double Like 26UI", TypeCode.Double Like 26UI) PrintResult("TypeCode.Double Like -7L", TypeCode.Double Like -7L) PrintResult("TypeCode.Double Like 28UL", TypeCode.Double Like 28UL) PrintResult("TypeCode.Double Like -9D", TypeCode.Double Like -9D) PrintResult("TypeCode.Double Like 10.0F", TypeCode.Double Like 10.0F) PrintResult("TypeCode.Double Like -11.0R", TypeCode.Double Like -11.0R) PrintResult("TypeCode.Double Like ""12""", TypeCode.Double Like "12") PrintResult("TypeCode.Double Like TypeCode.Double", TypeCode.Double Like TypeCode.Double) PrintResult("False = False", False = False) PrintResult("False = True", False = True) PrintResult("False = System.SByte.MinValue", False = System.SByte.MinValue) PrintResult("False = System.Byte.MaxValue", False = System.Byte.MaxValue) PrintResult("False = -3S", False = -3S) PrintResult("False = 24US", False = 24US) PrintResult("False = -5I", False = -5I) PrintResult("False = 26UI", False = 26UI) PrintResult("False = -7L", False = -7L) PrintResult("False = 28UL", False = 28UL) PrintResult("False = -9D", False = -9D) PrintResult("False = 10.0F", False = 10.0F) PrintResult("False = -11.0R", False = -11.0R) PrintResult("False = ""12""", False = "12") PrintResult("False = TypeCode.Double", False = TypeCode.Double) PrintResult("True = False", True = False) PrintResult("True = True", True = True) PrintResult("True = System.SByte.MinValue", True = System.SByte.MinValue) PrintResult("True = System.Byte.MaxValue", True = System.Byte.MaxValue) PrintResult("True = -3S", True = -3S) PrintResult("True = 24US", True = 24US) PrintResult("True = -5I", True = -5I) PrintResult("True = 26UI", True = 26UI) PrintResult("True = -7L", True = -7L) PrintResult("True = 28UL", True = 28UL) PrintResult("True = -9D", True = -9D) PrintResult("True = 10.0F", True = 10.0F) PrintResult("True = -11.0R", True = -11.0R) PrintResult("True = ""12""", True = "12") PrintResult("True = TypeCode.Double", True = TypeCode.Double) PrintResult("System.SByte.MinValue = False", System.SByte.MinValue = False) PrintResult("System.SByte.MinValue = True", System.SByte.MinValue = True) PrintResult("System.SByte.MinValue = System.SByte.MinValue", System.SByte.MinValue = System.SByte.MinValue) PrintResult("System.SByte.MinValue = System.Byte.MaxValue", System.SByte.MinValue = System.Byte.MaxValue) PrintResult("System.SByte.MinValue = -3S", System.SByte.MinValue = -3S) PrintResult("System.SByte.MinValue = 24US", System.SByte.MinValue = 24US) PrintResult("System.SByte.MinValue = -5I", System.SByte.MinValue = -5I) PrintResult("System.SByte.MinValue = 26UI", System.SByte.MinValue = 26UI) PrintResult("System.SByte.MinValue = -7L", System.SByte.MinValue = -7L) PrintResult("System.SByte.MinValue = 28UL", System.SByte.MinValue = 28UL) PrintResult("System.SByte.MinValue = -9D", System.SByte.MinValue = -9D) PrintResult("System.SByte.MinValue = 10.0F", System.SByte.MinValue = 10.0F) PrintResult("System.SByte.MinValue = -11.0R", System.SByte.MinValue = -11.0R) PrintResult("System.SByte.MinValue = ""12""", System.SByte.MinValue = "12") PrintResult("System.SByte.MinValue = TypeCode.Double", System.SByte.MinValue = TypeCode.Double) PrintResult("System.Byte.MaxValue = False", System.Byte.MaxValue = False) PrintResult("System.Byte.MaxValue = True", System.Byte.MaxValue = True) PrintResult("System.Byte.MaxValue = System.SByte.MinValue", System.Byte.MaxValue = System.SByte.MinValue) PrintResult("System.Byte.MaxValue = System.Byte.MaxValue", System.Byte.MaxValue = System.Byte.MaxValue) PrintResult("System.Byte.MaxValue = -3S", System.Byte.MaxValue = -3S) PrintResult("System.Byte.MaxValue = 24US", System.Byte.MaxValue = 24US) PrintResult("System.Byte.MaxValue = -5I", System.Byte.MaxValue = -5I) PrintResult("System.Byte.MaxValue = 26UI", System.Byte.MaxValue = 26UI) PrintResult("System.Byte.MaxValue = -7L", System.Byte.MaxValue = -7L) PrintResult("System.Byte.MaxValue = 28UL", System.Byte.MaxValue = 28UL) PrintResult("System.Byte.MaxValue = -9D", System.Byte.MaxValue = -9D) PrintResult("System.Byte.MaxValue = 10.0F", System.Byte.MaxValue = 10.0F) PrintResult("System.Byte.MaxValue = -11.0R", System.Byte.MaxValue = -11.0R) PrintResult("System.Byte.MaxValue = ""12""", System.Byte.MaxValue = "12") PrintResult("System.Byte.MaxValue = TypeCode.Double", System.Byte.MaxValue = TypeCode.Double) PrintResult("-3S = False", -3S = False) PrintResult("-3S = True", -3S = True) PrintResult("-3S = System.SByte.MinValue", -3S = System.SByte.MinValue) PrintResult("-3S = System.Byte.MaxValue", -3S = System.Byte.MaxValue) PrintResult("-3S = -3S", -3S = -3S) PrintResult("-3S = 24US", -3S = 24US) PrintResult("-3S = -5I", -3S = -5I) PrintResult("-3S = 26UI", -3S = 26UI) PrintResult("-3S = -7L", -3S = -7L) PrintResult("-3S = 28UL", -3S = 28UL) PrintResult("-3S = -9D", -3S = -9D) PrintResult("-3S = 10.0F", -3S = 10.0F) PrintResult("-3S = -11.0R", -3S = -11.0R) PrintResult("-3S = ""12""", -3S = "12") PrintResult("-3S = TypeCode.Double", -3S = TypeCode.Double) PrintResult("24US = False", 24US = False) PrintResult("24US = True", 24US = True) PrintResult("24US = System.SByte.MinValue", 24US = System.SByte.MinValue) PrintResult("24US = System.Byte.MaxValue", 24US = System.Byte.MaxValue) PrintResult("24US = -3S", 24US = -3S) PrintResult("24US = 24US", 24US = 24US) PrintResult("24US = -5I", 24US = -5I) PrintResult("24US = 26UI", 24US = 26UI) PrintResult("24US = -7L", 24US = -7L) PrintResult("24US = 28UL", 24US = 28UL) PrintResult("24US = -9D", 24US = -9D) PrintResult("24US = 10.0F", 24US = 10.0F) PrintResult("24US = -11.0R", 24US = -11.0R) PrintResult("24US = ""12""", 24US = "12") PrintResult("24US = TypeCode.Double", 24US = TypeCode.Double) PrintResult("-5I = False", -5I = False) PrintResult("-5I = True", -5I = True) PrintResult("-5I = System.SByte.MinValue", -5I = System.SByte.MinValue) PrintResult("-5I = System.Byte.MaxValue", -5I = System.Byte.MaxValue) PrintResult("-5I = -3S", -5I = -3S) PrintResult("-5I = 24US", -5I = 24US) PrintResult("-5I = -5I", -5I = -5I) PrintResult("-5I = 26UI", -5I = 26UI) PrintResult("-5I = -7L", -5I = -7L) PrintResult("-5I = 28UL", -5I = 28UL) PrintResult("-5I = -9D", -5I = -9D) PrintResult("-5I = 10.0F", -5I = 10.0F) PrintResult("-5I = -11.0R", -5I = -11.0R) PrintResult("-5I = ""12""", -5I = "12") PrintResult("-5I = TypeCode.Double", -5I = TypeCode.Double) PrintResult("26UI = False", 26UI = False) PrintResult("26UI = True", 26UI = True) PrintResult("26UI = System.SByte.MinValue", 26UI = System.SByte.MinValue) PrintResult("26UI = System.Byte.MaxValue", 26UI = System.Byte.MaxValue) PrintResult("26UI = -3S", 26UI = -3S) PrintResult("26UI = 24US", 26UI = 24US) PrintResult("26UI = -5I", 26UI = -5I) PrintResult("26UI = 26UI", 26UI = 26UI) PrintResult("26UI = -7L", 26UI = -7L) PrintResult("26UI = 28UL", 26UI = 28UL) PrintResult("26UI = -9D", 26UI = -9D) PrintResult("26UI = 10.0F", 26UI = 10.0F) PrintResult("26UI = -11.0R", 26UI = -11.0R) PrintResult("26UI = ""12""", 26UI = "12") PrintResult("26UI = TypeCode.Double", 26UI = TypeCode.Double) PrintResult("-7L = False", -7L = False) PrintResult("-7L = True", -7L = True) PrintResult("-7L = System.SByte.MinValue", -7L = System.SByte.MinValue) PrintResult("-7L = System.Byte.MaxValue", -7L = System.Byte.MaxValue) PrintResult("-7L = -3S", -7L = -3S) PrintResult("-7L = 24US", -7L = 24US) PrintResult("-7L = -5I", -7L = -5I) PrintResult("-7L = 26UI", -7L = 26UI) PrintResult("-7L = -7L", -7L = -7L) PrintResult("-7L = 28UL", -7L = 28UL) PrintResult("-7L = -9D", -7L = -9D) PrintResult("-7L = 10.0F", -7L = 10.0F) PrintResult("-7L = -11.0R", -7L = -11.0R) PrintResult("-7L = ""12""", -7L = "12") PrintResult("-7L = TypeCode.Double", -7L = TypeCode.Double) PrintResult("28UL = False", 28UL = False) PrintResult("28UL = True", 28UL = True) PrintResult("28UL = System.SByte.MinValue", 28UL = System.SByte.MinValue) PrintResult("28UL = System.Byte.MaxValue", 28UL = System.Byte.MaxValue) PrintResult("28UL = -3S", 28UL = -3S) PrintResult("28UL = 24US", 28UL = 24US) PrintResult("28UL = -5I", 28UL = -5I) PrintResult("28UL = 26UI", 28UL = 26UI) PrintResult("28UL = -7L", 28UL = -7L) PrintResult("28UL = 28UL", 28UL = 28UL) PrintResult("28UL = -9D", 28UL = -9D) PrintResult("28UL = 10.0F", 28UL = 10.0F) PrintResult("28UL = -11.0R", 28UL = -11.0R) PrintResult("28UL = ""12""", 28UL = "12") PrintResult("28UL = TypeCode.Double", 28UL = TypeCode.Double) PrintResult("-9D = False", -9D = False) PrintResult("-9D = True", -9D = True) PrintResult("-9D = System.SByte.MinValue", -9D = System.SByte.MinValue) PrintResult("-9D = System.Byte.MaxValue", -9D = System.Byte.MaxValue) PrintResult("-9D = -3S", -9D = -3S) PrintResult("-9D = 24US", -9D = 24US) PrintResult("-9D = -5I", -9D = -5I) PrintResult("-9D = 26UI", -9D = 26UI) PrintResult("-9D = -7L", -9D = -7L) PrintResult("-9D = 28UL", -9D = 28UL) PrintResult("-9D = -9D", -9D = -9D) PrintResult("-9D = 10.0F", -9D = 10.0F) PrintResult("-9D = -11.0R", -9D = -11.0R) PrintResult("-9D = ""12""", -9D = "12") PrintResult("-9D = TypeCode.Double", -9D = TypeCode.Double) PrintResult("10.0F = False", 10.0F = False) PrintResult("10.0F = True", 10.0F = True) PrintResult("10.0F = System.SByte.MinValue", 10.0F = System.SByte.MinValue) PrintResult("10.0F = System.Byte.MaxValue", 10.0F = System.Byte.MaxValue) PrintResult("10.0F = -3S", 10.0F = -3S) PrintResult("10.0F = 24US", 10.0F = 24US) PrintResult("10.0F = -5I", 10.0F = -5I) PrintResult("10.0F = 26UI", 10.0F = 26UI) PrintResult("10.0F = -7L", 10.0F = -7L) PrintResult("10.0F = 28UL", 10.0F = 28UL) PrintResult("10.0F = -9D", 10.0F = -9D) PrintResult("10.0F = 10.0F", 10.0F = 10.0F) PrintResult("10.0F = -11.0R", 10.0F = -11.0R) PrintResult("10.0F = ""12""", 10.0F = "12") PrintResult("10.0F = TypeCode.Double", 10.0F = TypeCode.Double) PrintResult("-11.0R = False", -11.0R = False) PrintResult("-11.0R = True", -11.0R = True) PrintResult("-11.0R = System.SByte.MinValue", -11.0R = System.SByte.MinValue) PrintResult("-11.0R = System.Byte.MaxValue", -11.0R = System.Byte.MaxValue) PrintResult("-11.0R = -3S", -11.0R = -3S) PrintResult("-11.0R = 24US", -11.0R = 24US) PrintResult("-11.0R = -5I", -11.0R = -5I) PrintResult("-11.0R = 26UI", -11.0R = 26UI) PrintResult("-11.0R = -7L", -11.0R = -7L) PrintResult("-11.0R = 28UL", -11.0R = 28UL) PrintResult("-11.0R = -9D", -11.0R = -9D) PrintResult("-11.0R = 10.0F", -11.0R = 10.0F) PrintResult("-11.0R = -11.0R", -11.0R = -11.0R) PrintResult("-11.0R = ""12""", -11.0R = "12") PrintResult("-11.0R = TypeCode.Double", -11.0R = TypeCode.Double) PrintResult("""12"" = False", "12" = False) PrintResult("""12"" = True", "12" = True) PrintResult("""12"" = System.SByte.MinValue", "12" = System.SByte.MinValue) PrintResult("""12"" = System.Byte.MaxValue", "12" = System.Byte.MaxValue) PrintResult("""12"" = -3S", "12" = -3S) PrintResult("""12"" = 24US", "12" = 24US) PrintResult("""12"" = -5I", "12" = -5I) PrintResult("""12"" = 26UI", "12" = 26UI) PrintResult("""12"" = -7L", "12" = -7L) PrintResult("""12"" = 28UL", "12" = 28UL) PrintResult("""12"" = -9D", "12" = -9D) PrintResult("""12"" = 10.0F", "12" = 10.0F) PrintResult("""12"" = -11.0R", "12" = -11.0R) PrintResult("""12"" = ""12""", "12" = "12") PrintResult("""12"" = TypeCode.Double", "12" = TypeCode.Double) PrintResult("TypeCode.Double = False", TypeCode.Double = False) PrintResult("TypeCode.Double = True", TypeCode.Double = True) PrintResult("TypeCode.Double = System.SByte.MinValue", TypeCode.Double = System.SByte.MinValue) PrintResult("TypeCode.Double = System.Byte.MaxValue", TypeCode.Double = System.Byte.MaxValue) PrintResult("TypeCode.Double = -3S", TypeCode.Double = -3S) PrintResult("TypeCode.Double = 24US", TypeCode.Double = 24US) PrintResult("TypeCode.Double = -5I", TypeCode.Double = -5I) PrintResult("TypeCode.Double = 26UI", TypeCode.Double = 26UI) PrintResult("TypeCode.Double = -7L", TypeCode.Double = -7L) PrintResult("TypeCode.Double = 28UL", TypeCode.Double = 28UL) PrintResult("TypeCode.Double = -9D", TypeCode.Double = -9D) PrintResult("TypeCode.Double = 10.0F", TypeCode.Double = 10.0F) PrintResult("TypeCode.Double = -11.0R", TypeCode.Double = -11.0R) PrintResult("TypeCode.Double = ""12""", TypeCode.Double = "12") PrintResult("TypeCode.Double = TypeCode.Double", TypeCode.Double = TypeCode.Double) PrintResult("False <> False", False <> False) PrintResult("False <> True", False <> True) PrintResult("False <> System.SByte.MinValue", False <> System.SByte.MinValue) PrintResult("False <> System.Byte.MaxValue", False <> System.Byte.MaxValue) PrintResult("False <> -3S", False <> -3S) PrintResult("False <> 24US", False <> 24US) PrintResult("False <> -5I", False <> -5I) PrintResult("False <> 26UI", False <> 26UI) PrintResult("False <> -7L", False <> -7L) PrintResult("False <> 28UL", False <> 28UL) PrintResult("False <> -9D", False <> -9D) PrintResult("False <> 10.0F", False <> 10.0F) PrintResult("False <> -11.0R", False <> -11.0R) PrintResult("False <> ""12""", False <> "12") PrintResult("False <> TypeCode.Double", False <> TypeCode.Double) PrintResult("True <> False", True <> False) PrintResult("True <> True", True <> True) PrintResult("True <> System.SByte.MinValue", True <> System.SByte.MinValue) PrintResult("True <> System.Byte.MaxValue", True <> System.Byte.MaxValue) PrintResult("True <> -3S", True <> -3S) PrintResult("True <> 24US", True <> 24US) PrintResult("True <> -5I", True <> -5I) PrintResult("True <> 26UI", True <> 26UI) PrintResult("True <> -7L", True <> -7L) PrintResult("True <> 28UL", True <> 28UL) PrintResult("True <> -9D", True <> -9D) PrintResult("True <> 10.0F", True <> 10.0F) PrintResult("True <> -11.0R", True <> -11.0R) PrintResult("True <> ""12""", True <> "12") PrintResult("True <> TypeCode.Double", True <> TypeCode.Double) PrintResult("System.SByte.MinValue <> False", System.SByte.MinValue <> False) PrintResult("System.SByte.MinValue <> True", System.SByte.MinValue <> True) PrintResult("System.SByte.MinValue <> System.SByte.MinValue", System.SByte.MinValue <> System.SByte.MinValue) PrintResult("System.SByte.MinValue <> System.Byte.MaxValue", System.SByte.MinValue <> System.Byte.MaxValue) PrintResult("System.SByte.MinValue <> -3S", System.SByte.MinValue <> -3S) PrintResult("System.SByte.MinValue <> 24US", System.SByte.MinValue <> 24US) PrintResult("System.SByte.MinValue <> -5I", System.SByte.MinValue <> -5I) PrintResult("System.SByte.MinValue <> 26UI", System.SByte.MinValue <> 26UI) PrintResult("System.SByte.MinValue <> -7L", System.SByte.MinValue <> -7L) PrintResult("System.SByte.MinValue <> 28UL", System.SByte.MinValue <> 28UL) PrintResult("System.SByte.MinValue <> -9D", System.SByte.MinValue <> -9D) PrintResult("System.SByte.MinValue <> 10.0F", System.SByte.MinValue <> 10.0F) PrintResult("System.SByte.MinValue <> -11.0R", System.SByte.MinValue <> -11.0R) PrintResult("System.SByte.MinValue <> ""12""", System.SByte.MinValue <> "12") PrintResult("System.SByte.MinValue <> TypeCode.Double", System.SByte.MinValue <> TypeCode.Double) PrintResult("System.Byte.MaxValue <> False", System.Byte.MaxValue <> False) PrintResult("System.Byte.MaxValue <> True", System.Byte.MaxValue <> True) PrintResult("System.Byte.MaxValue <> System.SByte.MinValue", System.Byte.MaxValue <> System.SByte.MinValue) PrintResult("System.Byte.MaxValue <> System.Byte.MaxValue", System.Byte.MaxValue <> System.Byte.MaxValue) PrintResult("System.Byte.MaxValue <> -3S", System.Byte.MaxValue <> -3S) PrintResult("System.Byte.MaxValue <> 24US", System.Byte.MaxValue <> 24US) PrintResult("System.Byte.MaxValue <> -5I", System.Byte.MaxValue <> -5I) PrintResult("System.Byte.MaxValue <> 26UI", System.Byte.MaxValue <> 26UI) PrintResult("System.Byte.MaxValue <> -7L", System.Byte.MaxValue <> -7L) PrintResult("System.Byte.MaxValue <> 28UL", System.Byte.MaxValue <> 28UL) PrintResult("System.Byte.MaxValue <> -9D", System.Byte.MaxValue <> -9D) PrintResult("System.Byte.MaxValue <> 10.0F", System.Byte.MaxValue <> 10.0F) PrintResult("System.Byte.MaxValue <> -11.0R", System.Byte.MaxValue <> -11.0R) PrintResult("System.Byte.MaxValue <> ""12""", System.Byte.MaxValue <> "12") PrintResult("System.Byte.MaxValue <> TypeCode.Double", System.Byte.MaxValue <> TypeCode.Double) PrintResult("-3S <> False", -3S <> False) PrintResult("-3S <> True", -3S <> True) PrintResult("-3S <> System.SByte.MinValue", -3S <> System.SByte.MinValue) PrintResult("-3S <> System.Byte.MaxValue", -3S <> System.Byte.MaxValue) PrintResult("-3S <> -3S", -3S <> -3S) PrintResult("-3S <> 24US", -3S <> 24US) PrintResult("-3S <> -5I", -3S <> -5I) PrintResult("-3S <> 26UI", -3S <> 26UI) PrintResult("-3S <> -7L", -3S <> -7L) PrintResult("-3S <> 28UL", -3S <> 28UL) PrintResult("-3S <> -9D", -3S <> -9D) PrintResult("-3S <> 10.0F", -3S <> 10.0F) PrintResult("-3S <> -11.0R", -3S <> -11.0R) PrintResult("-3S <> ""12""", -3S <> "12") PrintResult("-3S <> TypeCode.Double", -3S <> TypeCode.Double) PrintResult("24US <> False", 24US <> False) PrintResult("24US <> True", 24US <> True) PrintResult("24US <> System.SByte.MinValue", 24US <> System.SByte.MinValue) PrintResult("24US <> System.Byte.MaxValue", 24US <> System.Byte.MaxValue) PrintResult("24US <> -3S", 24US <> -3S) PrintResult("24US <> 24US", 24US <> 24US) PrintResult("24US <> -5I", 24US <> -5I) PrintResult("24US <> 26UI", 24US <> 26UI) PrintResult("24US <> -7L", 24US <> -7L) PrintResult("24US <> 28UL", 24US <> 28UL) PrintResult("24US <> -9D", 24US <> -9D) PrintResult("24US <> 10.0F", 24US <> 10.0F) PrintResult("24US <> -11.0R", 24US <> -11.0R) PrintResult("24US <> ""12""", 24US <> "12") PrintResult("24US <> TypeCode.Double", 24US <> TypeCode.Double) PrintResult("-5I <> False", -5I <> False) PrintResult("-5I <> True", -5I <> True) PrintResult("-5I <> System.SByte.MinValue", -5I <> System.SByte.MinValue) PrintResult("-5I <> System.Byte.MaxValue", -5I <> System.Byte.MaxValue) PrintResult("-5I <> -3S", -5I <> -3S) PrintResult("-5I <> 24US", -5I <> 24US) PrintResult("-5I <> -5I", -5I <> -5I) PrintResult("-5I <> 26UI", -5I <> 26UI) PrintResult("-5I <> -7L", -5I <> -7L) PrintResult("-5I <> 28UL", -5I <> 28UL) PrintResult("-5I <> -9D", -5I <> -9D) PrintResult("-5I <> 10.0F", -5I <> 10.0F) PrintResult("-5I <> -11.0R", -5I <> -11.0R) PrintResult("-5I <> ""12""", -5I <> "12") PrintResult("-5I <> TypeCode.Double", -5I <> TypeCode.Double) PrintResult("26UI <> False", 26UI <> False) PrintResult("26UI <> True", 26UI <> True) PrintResult("26UI <> System.SByte.MinValue", 26UI <> System.SByte.MinValue) PrintResult("26UI <> System.Byte.MaxValue", 26UI <> System.Byte.MaxValue) PrintResult("26UI <> -3S", 26UI <> -3S) PrintResult("26UI <> 24US", 26UI <> 24US) PrintResult("26UI <> -5I", 26UI <> -5I) PrintResult("26UI <> 26UI", 26UI <> 26UI) PrintResult("26UI <> -7L", 26UI <> -7L) PrintResult("26UI <> 28UL", 26UI <> 28UL) PrintResult("26UI <> -9D", 26UI <> -9D) PrintResult("26UI <> 10.0F", 26UI <> 10.0F) PrintResult("26UI <> -11.0R", 26UI <> -11.0R) PrintResult("26UI <> ""12""", 26UI <> "12") PrintResult("26UI <> TypeCode.Double", 26UI <> TypeCode.Double) PrintResult("-7L <> False", -7L <> False) PrintResult("-7L <> True", -7L <> True) PrintResult("-7L <> System.SByte.MinValue", -7L <> System.SByte.MinValue) PrintResult("-7L <> System.Byte.MaxValue", -7L <> System.Byte.MaxValue) PrintResult("-7L <> -3S", -7L <> -3S) PrintResult("-7L <> 24US", -7L <> 24US) PrintResult("-7L <> -5I", -7L <> -5I) PrintResult("-7L <> 26UI", -7L <> 26UI) PrintResult("-7L <> -7L", -7L <> -7L) PrintResult("-7L <> 28UL", -7L <> 28UL) PrintResult("-7L <> -9D", -7L <> -9D) PrintResult("-7L <> 10.0F", -7L <> 10.0F) PrintResult("-7L <> -11.0R", -7L <> -11.0R) PrintResult("-7L <> ""12""", -7L <> "12") PrintResult("-7L <> TypeCode.Double", -7L <> TypeCode.Double) PrintResult("28UL <> False", 28UL <> False) PrintResult("28UL <> True", 28UL <> True) PrintResult("28UL <> System.SByte.MinValue", 28UL <> System.SByte.MinValue) PrintResult("28UL <> System.Byte.MaxValue", 28UL <> System.Byte.MaxValue) PrintResult("28UL <> -3S", 28UL <> -3S) PrintResult("28UL <> 24US", 28UL <> 24US) PrintResult("28UL <> -5I", 28UL <> -5I) PrintResult("28UL <> 26UI", 28UL <> 26UI) PrintResult("28UL <> -7L", 28UL <> -7L) PrintResult("28UL <> 28UL", 28UL <> 28UL) PrintResult("28UL <> -9D", 28UL <> -9D) PrintResult("28UL <> 10.0F", 28UL <> 10.0F) PrintResult("28UL <> -11.0R", 28UL <> -11.0R) PrintResult("28UL <> ""12""", 28UL <> "12") PrintResult("28UL <> TypeCode.Double", 28UL <> TypeCode.Double) PrintResult("-9D <> False", -9D <> False) PrintResult("-9D <> True", -9D <> True) PrintResult("-9D <> System.SByte.MinValue", -9D <> System.SByte.MinValue) PrintResult("-9D <> System.Byte.MaxValue", -9D <> System.Byte.MaxValue) PrintResult("-9D <> -3S", -9D <> -3S) PrintResult("-9D <> 24US", -9D <> 24US) PrintResult("-9D <> -5I", -9D <> -5I) PrintResult("-9D <> 26UI", -9D <> 26UI) PrintResult("-9D <> -7L", -9D <> -7L) PrintResult("-9D <> 28UL", -9D <> 28UL) PrintResult("-9D <> -9D", -9D <> -9D) PrintResult("-9D <> 10.0F", -9D <> 10.0F) PrintResult("-9D <> -11.0R", -9D <> -11.0R) PrintResult("-9D <> ""12""", -9D <> "12") PrintResult("-9D <> TypeCode.Double", -9D <> TypeCode.Double) PrintResult("10.0F <> False", 10.0F <> False) PrintResult("10.0F <> True", 10.0F <> True) PrintResult("10.0F <> System.SByte.MinValue", 10.0F <> System.SByte.MinValue) PrintResult("10.0F <> System.Byte.MaxValue", 10.0F <> System.Byte.MaxValue) PrintResult("10.0F <> -3S", 10.0F <> -3S) PrintResult("10.0F <> 24US", 10.0F <> 24US) PrintResult("10.0F <> -5I", 10.0F <> -5I) PrintResult("10.0F <> 26UI", 10.0F <> 26UI) PrintResult("10.0F <> -7L", 10.0F <> -7L) PrintResult("10.0F <> 28UL", 10.0F <> 28UL) PrintResult("10.0F <> -9D", 10.0F <> -9D) PrintResult("10.0F <> 10.0F", 10.0F <> 10.0F) PrintResult("10.0F <> -11.0R", 10.0F <> -11.0R) PrintResult("10.0F <> ""12""", 10.0F <> "12") PrintResult("10.0F <> TypeCode.Double", 10.0F <> TypeCode.Double) PrintResult("-11.0R <> False", -11.0R <> False) PrintResult("-11.0R <> True", -11.0R <> True) PrintResult("-11.0R <> System.SByte.MinValue", -11.0R <> System.SByte.MinValue) PrintResult("-11.0R <> System.Byte.MaxValue", -11.0R <> System.Byte.MaxValue) PrintResult("-11.0R <> -3S", -11.0R <> -3S) PrintResult("-11.0R <> 24US", -11.0R <> 24US) PrintResult("-11.0R <> -5I", -11.0R <> -5I) PrintResult("-11.0R <> 26UI", -11.0R <> 26UI) PrintResult("-11.0R <> -7L", -11.0R <> -7L) PrintResult("-11.0R <> 28UL", -11.0R <> 28UL) PrintResult("-11.0R <> -9D", -11.0R <> -9D) PrintResult("-11.0R <> 10.0F", -11.0R <> 10.0F) PrintResult("-11.0R <> -11.0R", -11.0R <> -11.0R) PrintResult("-11.0R <> ""12""", -11.0R <> "12") PrintResult("-11.0R <> TypeCode.Double", -11.0R <> TypeCode.Double) PrintResult("""12"" <> False", "12" <> False) PrintResult("""12"" <> True", "12" <> True) PrintResult("""12"" <> System.SByte.MinValue", "12" <> System.SByte.MinValue) PrintResult("""12"" <> System.Byte.MaxValue", "12" <> System.Byte.MaxValue) PrintResult("""12"" <> -3S", "12" <> -3S) PrintResult("""12"" <> 24US", "12" <> 24US) PrintResult("""12"" <> -5I", "12" <> -5I) PrintResult("""12"" <> 26UI", "12" <> 26UI) PrintResult("""12"" <> -7L", "12" <> -7L) PrintResult("""12"" <> 28UL", "12" <> 28UL) PrintResult("""12"" <> -9D", "12" <> -9D) PrintResult("""12"" <> 10.0F", "12" <> 10.0F) PrintResult("""12"" <> -11.0R", "12" <> -11.0R) PrintResult("""12"" <> ""12""", "12" <> "12") PrintResult("""12"" <> TypeCode.Double", "12" <> TypeCode.Double) PrintResult("TypeCode.Double <> False", TypeCode.Double <> False) PrintResult("TypeCode.Double <> True", TypeCode.Double <> True) PrintResult("TypeCode.Double <> System.SByte.MinValue", TypeCode.Double <> System.SByte.MinValue) PrintResult("TypeCode.Double <> System.Byte.MaxValue", TypeCode.Double <> System.Byte.MaxValue) PrintResult("TypeCode.Double <> -3S", TypeCode.Double <> -3S) PrintResult("TypeCode.Double <> 24US", TypeCode.Double <> 24US) PrintResult("TypeCode.Double <> -5I", TypeCode.Double <> -5I) PrintResult("TypeCode.Double <> 26UI", TypeCode.Double <> 26UI) PrintResult("TypeCode.Double <> -7L", TypeCode.Double <> -7L) PrintResult("TypeCode.Double <> 28UL", TypeCode.Double <> 28UL) PrintResult("TypeCode.Double <> -9D", TypeCode.Double <> -9D) PrintResult("TypeCode.Double <> 10.0F", TypeCode.Double <> 10.0F) PrintResult("TypeCode.Double <> -11.0R", TypeCode.Double <> -11.0R) PrintResult("TypeCode.Double <> ""12""", TypeCode.Double <> "12") PrintResult("TypeCode.Double <> TypeCode.Double", TypeCode.Double <> TypeCode.Double) PrintResult("False <= False", False <= False) PrintResult("False <= True", False <= True) PrintResult("False <= System.SByte.MinValue", False <= System.SByte.MinValue) PrintResult("False <= System.Byte.MaxValue", False <= System.Byte.MaxValue) PrintResult("False <= -3S", False <= -3S) PrintResult("False <= 24US", False <= 24US) PrintResult("False <= -5I", False <= -5I) PrintResult("False <= 26UI", False <= 26UI) PrintResult("False <= -7L", False <= -7L) PrintResult("False <= 28UL", False <= 28UL) PrintResult("False <= -9D", False <= -9D) PrintResult("False <= 10.0F", False <= 10.0F) PrintResult("False <= -11.0R", False <= -11.0R) PrintResult("False <= ""12""", False <= "12") PrintResult("False <= TypeCode.Double", False <= TypeCode.Double) PrintResult("True <= False", True <= False) PrintResult("True <= True", True <= True) PrintResult("True <= System.SByte.MinValue", True <= System.SByte.MinValue) PrintResult("True <= System.Byte.MaxValue", True <= System.Byte.MaxValue) PrintResult("True <= -3S", True <= -3S) PrintResult("True <= 24US", True <= 24US) PrintResult("True <= -5I", True <= -5I) PrintResult("True <= 26UI", True <= 26UI) PrintResult("True <= -7L", True <= -7L) PrintResult("True <= 28UL", True <= 28UL) PrintResult("True <= -9D", True <= -9D) PrintResult("True <= 10.0F", True <= 10.0F) PrintResult("True <= -11.0R", True <= -11.0R) PrintResult("True <= ""12""", True <= "12") PrintResult("True <= TypeCode.Double", True <= TypeCode.Double) PrintResult("System.SByte.MinValue <= False", System.SByte.MinValue <= False) PrintResult("System.SByte.MinValue <= True", System.SByte.MinValue <= True) PrintResult("System.SByte.MinValue <= System.SByte.MinValue", System.SByte.MinValue <= System.SByte.MinValue) PrintResult("System.SByte.MinValue <= System.Byte.MaxValue", System.SByte.MinValue <= System.Byte.MaxValue) PrintResult("System.SByte.MinValue <= -3S", System.SByte.MinValue <= -3S) PrintResult("System.SByte.MinValue <= 24US", System.SByte.MinValue <= 24US) PrintResult("System.SByte.MinValue <= -5I", System.SByte.MinValue <= -5I) PrintResult("System.SByte.MinValue <= 26UI", System.SByte.MinValue <= 26UI) PrintResult("System.SByte.MinValue <= -7L", System.SByte.MinValue <= -7L) PrintResult("System.SByte.MinValue <= 28UL", System.SByte.MinValue <= 28UL) PrintResult("System.SByte.MinValue <= -9D", System.SByte.MinValue <= -9D) PrintResult("System.SByte.MinValue <= 10.0F", System.SByte.MinValue <= 10.0F) PrintResult("System.SByte.MinValue <= -11.0R", System.SByte.MinValue <= -11.0R) PrintResult("System.SByte.MinValue <= ""12""", System.SByte.MinValue <= "12") PrintResult("System.SByte.MinValue <= TypeCode.Double", System.SByte.MinValue <= TypeCode.Double) PrintResult("System.Byte.MaxValue <= False", System.Byte.MaxValue <= False) PrintResult("System.Byte.MaxValue <= True", System.Byte.MaxValue <= True) PrintResult("System.Byte.MaxValue <= System.SByte.MinValue", System.Byte.MaxValue <= System.SByte.MinValue) PrintResult("System.Byte.MaxValue <= System.Byte.MaxValue", System.Byte.MaxValue <= System.Byte.MaxValue) PrintResult("System.Byte.MaxValue <= -3S", System.Byte.MaxValue <= -3S) PrintResult("System.Byte.MaxValue <= 24US", System.Byte.MaxValue <= 24US) PrintResult("System.Byte.MaxValue <= -5I", System.Byte.MaxValue <= -5I) PrintResult("System.Byte.MaxValue <= 26UI", System.Byte.MaxValue <= 26UI) PrintResult("System.Byte.MaxValue <= -7L", System.Byte.MaxValue <= -7L) PrintResult("System.Byte.MaxValue <= 28UL", System.Byte.MaxValue <= 28UL) PrintResult("System.Byte.MaxValue <= -9D", System.Byte.MaxValue <= -9D) PrintResult("System.Byte.MaxValue <= 10.0F", System.Byte.MaxValue <= 10.0F) PrintResult("System.Byte.MaxValue <= -11.0R", System.Byte.MaxValue <= -11.0R) PrintResult("System.Byte.MaxValue <= ""12""", System.Byte.MaxValue <= "12") PrintResult("System.Byte.MaxValue <= TypeCode.Double", System.Byte.MaxValue <= TypeCode.Double) PrintResult("-3S <= False", -3S <= False) PrintResult("-3S <= True", -3S <= True) PrintResult("-3S <= System.SByte.MinValue", -3S <= System.SByte.MinValue) PrintResult("-3S <= System.Byte.MaxValue", -3S <= System.Byte.MaxValue) PrintResult("-3S <= -3S", -3S <= -3S) PrintResult("-3S <= 24US", -3S <= 24US) PrintResult("-3S <= -5I", -3S <= -5I) PrintResult("-3S <= 26UI", -3S <= 26UI) PrintResult("-3S <= -7L", -3S <= -7L) PrintResult("-3S <= 28UL", -3S <= 28UL) PrintResult("-3S <= -9D", -3S <= -9D) PrintResult("-3S <= 10.0F", -3S <= 10.0F) PrintResult("-3S <= -11.0R", -3S <= -11.0R) PrintResult("-3S <= ""12""", -3S <= "12") PrintResult("-3S <= TypeCode.Double", -3S <= TypeCode.Double) PrintResult("24US <= False", 24US <= False) PrintResult("24US <= True", 24US <= True) PrintResult("24US <= System.SByte.MinValue", 24US <= System.SByte.MinValue) PrintResult("24US <= System.Byte.MaxValue", 24US <= System.Byte.MaxValue) PrintResult("24US <= -3S", 24US <= -3S) PrintResult("24US <= 24US", 24US <= 24US) PrintResult("24US <= -5I", 24US <= -5I) PrintResult("24US <= 26UI", 24US <= 26UI) PrintResult("24US <= -7L", 24US <= -7L) PrintResult("24US <= 28UL", 24US <= 28UL) PrintResult("24US <= -9D", 24US <= -9D) PrintResult("24US <= 10.0F", 24US <= 10.0F) PrintResult("24US <= -11.0R", 24US <= -11.0R) PrintResult("24US <= ""12""", 24US <= "12") PrintResult("24US <= TypeCode.Double", 24US <= TypeCode.Double) PrintResult("-5I <= False", -5I <= False) PrintResult("-5I <= True", -5I <= True) PrintResult("-5I <= System.SByte.MinValue", -5I <= System.SByte.MinValue) PrintResult("-5I <= System.Byte.MaxValue", -5I <= System.Byte.MaxValue) PrintResult("-5I <= -3S", -5I <= -3S) PrintResult("-5I <= 24US", -5I <= 24US) PrintResult("-5I <= -5I", -5I <= -5I) PrintResult("-5I <= 26UI", -5I <= 26UI) PrintResult("-5I <= -7L", -5I <= -7L) PrintResult("-5I <= 28UL", -5I <= 28UL) PrintResult("-5I <= -9D", -5I <= -9D) PrintResult("-5I <= 10.0F", -5I <= 10.0F) PrintResult("-5I <= -11.0R", -5I <= -11.0R) PrintResult("-5I <= ""12""", -5I <= "12") PrintResult("-5I <= TypeCode.Double", -5I <= TypeCode.Double) PrintResult("26UI <= False", 26UI <= False) PrintResult("26UI <= True", 26UI <= True) PrintResult("26UI <= System.SByte.MinValue", 26UI <= System.SByte.MinValue) PrintResult("26UI <= System.Byte.MaxValue", 26UI <= System.Byte.MaxValue) PrintResult("26UI <= -3S", 26UI <= -3S) PrintResult("26UI <= 24US", 26UI <= 24US) PrintResult("26UI <= -5I", 26UI <= -5I) PrintResult("26UI <= 26UI", 26UI <= 26UI) PrintResult("26UI <= -7L", 26UI <= -7L) PrintResult("26UI <= 28UL", 26UI <= 28UL) PrintResult("26UI <= -9D", 26UI <= -9D) PrintResult("26UI <= 10.0F", 26UI <= 10.0F) PrintResult("26UI <= -11.0R", 26UI <= -11.0R) PrintResult("26UI <= ""12""", 26UI <= "12") PrintResult("26UI <= TypeCode.Double", 26UI <= TypeCode.Double) PrintResult("-7L <= False", -7L <= False) PrintResult("-7L <= True", -7L <= True) PrintResult("-7L <= System.SByte.MinValue", -7L <= System.SByte.MinValue) PrintResult("-7L <= System.Byte.MaxValue", -7L <= System.Byte.MaxValue) PrintResult("-7L <= -3S", -7L <= -3S) PrintResult("-7L <= 24US", -7L <= 24US) PrintResult("-7L <= -5I", -7L <= -5I) PrintResult("-7L <= 26UI", -7L <= 26UI) PrintResult("-7L <= -7L", -7L <= -7L) PrintResult("-7L <= 28UL", -7L <= 28UL) PrintResult("-7L <= -9D", -7L <= -9D) PrintResult("-7L <= 10.0F", -7L <= 10.0F) PrintResult("-7L <= -11.0R", -7L <= -11.0R) PrintResult("-7L <= ""12""", -7L <= "12") PrintResult("-7L <= TypeCode.Double", -7L <= TypeCode.Double) PrintResult("28UL <= False", 28UL <= False) PrintResult("28UL <= True", 28UL <= True) PrintResult("28UL <= System.SByte.MinValue", 28UL <= System.SByte.MinValue) PrintResult("28UL <= System.Byte.MaxValue", 28UL <= System.Byte.MaxValue) PrintResult("28UL <= -3S", 28UL <= -3S) PrintResult("28UL <= 24US", 28UL <= 24US) PrintResult("28UL <= -5I", 28UL <= -5I) PrintResult("28UL <= 26UI", 28UL <= 26UI) PrintResult("28UL <= -7L", 28UL <= -7L) PrintResult("28UL <= 28UL", 28UL <= 28UL) PrintResult("28UL <= -9D", 28UL <= -9D) PrintResult("28UL <= 10.0F", 28UL <= 10.0F) PrintResult("28UL <= -11.0R", 28UL <= -11.0R) PrintResult("28UL <= ""12""", 28UL <= "12") PrintResult("28UL <= TypeCode.Double", 28UL <= TypeCode.Double) PrintResult("-9D <= False", -9D <= False) PrintResult("-9D <= True", -9D <= True) PrintResult("-9D <= System.SByte.MinValue", -9D <= System.SByte.MinValue) PrintResult("-9D <= System.Byte.MaxValue", -9D <= System.Byte.MaxValue) PrintResult("-9D <= -3S", -9D <= -3S) PrintResult("-9D <= 24US", -9D <= 24US) PrintResult("-9D <= -5I", -9D <= -5I) PrintResult("-9D <= 26UI", -9D <= 26UI) PrintResult("-9D <= -7L", -9D <= -7L) PrintResult("-9D <= 28UL", -9D <= 28UL) PrintResult("-9D <= -9D", -9D <= -9D) PrintResult("-9D <= 10.0F", -9D <= 10.0F) PrintResult("-9D <= -11.0R", -9D <= -11.0R) PrintResult("-9D <= ""12""", -9D <= "12") PrintResult("-9D <= TypeCode.Double", -9D <= TypeCode.Double) PrintResult("10.0F <= False", 10.0F <= False) PrintResult("10.0F <= True", 10.0F <= True) PrintResult("10.0F <= System.SByte.MinValue", 10.0F <= System.SByte.MinValue) PrintResult("10.0F <= System.Byte.MaxValue", 10.0F <= System.Byte.MaxValue) PrintResult("10.0F <= -3S", 10.0F <= -3S) PrintResult("10.0F <= 24US", 10.0F <= 24US) PrintResult("10.0F <= -5I", 10.0F <= -5I) PrintResult("10.0F <= 26UI", 10.0F <= 26UI) PrintResult("10.0F <= -7L", 10.0F <= -7L) PrintResult("10.0F <= 28UL", 10.0F <= 28UL) PrintResult("10.0F <= -9D", 10.0F <= -9D) PrintResult("10.0F <= 10.0F", 10.0F <= 10.0F) PrintResult("10.0F <= -11.0R", 10.0F <= -11.0R) PrintResult("10.0F <= ""12""", 10.0F <= "12") PrintResult("10.0F <= TypeCode.Double", 10.0F <= TypeCode.Double) PrintResult("-11.0R <= False", -11.0R <= False) PrintResult("-11.0R <= True", -11.0R <= True) PrintResult("-11.0R <= System.SByte.MinValue", -11.0R <= System.SByte.MinValue) PrintResult("-11.0R <= System.Byte.MaxValue", -11.0R <= System.Byte.MaxValue) PrintResult("-11.0R <= -3S", -11.0R <= -3S) PrintResult("-11.0R <= 24US", -11.0R <= 24US) PrintResult("-11.0R <= -5I", -11.0R <= -5I) PrintResult("-11.0R <= 26UI", -11.0R <= 26UI) PrintResult("-11.0R <= -7L", -11.0R <= -7L) PrintResult("-11.0R <= 28UL", -11.0R <= 28UL) PrintResult("-11.0R <= -9D", -11.0R <= -9D) PrintResult("-11.0R <= 10.0F", -11.0R <= 10.0F) PrintResult("-11.0R <= -11.0R", -11.0R <= -11.0R) PrintResult("-11.0R <= ""12""", -11.0R <= "12") PrintResult("-11.0R <= TypeCode.Double", -11.0R <= TypeCode.Double) PrintResult("""12"" <= False", "12" <= False) PrintResult("""12"" <= True", "12" <= True) PrintResult("""12"" <= System.SByte.MinValue", "12" <= System.SByte.MinValue) PrintResult("""12"" <= System.Byte.MaxValue", "12" <= System.Byte.MaxValue) PrintResult("""12"" <= -3S", "12" <= -3S) PrintResult("""12"" <= 24US", "12" <= 24US) PrintResult("""12"" <= -5I", "12" <= -5I) PrintResult("""12"" <= 26UI", "12" <= 26UI) PrintResult("""12"" <= -7L", "12" <= -7L) PrintResult("""12"" <= 28UL", "12" <= 28UL) PrintResult("""12"" <= -9D", "12" <= -9D) PrintResult("""12"" <= 10.0F", "12" <= 10.0F) PrintResult("""12"" <= -11.0R", "12" <= -11.0R) PrintResult("""12"" <= ""12""", "12" <= "12") PrintResult("""12"" <= TypeCode.Double", "12" <= TypeCode.Double) PrintResult("TypeCode.Double <= False", TypeCode.Double <= False) PrintResult("TypeCode.Double <= True", TypeCode.Double <= True) PrintResult("TypeCode.Double <= System.SByte.MinValue", TypeCode.Double <= System.SByte.MinValue) PrintResult("TypeCode.Double <= System.Byte.MaxValue", TypeCode.Double <= System.Byte.MaxValue) PrintResult("TypeCode.Double <= -3S", TypeCode.Double <= -3S) PrintResult("TypeCode.Double <= 24US", TypeCode.Double <= 24US) PrintResult("TypeCode.Double <= -5I", TypeCode.Double <= -5I) PrintResult("TypeCode.Double <= 26UI", TypeCode.Double <= 26UI) PrintResult("TypeCode.Double <= -7L", TypeCode.Double <= -7L) PrintResult("TypeCode.Double <= 28UL", TypeCode.Double <= 28UL) PrintResult("TypeCode.Double <= -9D", TypeCode.Double <= -9D) PrintResult("TypeCode.Double <= 10.0F", TypeCode.Double <= 10.0F) PrintResult("TypeCode.Double <= -11.0R", TypeCode.Double <= -11.0R) PrintResult("TypeCode.Double <= ""12""", TypeCode.Double <= "12") PrintResult("TypeCode.Double <= TypeCode.Double", TypeCode.Double <= TypeCode.Double) PrintResult("False >= False", False >= False) PrintResult("False >= True", False >= True) PrintResult("False >= System.SByte.MinValue", False >= System.SByte.MinValue) PrintResult("False >= System.Byte.MaxValue", False >= System.Byte.MaxValue) PrintResult("False >= -3S", False >= -3S) PrintResult("False >= 24US", False >= 24US) PrintResult("False >= -5I", False >= -5I) PrintResult("False >= 26UI", False >= 26UI) PrintResult("False >= -7L", False >= -7L) PrintResult("False >= 28UL", False >= 28UL) PrintResult("False >= -9D", False >= -9D) PrintResult("False >= 10.0F", False >= 10.0F) PrintResult("False >= -11.0R", False >= -11.0R) PrintResult("False >= ""12""", False >= "12") PrintResult("False >= TypeCode.Double", False >= TypeCode.Double) PrintResult("True >= False", True >= False) PrintResult("True >= True", True >= True) PrintResult("True >= System.SByte.MinValue", True >= System.SByte.MinValue) PrintResult("True >= System.Byte.MaxValue", True >= System.Byte.MaxValue) PrintResult("True >= -3S", True >= -3S) PrintResult("True >= 24US", True >= 24US) PrintResult("True >= -5I", True >= -5I) PrintResult("True >= 26UI", True >= 26UI) PrintResult("True >= -7L", True >= -7L) PrintResult("True >= 28UL", True >= 28UL) PrintResult("True >= -9D", True >= -9D) PrintResult("True >= 10.0F", True >= 10.0F) PrintResult("True >= -11.0R", True >= -11.0R) PrintResult("True >= ""12""", True >= "12") PrintResult("True >= TypeCode.Double", True >= TypeCode.Double) PrintResult("System.SByte.MinValue >= False", System.SByte.MinValue >= False) PrintResult("System.SByte.MinValue >= True", System.SByte.MinValue >= True) PrintResult("System.SByte.MinValue >= System.SByte.MinValue", System.SByte.MinValue >= System.SByte.MinValue) PrintResult("System.SByte.MinValue >= System.Byte.MaxValue", System.SByte.MinValue >= System.Byte.MaxValue) PrintResult("System.SByte.MinValue >= -3S", System.SByte.MinValue >= -3S) PrintResult("System.SByte.MinValue >= 24US", System.SByte.MinValue >= 24US) PrintResult("System.SByte.MinValue >= -5I", System.SByte.MinValue >= -5I) PrintResult("System.SByte.MinValue >= 26UI", System.SByte.MinValue >= 26UI) PrintResult("System.SByte.MinValue >= -7L", System.SByte.MinValue >= -7L) PrintResult("System.SByte.MinValue >= 28UL", System.SByte.MinValue >= 28UL) PrintResult("System.SByte.MinValue >= -9D", System.SByte.MinValue >= -9D) PrintResult("System.SByte.MinValue >= 10.0F", System.SByte.MinValue >= 10.0F) PrintResult("System.SByte.MinValue >= -11.0R", System.SByte.MinValue >= -11.0R) PrintResult("System.SByte.MinValue >= ""12""", System.SByte.MinValue >= "12") PrintResult("System.SByte.MinValue >= TypeCode.Double", System.SByte.MinValue >= TypeCode.Double) PrintResult("System.Byte.MaxValue >= False", System.Byte.MaxValue >= False) PrintResult("System.Byte.MaxValue >= True", System.Byte.MaxValue >= True) PrintResult("System.Byte.MaxValue >= System.SByte.MinValue", System.Byte.MaxValue >= System.SByte.MinValue) PrintResult("System.Byte.MaxValue >= System.Byte.MaxValue", System.Byte.MaxValue >= System.Byte.MaxValue) PrintResult("System.Byte.MaxValue >= -3S", System.Byte.MaxValue >= -3S) PrintResult("System.Byte.MaxValue >= 24US", System.Byte.MaxValue >= 24US) PrintResult("System.Byte.MaxValue >= -5I", System.Byte.MaxValue >= -5I) PrintResult("System.Byte.MaxValue >= 26UI", System.Byte.MaxValue >= 26UI) PrintResult("System.Byte.MaxValue >= -7L", System.Byte.MaxValue >= -7L) PrintResult("System.Byte.MaxValue >= 28UL", System.Byte.MaxValue >= 28UL) PrintResult("System.Byte.MaxValue >= -9D", System.Byte.MaxValue >= -9D) PrintResult("System.Byte.MaxValue >= 10.0F", System.Byte.MaxValue >= 10.0F) PrintResult("System.Byte.MaxValue >= -11.0R", System.Byte.MaxValue >= -11.0R) PrintResult("System.Byte.MaxValue >= ""12""", System.Byte.MaxValue >= "12") PrintResult("System.Byte.MaxValue >= TypeCode.Double", System.Byte.MaxValue >= TypeCode.Double) PrintResult("-3S >= False", -3S >= False) PrintResult("-3S >= True", -3S >= True) PrintResult("-3S >= System.SByte.MinValue", -3S >= System.SByte.MinValue) PrintResult("-3S >= System.Byte.MaxValue", -3S >= System.Byte.MaxValue) PrintResult("-3S >= -3S", -3S >= -3S) PrintResult("-3S >= 24US", -3S >= 24US) PrintResult("-3S >= -5I", -3S >= -5I) PrintResult("-3S >= 26UI", -3S >= 26UI) PrintResult("-3S >= -7L", -3S >= -7L) PrintResult("-3S >= 28UL", -3S >= 28UL) PrintResult("-3S >= -9D", -3S >= -9D) PrintResult("-3S >= 10.0F", -3S >= 10.0F) PrintResult("-3S >= -11.0R", -3S >= -11.0R) PrintResult("-3S >= ""12""", -3S >= "12") PrintResult("-3S >= TypeCode.Double", -3S >= TypeCode.Double) PrintResult("24US >= False", 24US >= False) PrintResult("24US >= True", 24US >= True) PrintResult("24US >= System.SByte.MinValue", 24US >= System.SByte.MinValue) PrintResult("24US >= System.Byte.MaxValue", 24US >= System.Byte.MaxValue) PrintResult("24US >= -3S", 24US >= -3S) PrintResult("24US >= 24US", 24US >= 24US) PrintResult("24US >= -5I", 24US >= -5I) PrintResult("24US >= 26UI", 24US >= 26UI) PrintResult("24US >= -7L", 24US >= -7L) PrintResult("24US >= 28UL", 24US >= 28UL) PrintResult("24US >= -9D", 24US >= -9D) PrintResult("24US >= 10.0F", 24US >= 10.0F) PrintResult("24US >= -11.0R", 24US >= -11.0R) PrintResult("24US >= ""12""", 24US >= "12") PrintResult("24US >= TypeCode.Double", 24US >= TypeCode.Double) PrintResult("-5I >= False", -5I >= False) PrintResult("-5I >= True", -5I >= True) PrintResult("-5I >= System.SByte.MinValue", -5I >= System.SByte.MinValue) PrintResult("-5I >= System.Byte.MaxValue", -5I >= System.Byte.MaxValue) PrintResult("-5I >= -3S", -5I >= -3S) PrintResult("-5I >= 24US", -5I >= 24US) PrintResult("-5I >= -5I", -5I >= -5I) PrintResult("-5I >= 26UI", -5I >= 26UI) PrintResult("-5I >= -7L", -5I >= -7L) PrintResult("-5I >= 28UL", -5I >= 28UL) PrintResult("-5I >= -9D", -5I >= -9D) PrintResult("-5I >= 10.0F", -5I >= 10.0F) PrintResult("-5I >= -11.0R", -5I >= -11.0R) PrintResult("-5I >= ""12""", -5I >= "12") PrintResult("-5I >= TypeCode.Double", -5I >= TypeCode.Double) PrintResult("26UI >= False", 26UI >= False) PrintResult("26UI >= True", 26UI >= True) PrintResult("26UI >= System.SByte.MinValue", 26UI >= System.SByte.MinValue) PrintResult("26UI >= System.Byte.MaxValue", 26UI >= System.Byte.MaxValue) PrintResult("26UI >= -3S", 26UI >= -3S) PrintResult("26UI >= 24US", 26UI >= 24US) PrintResult("26UI >= -5I", 26UI >= -5I) PrintResult("26UI >= 26UI", 26UI >= 26UI) PrintResult("26UI >= -7L", 26UI >= -7L) PrintResult("26UI >= 28UL", 26UI >= 28UL) PrintResult("26UI >= -9D", 26UI >= -9D) PrintResult("26UI >= 10.0F", 26UI >= 10.0F) PrintResult("26UI >= -11.0R", 26UI >= -11.0R) PrintResult("26UI >= ""12""", 26UI >= "12") PrintResult("26UI >= TypeCode.Double", 26UI >= TypeCode.Double) PrintResult("-7L >= False", -7L >= False) PrintResult("-7L >= True", -7L >= True) PrintResult("-7L >= System.SByte.MinValue", -7L >= System.SByte.MinValue) PrintResult("-7L >= System.Byte.MaxValue", -7L >= System.Byte.MaxValue) PrintResult("-7L >= -3S", -7L >= -3S) PrintResult("-7L >= 24US", -7L >= 24US) PrintResult("-7L >= -5I", -7L >= -5I) PrintResult("-7L >= 26UI", -7L >= 26UI) PrintResult("-7L >= -7L", -7L >= -7L) PrintResult("-7L >= 28UL", -7L >= 28UL) PrintResult("-7L >= -9D", -7L >= -9D) PrintResult("-7L >= 10.0F", -7L >= 10.0F) PrintResult("-7L >= -11.0R", -7L >= -11.0R) PrintResult("-7L >= ""12""", -7L >= "12") PrintResult("-7L >= TypeCode.Double", -7L >= TypeCode.Double) PrintResult("28UL >= False", 28UL >= False) PrintResult("28UL >= True", 28UL >= True) PrintResult("28UL >= System.SByte.MinValue", 28UL >= System.SByte.MinValue) PrintResult("28UL >= System.Byte.MaxValue", 28UL >= System.Byte.MaxValue) PrintResult("28UL >= -3S", 28UL >= -3S) PrintResult("28UL >= 24US", 28UL >= 24US) PrintResult("28UL >= -5I", 28UL >= -5I) PrintResult("28UL >= 26UI", 28UL >= 26UI) PrintResult("28UL >= -7L", 28UL >= -7L) PrintResult("28UL >= 28UL", 28UL >= 28UL) PrintResult("28UL >= -9D", 28UL >= -9D) PrintResult("28UL >= 10.0F", 28UL >= 10.0F) PrintResult("28UL >= -11.0R", 28UL >= -11.0R) PrintResult("28UL >= ""12""", 28UL >= "12") PrintResult("28UL >= TypeCode.Double", 28UL >= TypeCode.Double) PrintResult("-9D >= False", -9D >= False) PrintResult("-9D >= True", -9D >= True) PrintResult("-9D >= System.SByte.MinValue", -9D >= System.SByte.MinValue) PrintResult("-9D >= System.Byte.MaxValue", -9D >= System.Byte.MaxValue) PrintResult("-9D >= -3S", -9D >= -3S) PrintResult("-9D >= 24US", -9D >= 24US) PrintResult("-9D >= -5I", -9D >= -5I) PrintResult("-9D >= 26UI", -9D >= 26UI) PrintResult("-9D >= -7L", -9D >= -7L) PrintResult("-9D >= 28UL", -9D >= 28UL) PrintResult("-9D >= -9D", -9D >= -9D) PrintResult("-9D >= 10.0F", -9D >= 10.0F) PrintResult("-9D >= -11.0R", -9D >= -11.0R) PrintResult("-9D >= ""12""", -9D >= "12") PrintResult("-9D >= TypeCode.Double", -9D >= TypeCode.Double) PrintResult("10.0F >= False", 10.0F >= False) PrintResult("10.0F >= True", 10.0F >= True) PrintResult("10.0F >= System.SByte.MinValue", 10.0F >= System.SByte.MinValue) PrintResult("10.0F >= System.Byte.MaxValue", 10.0F >= System.Byte.MaxValue) PrintResult("10.0F >= -3S", 10.0F >= -3S) PrintResult("10.0F >= 24US", 10.0F >= 24US) PrintResult("10.0F >= -5I", 10.0F >= -5I) PrintResult("10.0F >= 26UI", 10.0F >= 26UI) PrintResult("10.0F >= -7L", 10.0F >= -7L) PrintResult("10.0F >= 28UL", 10.0F >= 28UL) PrintResult("10.0F >= -9D", 10.0F >= -9D) PrintResult("10.0F >= 10.0F", 10.0F >= 10.0F) PrintResult("10.0F >= -11.0R", 10.0F >= -11.0R) PrintResult("10.0F >= ""12""", 10.0F >= "12") PrintResult("10.0F >= TypeCode.Double", 10.0F >= TypeCode.Double) PrintResult("-11.0R >= False", -11.0R >= False) PrintResult("-11.0R >= True", -11.0R >= True) PrintResult("-11.0R >= System.SByte.MinValue", -11.0R >= System.SByte.MinValue) PrintResult("-11.0R >= System.Byte.MaxValue", -11.0R >= System.Byte.MaxValue) PrintResult("-11.0R >= -3S", -11.0R >= -3S) PrintResult("-11.0R >= 24US", -11.0R >= 24US) PrintResult("-11.0R >= -5I", -11.0R >= -5I) PrintResult("-11.0R >= 26UI", -11.0R >= 26UI) PrintResult("-11.0R >= -7L", -11.0R >= -7L) PrintResult("-11.0R >= 28UL", -11.0R >= 28UL) PrintResult("-11.0R >= -9D", -11.0R >= -9D) PrintResult("-11.0R >= 10.0F", -11.0R >= 10.0F) PrintResult("-11.0R >= -11.0R", -11.0R >= -11.0R) PrintResult("-11.0R >= ""12""", -11.0R >= "12") PrintResult("-11.0R >= TypeCode.Double", -11.0R >= TypeCode.Double) PrintResult("""12"" >= False", "12" >= False) PrintResult("""12"" >= True", "12" >= True) PrintResult("""12"" >= System.SByte.MinValue", "12" >= System.SByte.MinValue) PrintResult("""12"" >= System.Byte.MaxValue", "12" >= System.Byte.MaxValue) PrintResult("""12"" >= -3S", "12" >= -3S) PrintResult("""12"" >= 24US", "12" >= 24US) PrintResult("""12"" >= -5I", "12" >= -5I) PrintResult("""12"" >= 26UI", "12" >= 26UI) PrintResult("""12"" >= -7L", "12" >= -7L) PrintResult("""12"" >= 28UL", "12" >= 28UL) PrintResult("""12"" >= -9D", "12" >= -9D) PrintResult("""12"" >= 10.0F", "12" >= 10.0F) PrintResult("""12"" >= -11.0R", "12" >= -11.0R) PrintResult("""12"" >= ""12""", "12" >= "12") PrintResult("""12"" >= TypeCode.Double", "12" >= TypeCode.Double) PrintResult("TypeCode.Double >= False", TypeCode.Double >= False) PrintResult("TypeCode.Double >= True", TypeCode.Double >= True) PrintResult("TypeCode.Double >= System.SByte.MinValue", TypeCode.Double >= System.SByte.MinValue) PrintResult("TypeCode.Double >= System.Byte.MaxValue", TypeCode.Double >= System.Byte.MaxValue) PrintResult("TypeCode.Double >= -3S", TypeCode.Double >= -3S) PrintResult("TypeCode.Double >= 24US", TypeCode.Double >= 24US) PrintResult("TypeCode.Double >= -5I", TypeCode.Double >= -5I) PrintResult("TypeCode.Double >= 26UI", TypeCode.Double >= 26UI) PrintResult("TypeCode.Double >= -7L", TypeCode.Double >= -7L) PrintResult("TypeCode.Double >= 28UL", TypeCode.Double >= 28UL) PrintResult("TypeCode.Double >= -9D", TypeCode.Double >= -9D) PrintResult("TypeCode.Double >= 10.0F", TypeCode.Double >= 10.0F) PrintResult("TypeCode.Double >= -11.0R", TypeCode.Double >= -11.0R) PrintResult("TypeCode.Double >= ""12""", TypeCode.Double >= "12") PrintResult("TypeCode.Double >= TypeCode.Double", TypeCode.Double >= TypeCode.Double) PrintResult("False < False", False < False) PrintResult("False < True", False < True) PrintResult("False < System.SByte.MinValue", False < System.SByte.MinValue) PrintResult("False < System.Byte.MaxValue", False < System.Byte.MaxValue) PrintResult("False < -3S", False < -3S) PrintResult("False < 24US", False < 24US) PrintResult("False < -5I", False < -5I) PrintResult("False < 26UI", False < 26UI) PrintResult("False < -7L", False < -7L) PrintResult("False < 28UL", False < 28UL) PrintResult("False < -9D", False < -9D) PrintResult("False < 10.0F", False < 10.0F) PrintResult("False < -11.0R", False < -11.0R) PrintResult("False < ""12""", False < "12") PrintResult("False < TypeCode.Double", False < TypeCode.Double) PrintResult("True < False", True < False) PrintResult("True < True", True < True) PrintResult("True < System.SByte.MinValue", True < System.SByte.MinValue) PrintResult("True < System.Byte.MaxValue", True < System.Byte.MaxValue) PrintResult("True < -3S", True < -3S) PrintResult("True < 24US", True < 24US) PrintResult("True < -5I", True < -5I) PrintResult("True < 26UI", True < 26UI) PrintResult("True < -7L", True < -7L) PrintResult("True < 28UL", True < 28UL) PrintResult("True < -9D", True < -9D) PrintResult("True < 10.0F", True < 10.0F) PrintResult("True < -11.0R", True < -11.0R) PrintResult("True < ""12""", True < "12") PrintResult("True < TypeCode.Double", True < TypeCode.Double) PrintResult("System.SByte.MinValue < False", System.SByte.MinValue < False) PrintResult("System.SByte.MinValue < True", System.SByte.MinValue < True) PrintResult("System.SByte.MinValue < System.SByte.MinValue", System.SByte.MinValue < System.SByte.MinValue) PrintResult("System.SByte.MinValue < System.Byte.MaxValue", System.SByte.MinValue < System.Byte.MaxValue) PrintResult("System.SByte.MinValue < -3S", System.SByte.MinValue < -3S) PrintResult("System.SByte.MinValue < 24US", System.SByte.MinValue < 24US) PrintResult("System.SByte.MinValue < -5I", System.SByte.MinValue < -5I) PrintResult("System.SByte.MinValue < 26UI", System.SByte.MinValue < 26UI) PrintResult("System.SByte.MinValue < -7L", System.SByte.MinValue < -7L) PrintResult("System.SByte.MinValue < 28UL", System.SByte.MinValue < 28UL) PrintResult("System.SByte.MinValue < -9D", System.SByte.MinValue < -9D) PrintResult("System.SByte.MinValue < 10.0F", System.SByte.MinValue < 10.0F) PrintResult("System.SByte.MinValue < -11.0R", System.SByte.MinValue < -11.0R) PrintResult("System.SByte.MinValue < ""12""", System.SByte.MinValue < "12") PrintResult("System.SByte.MinValue < TypeCode.Double", System.SByte.MinValue < TypeCode.Double) PrintResult("System.Byte.MaxValue < False", System.Byte.MaxValue < False) PrintResult("System.Byte.MaxValue < True", System.Byte.MaxValue < True) PrintResult("System.Byte.MaxValue < System.SByte.MinValue", System.Byte.MaxValue < System.SByte.MinValue) PrintResult("System.Byte.MaxValue < System.Byte.MaxValue", System.Byte.MaxValue < System.Byte.MaxValue) PrintResult("System.Byte.MaxValue < -3S", System.Byte.MaxValue < -3S) PrintResult("System.Byte.MaxValue < 24US", System.Byte.MaxValue < 24US) PrintResult("System.Byte.MaxValue < -5I", System.Byte.MaxValue < -5I) PrintResult("System.Byte.MaxValue < 26UI", System.Byte.MaxValue < 26UI) PrintResult("System.Byte.MaxValue < -7L", System.Byte.MaxValue < -7L) PrintResult("System.Byte.MaxValue < 28UL", System.Byte.MaxValue < 28UL) PrintResult("System.Byte.MaxValue < -9D", System.Byte.MaxValue < -9D) PrintResult("System.Byte.MaxValue < 10.0F", System.Byte.MaxValue < 10.0F) PrintResult("System.Byte.MaxValue < -11.0R", System.Byte.MaxValue < -11.0R) PrintResult("System.Byte.MaxValue < ""12""", System.Byte.MaxValue < "12") PrintResult("System.Byte.MaxValue < TypeCode.Double", System.Byte.MaxValue < TypeCode.Double) PrintResult("-3S < False", -3S < False) PrintResult("-3S < True", -3S < True) PrintResult("-3S < System.SByte.MinValue", -3S < System.SByte.MinValue) PrintResult("-3S < System.Byte.MaxValue", -3S < System.Byte.MaxValue) PrintResult("-3S < -3S", -3S < -3S) PrintResult("-3S < 24US", -3S < 24US) PrintResult("-3S < -5I", -3S < -5I) PrintResult("-3S < 26UI", -3S < 26UI) PrintResult("-3S < -7L", -3S < -7L) PrintResult("-3S < 28UL", -3S < 28UL) PrintResult("-3S < -9D", -3S < -9D) PrintResult("-3S < 10.0F", -3S < 10.0F) PrintResult("-3S < -11.0R", -3S < -11.0R) PrintResult("-3S < ""12""", -3S < "12") PrintResult("-3S < TypeCode.Double", -3S < TypeCode.Double) PrintResult("24US < False", 24US < False) PrintResult("24US < True", 24US < True) PrintResult("24US < System.SByte.MinValue", 24US < System.SByte.MinValue) PrintResult("24US < System.Byte.MaxValue", 24US < System.Byte.MaxValue) PrintResult("24US < -3S", 24US < -3S) PrintResult("24US < 24US", 24US < 24US) PrintResult("24US < -5I", 24US < -5I) PrintResult("24US < 26UI", 24US < 26UI) PrintResult("24US < -7L", 24US < -7L) PrintResult("24US < 28UL", 24US < 28UL) PrintResult("24US < -9D", 24US < -9D) PrintResult("24US < 10.0F", 24US < 10.0F) PrintResult("24US < -11.0R", 24US < -11.0R) PrintResult("24US < ""12""", 24US < "12") PrintResult("24US < TypeCode.Double", 24US < TypeCode.Double) PrintResult("-5I < False", -5I < False) PrintResult("-5I < True", -5I < True) PrintResult("-5I < System.SByte.MinValue", -5I < System.SByte.MinValue) PrintResult("-5I < System.Byte.MaxValue", -5I < System.Byte.MaxValue) PrintResult("-5I < -3S", -5I < -3S) PrintResult("-5I < 24US", -5I < 24US) PrintResult("-5I < -5I", -5I < -5I) PrintResult("-5I < 26UI", -5I < 26UI) PrintResult("-5I < -7L", -5I < -7L) PrintResult("-5I < 28UL", -5I < 28UL) PrintResult("-5I < -9D", -5I < -9D) PrintResult("-5I < 10.0F", -5I < 10.0F) PrintResult("-5I < -11.0R", -5I < -11.0R) PrintResult("-5I < ""12""", -5I < "12") PrintResult("-5I < TypeCode.Double", -5I < TypeCode.Double) PrintResult("26UI < False", 26UI < False) PrintResult("26UI < True", 26UI < True) PrintResult("26UI < System.SByte.MinValue", 26UI < System.SByte.MinValue) PrintResult("26UI < System.Byte.MaxValue", 26UI < System.Byte.MaxValue) PrintResult("26UI < -3S", 26UI < -3S) PrintResult("26UI < 24US", 26UI < 24US) PrintResult("26UI < -5I", 26UI < -5I) PrintResult("26UI < 26UI", 26UI < 26UI) PrintResult("26UI < -7L", 26UI < -7L) PrintResult("26UI < 28UL", 26UI < 28UL) PrintResult("26UI < -9D", 26UI < -9D) PrintResult("26UI < 10.0F", 26UI < 10.0F) PrintResult("26UI < -11.0R", 26UI < -11.0R) PrintResult("26UI < ""12""", 26UI < "12") PrintResult("26UI < TypeCode.Double", 26UI < TypeCode.Double) PrintResult("-7L < False", -7L < False) PrintResult("-7L < True", -7L < True) PrintResult("-7L < System.SByte.MinValue", -7L < System.SByte.MinValue) PrintResult("-7L < System.Byte.MaxValue", -7L < System.Byte.MaxValue) PrintResult("-7L < -3S", -7L < -3S) PrintResult("-7L < 24US", -7L < 24US) PrintResult("-7L < -5I", -7L < -5I) PrintResult("-7L < 26UI", -7L < 26UI) PrintResult("-7L < -7L", -7L < -7L) PrintResult("-7L < 28UL", -7L < 28UL) PrintResult("-7L < -9D", -7L < -9D) PrintResult("-7L < 10.0F", -7L < 10.0F) PrintResult("-7L < -11.0R", -7L < -11.0R) PrintResult("-7L < ""12""", -7L < "12") PrintResult("-7L < TypeCode.Double", -7L < TypeCode.Double) PrintResult("28UL < False", 28UL < False) PrintResult("28UL < True", 28UL < True) PrintResult("28UL < System.SByte.MinValue", 28UL < System.SByte.MinValue) PrintResult("28UL < System.Byte.MaxValue", 28UL < System.Byte.MaxValue) PrintResult("28UL < -3S", 28UL < -3S) PrintResult("28UL < 24US", 28UL < 24US) PrintResult("28UL < -5I", 28UL < -5I) PrintResult("28UL < 26UI", 28UL < 26UI) PrintResult("28UL < -7L", 28UL < -7L) PrintResult("28UL < 28UL", 28UL < 28UL) PrintResult("28UL < -9D", 28UL < -9D) PrintResult("28UL < 10.0F", 28UL < 10.0F) PrintResult("28UL < -11.0R", 28UL < -11.0R) PrintResult("28UL < ""12""", 28UL < "12") PrintResult("28UL < TypeCode.Double", 28UL < TypeCode.Double) PrintResult("-9D < False", -9D < False) PrintResult("-9D < True", -9D < True) PrintResult("-9D < System.SByte.MinValue", -9D < System.SByte.MinValue) PrintResult("-9D < System.Byte.MaxValue", -9D < System.Byte.MaxValue) PrintResult("-9D < -3S", -9D < -3S) PrintResult("-9D < 24US", -9D < 24US) PrintResult("-9D < -5I", -9D < -5I) PrintResult("-9D < 26UI", -9D < 26UI) PrintResult("-9D < -7L", -9D < -7L) PrintResult("-9D < 28UL", -9D < 28UL) PrintResult("-9D < -9D", -9D < -9D) PrintResult("-9D < 10.0F", -9D < 10.0F) PrintResult("-9D < -11.0R", -9D < -11.0R) PrintResult("-9D < ""12""", -9D < "12") PrintResult("-9D < TypeCode.Double", -9D < TypeCode.Double) PrintResult("10.0F < False", 10.0F < False) PrintResult("10.0F < True", 10.0F < True) PrintResult("10.0F < System.SByte.MinValue", 10.0F < System.SByte.MinValue) PrintResult("10.0F < System.Byte.MaxValue", 10.0F < System.Byte.MaxValue) PrintResult("10.0F < -3S", 10.0F < -3S) PrintResult("10.0F < 24US", 10.0F < 24US) PrintResult("10.0F < -5I", 10.0F < -5I) PrintResult("10.0F < 26UI", 10.0F < 26UI) PrintResult("10.0F < -7L", 10.0F < -7L) PrintResult("10.0F < 28UL", 10.0F < 28UL) PrintResult("10.0F < -9D", 10.0F < -9D) PrintResult("10.0F < 10.0F", 10.0F < 10.0F) PrintResult("10.0F < -11.0R", 10.0F < -11.0R) PrintResult("10.0F < ""12""", 10.0F < "12") PrintResult("10.0F < TypeCode.Double", 10.0F < TypeCode.Double) PrintResult("-11.0R < False", -11.0R < False) PrintResult("-11.0R < True", -11.0R < True) PrintResult("-11.0R < System.SByte.MinValue", -11.0R < System.SByte.MinValue) PrintResult("-11.0R < System.Byte.MaxValue", -11.0R < System.Byte.MaxValue) PrintResult("-11.0R < -3S", -11.0R < -3S) PrintResult("-11.0R < 24US", -11.0R < 24US) PrintResult("-11.0R < -5I", -11.0R < -5I) PrintResult("-11.0R < 26UI", -11.0R < 26UI) PrintResult("-11.0R < -7L", -11.0R < -7L) PrintResult("-11.0R < 28UL", -11.0R < 28UL) PrintResult("-11.0R < -9D", -11.0R < -9D) PrintResult("-11.0R < 10.0F", -11.0R < 10.0F) PrintResult("-11.0R < -11.0R", -11.0R < -11.0R) PrintResult("-11.0R < ""12""", -11.0R < "12") PrintResult("-11.0R < TypeCode.Double", -11.0R < TypeCode.Double) PrintResult("""12"" < False", "12" < False) PrintResult("""12"" < True", "12" < True) PrintResult("""12"" < System.SByte.MinValue", "12" < System.SByte.MinValue) PrintResult("""12"" < System.Byte.MaxValue", "12" < System.Byte.MaxValue) PrintResult("""12"" < -3S", "12" < -3S) PrintResult("""12"" < 24US", "12" < 24US) PrintResult("""12"" < -5I", "12" < -5I) PrintResult("""12"" < 26UI", "12" < 26UI) PrintResult("""12"" < -7L", "12" < -7L) PrintResult("""12"" < 28UL", "12" < 28UL) PrintResult("""12"" < -9D", "12" < -9D) PrintResult("""12"" < 10.0F", "12" < 10.0F) PrintResult("""12"" < -11.0R", "12" < -11.0R) PrintResult("""12"" < ""12""", "12" < "12") PrintResult("""12"" < TypeCode.Double", "12" < TypeCode.Double) PrintResult("TypeCode.Double < False", TypeCode.Double < False) PrintResult("TypeCode.Double < True", TypeCode.Double < True) PrintResult("TypeCode.Double < System.SByte.MinValue", TypeCode.Double < System.SByte.MinValue) PrintResult("TypeCode.Double < System.Byte.MaxValue", TypeCode.Double < System.Byte.MaxValue) PrintResult("TypeCode.Double < -3S", TypeCode.Double < -3S) PrintResult("TypeCode.Double < 24US", TypeCode.Double < 24US) PrintResult("TypeCode.Double < -5I", TypeCode.Double < -5I) PrintResult("TypeCode.Double < 26UI", TypeCode.Double < 26UI) PrintResult("TypeCode.Double < -7L", TypeCode.Double < -7L) PrintResult("TypeCode.Double < 28UL", TypeCode.Double < 28UL) PrintResult("TypeCode.Double < -9D", TypeCode.Double < -9D) PrintResult("TypeCode.Double < 10.0F", TypeCode.Double < 10.0F) PrintResult("TypeCode.Double < -11.0R", TypeCode.Double < -11.0R) PrintResult("TypeCode.Double < ""12""", TypeCode.Double < "12") PrintResult("TypeCode.Double < TypeCode.Double", TypeCode.Double < TypeCode.Double) PrintResult("False > False", False > False) PrintResult("False > True", False > True) PrintResult("False > System.SByte.MinValue", False > System.SByte.MinValue) PrintResult("False > System.Byte.MaxValue", False > System.Byte.MaxValue) PrintResult("False > -3S", False > -3S) PrintResult("False > 24US", False > 24US) PrintResult("False > -5I", False > -5I) PrintResult("False > 26UI", False > 26UI) PrintResult("False > -7L", False > -7L) PrintResult("False > 28UL", False > 28UL) PrintResult("False > -9D", False > -9D) PrintResult("False > 10.0F", False > 10.0F) PrintResult("False > -11.0R", False > -11.0R) PrintResult("False > ""12""", False > "12") PrintResult("False > TypeCode.Double", False > TypeCode.Double) PrintResult("True > False", True > False) PrintResult("True > True", True > True) PrintResult("True > System.SByte.MinValue", True > System.SByte.MinValue) PrintResult("True > System.Byte.MaxValue", True > System.Byte.MaxValue) PrintResult("True > -3S", True > -3S) PrintResult("True > 24US", True > 24US) PrintResult("True > -5I", True > -5I) PrintResult("True > 26UI", True > 26UI) PrintResult("True > -7L", True > -7L) PrintResult("True > 28UL", True > 28UL) PrintResult("True > -9D", True > -9D) PrintResult("True > 10.0F", True > 10.0F) PrintResult("True > -11.0R", True > -11.0R) PrintResult("True > ""12""", True > "12") PrintResult("True > TypeCode.Double", True > TypeCode.Double) PrintResult("System.SByte.MinValue > False", System.SByte.MinValue > False) PrintResult("System.SByte.MinValue > True", System.SByte.MinValue > True) PrintResult("System.SByte.MinValue > System.SByte.MinValue", System.SByte.MinValue > System.SByte.MinValue) PrintResult("System.SByte.MinValue > System.Byte.MaxValue", System.SByte.MinValue > System.Byte.MaxValue) PrintResult("System.SByte.MinValue > -3S", System.SByte.MinValue > -3S) PrintResult("System.SByte.MinValue > 24US", System.SByte.MinValue > 24US) PrintResult("System.SByte.MinValue > -5I", System.SByte.MinValue > -5I) PrintResult("System.SByte.MinValue > 26UI", System.SByte.MinValue > 26UI) PrintResult("System.SByte.MinValue > -7L", System.SByte.MinValue > -7L) PrintResult("System.SByte.MinValue > 28UL", System.SByte.MinValue > 28UL) PrintResult("System.SByte.MinValue > -9D", System.SByte.MinValue > -9D) PrintResult("System.SByte.MinValue > 10.0F", System.SByte.MinValue > 10.0F) PrintResult("System.SByte.MinValue > -11.0R", System.SByte.MinValue > -11.0R) PrintResult("System.SByte.MinValue > ""12""", System.SByte.MinValue > "12") PrintResult("System.SByte.MinValue > TypeCode.Double", System.SByte.MinValue > TypeCode.Double) PrintResult("System.Byte.MaxValue > False", System.Byte.MaxValue > False) PrintResult("System.Byte.MaxValue > True", System.Byte.MaxValue > True) PrintResult("System.Byte.MaxValue > System.SByte.MinValue", System.Byte.MaxValue > System.SByte.MinValue) PrintResult("System.Byte.MaxValue > System.Byte.MaxValue", System.Byte.MaxValue > System.Byte.MaxValue) PrintResult("System.Byte.MaxValue > -3S", System.Byte.MaxValue > -3S) PrintResult("System.Byte.MaxValue > 24US", System.Byte.MaxValue > 24US) PrintResult("System.Byte.MaxValue > -5I", System.Byte.MaxValue > -5I) PrintResult("System.Byte.MaxValue > 26UI", System.Byte.MaxValue > 26UI) PrintResult("System.Byte.MaxValue > -7L", System.Byte.MaxValue > -7L) PrintResult("System.Byte.MaxValue > 28UL", System.Byte.MaxValue > 28UL) PrintResult("System.Byte.MaxValue > -9D", System.Byte.MaxValue > -9D) PrintResult("System.Byte.MaxValue > 10.0F", System.Byte.MaxValue > 10.0F) PrintResult("System.Byte.MaxValue > -11.0R", System.Byte.MaxValue > -11.0R) PrintResult("System.Byte.MaxValue > ""12""", System.Byte.MaxValue > "12") PrintResult("System.Byte.MaxValue > TypeCode.Double", System.Byte.MaxValue > TypeCode.Double) PrintResult("-3S > False", -3S > False) PrintResult("-3S > True", -3S > True) PrintResult("-3S > System.SByte.MinValue", -3S > System.SByte.MinValue) PrintResult("-3S > System.Byte.MaxValue", -3S > System.Byte.MaxValue) PrintResult("-3S > -3S", -3S > -3S) PrintResult("-3S > 24US", -3S > 24US) PrintResult("-3S > -5I", -3S > -5I) PrintResult("-3S > 26UI", -3S > 26UI) PrintResult("-3S > -7L", -3S > -7L) PrintResult("-3S > 28UL", -3S > 28UL) PrintResult("-3S > -9D", -3S > -9D) PrintResult("-3S > 10.0F", -3S > 10.0F) PrintResult("-3S > -11.0R", -3S > -11.0R) PrintResult("-3S > ""12""", -3S > "12") PrintResult("-3S > TypeCode.Double", -3S > TypeCode.Double) PrintResult("24US > False", 24US > False) PrintResult("24US > True", 24US > True) PrintResult("24US > System.SByte.MinValue", 24US > System.SByte.MinValue) PrintResult("24US > System.Byte.MaxValue", 24US > System.Byte.MaxValue) PrintResult("24US > -3S", 24US > -3S) PrintResult("24US > 24US", 24US > 24US) PrintResult("24US > -5I", 24US > -5I) PrintResult("24US > 26UI", 24US > 26UI) PrintResult("24US > -7L", 24US > -7L) PrintResult("24US > 28UL", 24US > 28UL) PrintResult("24US > -9D", 24US > -9D) PrintResult("24US > 10.0F", 24US > 10.0F) PrintResult("24US > -11.0R", 24US > -11.0R) PrintResult("24US > ""12""", 24US > "12") PrintResult("24US > TypeCode.Double", 24US > TypeCode.Double) PrintResult("-5I > False", -5I > False) PrintResult("-5I > True", -5I > True) PrintResult("-5I > System.SByte.MinValue", -5I > System.SByte.MinValue) PrintResult("-5I > System.Byte.MaxValue", -5I > System.Byte.MaxValue) PrintResult("-5I > -3S", -5I > -3S) PrintResult("-5I > 24US", -5I > 24US) PrintResult("-5I > -5I", -5I > -5I) PrintResult("-5I > 26UI", -5I > 26UI) PrintResult("-5I > -7L", -5I > -7L) PrintResult("-5I > 28UL", -5I > 28UL) PrintResult("-5I > -9D", -5I > -9D) PrintResult("-5I > 10.0F", -5I > 10.0F) PrintResult("-5I > -11.0R", -5I > -11.0R) PrintResult("-5I > ""12""", -5I > "12") PrintResult("-5I > TypeCode.Double", -5I > TypeCode.Double) PrintResult("26UI > False", 26UI > False) PrintResult("26UI > True", 26UI > True) PrintResult("26UI > System.SByte.MinValue", 26UI > System.SByte.MinValue) PrintResult("26UI > System.Byte.MaxValue", 26UI > System.Byte.MaxValue) PrintResult("26UI > -3S", 26UI > -3S) PrintResult("26UI > 24US", 26UI > 24US) PrintResult("26UI > -5I", 26UI > -5I) PrintResult("26UI > 26UI", 26UI > 26UI) PrintResult("26UI > -7L", 26UI > -7L) PrintResult("26UI > 28UL", 26UI > 28UL) PrintResult("26UI > -9D", 26UI > -9D) PrintResult("26UI > 10.0F", 26UI > 10.0F) PrintResult("26UI > -11.0R", 26UI > -11.0R) PrintResult("26UI > ""12""", 26UI > "12") PrintResult("26UI > TypeCode.Double", 26UI > TypeCode.Double) PrintResult("-7L > False", -7L > False) PrintResult("-7L > True", -7L > True) PrintResult("-7L > System.SByte.MinValue", -7L > System.SByte.MinValue) PrintResult("-7L > System.Byte.MaxValue", -7L > System.Byte.MaxValue) PrintResult("-7L > -3S", -7L > -3S) PrintResult("-7L > 24US", -7L > 24US) PrintResult("-7L > -5I", -7L > -5I) PrintResult("-7L > 26UI", -7L > 26UI) PrintResult("-7L > -7L", -7L > -7L) PrintResult("-7L > 28UL", -7L > 28UL) PrintResult("-7L > -9D", -7L > -9D) PrintResult("-7L > 10.0F", -7L > 10.0F) PrintResult("-7L > -11.0R", -7L > -11.0R) PrintResult("-7L > ""12""", -7L > "12") PrintResult("-7L > TypeCode.Double", -7L > TypeCode.Double) PrintResult("28UL > False", 28UL > False) PrintResult("28UL > True", 28UL > True) PrintResult("28UL > System.SByte.MinValue", 28UL > System.SByte.MinValue) PrintResult("28UL > System.Byte.MaxValue", 28UL > System.Byte.MaxValue) PrintResult("28UL > -3S", 28UL > -3S) PrintResult("28UL > 24US", 28UL > 24US) PrintResult("28UL > -5I", 28UL > -5I) PrintResult("28UL > 26UI", 28UL > 26UI) PrintResult("28UL > -7L", 28UL > -7L) PrintResult("28UL > 28UL", 28UL > 28UL) PrintResult("28UL > -9D", 28UL > -9D) PrintResult("28UL > 10.0F", 28UL > 10.0F) PrintResult("28UL > -11.0R", 28UL > -11.0R) PrintResult("28UL > ""12""", 28UL > "12") PrintResult("28UL > TypeCode.Double", 28UL > TypeCode.Double) PrintResult("-9D > False", -9D > False) PrintResult("-9D > True", -9D > True) PrintResult("-9D > System.SByte.MinValue", -9D > System.SByte.MinValue) PrintResult("-9D > System.Byte.MaxValue", -9D > System.Byte.MaxValue) PrintResult("-9D > -3S", -9D > -3S) PrintResult("-9D > 24US", -9D > 24US) PrintResult("-9D > -5I", -9D > -5I) PrintResult("-9D > 26UI", -9D > 26UI) PrintResult("-9D > -7L", -9D > -7L) PrintResult("-9D > 28UL", -9D > 28UL) PrintResult("-9D > -9D", -9D > -9D) PrintResult("-9D > 10.0F", -9D > 10.0F) PrintResult("-9D > -11.0R", -9D > -11.0R) PrintResult("-9D > ""12""", -9D > "12") PrintResult("-9D > TypeCode.Double", -9D > TypeCode.Double) PrintResult("10.0F > False", 10.0F > False) PrintResult("10.0F > True", 10.0F > True) PrintResult("10.0F > System.SByte.MinValue", 10.0F > System.SByte.MinValue) PrintResult("10.0F > System.Byte.MaxValue", 10.0F > System.Byte.MaxValue) PrintResult("10.0F > -3S", 10.0F > -3S) PrintResult("10.0F > 24US", 10.0F > 24US) PrintResult("10.0F > -5I", 10.0F > -5I) PrintResult("10.0F > 26UI", 10.0F > 26UI) PrintResult("10.0F > -7L", 10.0F > -7L) PrintResult("10.0F > 28UL", 10.0F > 28UL) PrintResult("10.0F > -9D", 10.0F > -9D) PrintResult("10.0F > 10.0F", 10.0F > 10.0F) PrintResult("10.0F > -11.0R", 10.0F > -11.0R) PrintResult("10.0F > ""12""", 10.0F > "12") PrintResult("10.0F > TypeCode.Double", 10.0F > TypeCode.Double) PrintResult("-11.0R > False", -11.0R > False) PrintResult("-11.0R > True", -11.0R > True) PrintResult("-11.0R > System.SByte.MinValue", -11.0R > System.SByte.MinValue) PrintResult("-11.0R > System.Byte.MaxValue", -11.0R > System.Byte.MaxValue) PrintResult("-11.0R > -3S", -11.0R > -3S) PrintResult("-11.0R > 24US", -11.0R > 24US) PrintResult("-11.0R > -5I", -11.0R > -5I) PrintResult("-11.0R > 26UI", -11.0R > 26UI) PrintResult("-11.0R > -7L", -11.0R > -7L) PrintResult("-11.0R > 28UL", -11.0R > 28UL) PrintResult("-11.0R > -9D", -11.0R > -9D) PrintResult("-11.0R > 10.0F", -11.0R > 10.0F) PrintResult("-11.0R > -11.0R", -11.0R > -11.0R) PrintResult("-11.0R > ""12""", -11.0R > "12") PrintResult("-11.0R > TypeCode.Double", -11.0R > TypeCode.Double) PrintResult("""12"" > False", "12" > False) PrintResult("""12"" > True", "12" > True) PrintResult("""12"" > System.SByte.MinValue", "12" > System.SByte.MinValue) PrintResult("""12"" > System.Byte.MaxValue", "12" > System.Byte.MaxValue) PrintResult("""12"" > -3S", "12" > -3S) PrintResult("""12"" > 24US", "12" > 24US) PrintResult("""12"" > -5I", "12" > -5I) PrintResult("""12"" > 26UI", "12" > 26UI) PrintResult("""12"" > -7L", "12" > -7L) PrintResult("""12"" > 28UL", "12" > 28UL) PrintResult("""12"" > -9D", "12" > -9D) PrintResult("""12"" > 10.0F", "12" > 10.0F) PrintResult("""12"" > -11.0R", "12" > -11.0R) PrintResult("""12"" > ""12""", "12" > "12") PrintResult("""12"" > TypeCode.Double", "12" > TypeCode.Double) PrintResult("TypeCode.Double > False", TypeCode.Double > False) PrintResult("TypeCode.Double > True", TypeCode.Double > True) PrintResult("TypeCode.Double > System.SByte.MinValue", TypeCode.Double > System.SByte.MinValue) PrintResult("TypeCode.Double > System.Byte.MaxValue", TypeCode.Double > System.Byte.MaxValue) PrintResult("TypeCode.Double > -3S", TypeCode.Double > -3S) PrintResult("TypeCode.Double > 24US", TypeCode.Double > 24US) PrintResult("TypeCode.Double > -5I", TypeCode.Double > -5I) PrintResult("TypeCode.Double > 26UI", TypeCode.Double > 26UI) PrintResult("TypeCode.Double > -7L", TypeCode.Double > -7L) PrintResult("TypeCode.Double > 28UL", TypeCode.Double > 28UL) PrintResult("TypeCode.Double > -9D", TypeCode.Double > -9D) PrintResult("TypeCode.Double > 10.0F", TypeCode.Double > 10.0F) PrintResult("TypeCode.Double > -11.0R", TypeCode.Double > -11.0R) PrintResult("TypeCode.Double > ""12""", TypeCode.Double > "12") PrintResult("TypeCode.Double > TypeCode.Double", TypeCode.Double > TypeCode.Double) PrintResult("False Xor False", False Xor False) PrintResult("False Xor True", False Xor True) PrintResult("False Xor System.SByte.MinValue", False Xor System.SByte.MinValue) PrintResult("False Xor System.Byte.MaxValue", False Xor System.Byte.MaxValue) PrintResult("False Xor -3S", False Xor -3S) PrintResult("False Xor 24US", False Xor 24US) PrintResult("False Xor -5I", False Xor -5I) PrintResult("False Xor 26UI", False Xor 26UI) PrintResult("False Xor -7L", False Xor -7L) PrintResult("False Xor 28UL", False Xor 28UL) PrintResult("False Xor -9D", False Xor -9D) PrintResult("False Xor 10.0F", False Xor 10.0F) PrintResult("False Xor -11.0R", False Xor -11.0R) PrintResult("False Xor ""12""", False Xor "12") PrintResult("False Xor TypeCode.Double", False Xor TypeCode.Double) PrintResult("True Xor False", True Xor False) PrintResult("True Xor True", True Xor True) PrintResult("True Xor System.SByte.MinValue", True Xor System.SByte.MinValue) PrintResult("True Xor System.Byte.MaxValue", True Xor System.Byte.MaxValue) PrintResult("True Xor -3S", True Xor -3S) PrintResult("True Xor 24US", True Xor 24US) PrintResult("True Xor -5I", True Xor -5I) PrintResult("True Xor 26UI", True Xor 26UI) PrintResult("True Xor -7L", True Xor -7L) PrintResult("True Xor 28UL", True Xor 28UL) PrintResult("True Xor -9D", True Xor -9D) PrintResult("True Xor 10.0F", True Xor 10.0F) PrintResult("True Xor -11.0R", True Xor -11.0R) PrintResult("True Xor ""12""", True Xor "12") PrintResult("True Xor TypeCode.Double", True Xor TypeCode.Double) PrintResult("System.SByte.MinValue Xor False", System.SByte.MinValue Xor False) PrintResult("System.SByte.MinValue Xor True", System.SByte.MinValue Xor True) PrintResult("System.SByte.MinValue Xor System.SByte.MinValue", System.SByte.MinValue Xor System.SByte.MinValue) PrintResult("System.SByte.MinValue Xor System.Byte.MaxValue", System.SByte.MinValue Xor System.Byte.MaxValue) PrintResult("System.SByte.MinValue Xor -3S", System.SByte.MinValue Xor -3S) PrintResult("System.SByte.MinValue Xor 24US", System.SByte.MinValue Xor 24US) PrintResult("System.SByte.MinValue Xor -5I", System.SByte.MinValue Xor -5I) PrintResult("System.SByte.MinValue Xor 26UI", System.SByte.MinValue Xor 26UI) PrintResult("System.SByte.MinValue Xor -7L", System.SByte.MinValue Xor -7L) PrintResult("System.SByte.MinValue Xor 28UL", System.SByte.MinValue Xor 28UL) PrintResult("System.SByte.MinValue Xor -9D", System.SByte.MinValue Xor -9D) PrintResult("System.SByte.MinValue Xor 10.0F", System.SByte.MinValue Xor 10.0F) PrintResult("System.SByte.MinValue Xor -11.0R", System.SByte.MinValue Xor -11.0R) PrintResult("System.SByte.MinValue Xor ""12""", System.SByte.MinValue Xor "12") PrintResult("System.SByte.MinValue Xor TypeCode.Double", System.SByte.MinValue Xor TypeCode.Double) PrintResult("System.Byte.MaxValue Xor False", System.Byte.MaxValue Xor False) PrintResult("System.Byte.MaxValue Xor True", System.Byte.MaxValue Xor True) PrintResult("System.Byte.MaxValue Xor System.SByte.MinValue", System.Byte.MaxValue Xor System.SByte.MinValue) PrintResult("System.Byte.MaxValue Xor System.Byte.MaxValue", System.Byte.MaxValue Xor System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Xor -3S", System.Byte.MaxValue Xor -3S) PrintResult("System.Byte.MaxValue Xor 24US", System.Byte.MaxValue Xor 24US) PrintResult("System.Byte.MaxValue Xor -5I", System.Byte.MaxValue Xor -5I) PrintResult("System.Byte.MaxValue Xor 26UI", System.Byte.MaxValue Xor 26UI) PrintResult("System.Byte.MaxValue Xor -7L", System.Byte.MaxValue Xor -7L) PrintResult("System.Byte.MaxValue Xor 28UL", System.Byte.MaxValue Xor 28UL) PrintResult("System.Byte.MaxValue Xor -9D", System.Byte.MaxValue Xor -9D) PrintResult("System.Byte.MaxValue Xor 10.0F", System.Byte.MaxValue Xor 10.0F) PrintResult("System.Byte.MaxValue Xor -11.0R", System.Byte.MaxValue Xor -11.0R) PrintResult("System.Byte.MaxValue Xor ""12""", System.Byte.MaxValue Xor "12") PrintResult("System.Byte.MaxValue Xor TypeCode.Double", System.Byte.MaxValue Xor TypeCode.Double) PrintResult("-3S Xor False", -3S Xor False) PrintResult("-3S Xor True", -3S Xor True) PrintResult("-3S Xor System.SByte.MinValue", -3S Xor System.SByte.MinValue) PrintResult("-3S Xor System.Byte.MaxValue", -3S Xor System.Byte.MaxValue) PrintResult("-3S Xor -3S", -3S Xor -3S) PrintResult("-3S Xor 24US", -3S Xor 24US) PrintResult("-3S Xor -5I", -3S Xor -5I) PrintResult("-3S Xor 26UI", -3S Xor 26UI) PrintResult("-3S Xor -7L", -3S Xor -7L) PrintResult("-3S Xor 28UL", -3S Xor 28UL) PrintResult("-3S Xor -9D", -3S Xor -9D) PrintResult("-3S Xor 10.0F", -3S Xor 10.0F) PrintResult("-3S Xor -11.0R", -3S Xor -11.0R) PrintResult("-3S Xor ""12""", -3S Xor "12") PrintResult("-3S Xor TypeCode.Double", -3S Xor TypeCode.Double) PrintResult("24US Xor False", 24US Xor False) PrintResult("24US Xor True", 24US Xor True) PrintResult("24US Xor System.SByte.MinValue", 24US Xor System.SByte.MinValue) PrintResult("24US Xor System.Byte.MaxValue", 24US Xor System.Byte.MaxValue) PrintResult("24US Xor -3S", 24US Xor -3S) PrintResult("24US Xor 24US", 24US Xor 24US) PrintResult("24US Xor -5I", 24US Xor -5I) PrintResult("24US Xor 26UI", 24US Xor 26UI) PrintResult("24US Xor -7L", 24US Xor -7L) PrintResult("24US Xor 28UL", 24US Xor 28UL) PrintResult("24US Xor -9D", 24US Xor -9D) PrintResult("24US Xor 10.0F", 24US Xor 10.0F) PrintResult("24US Xor -11.0R", 24US Xor -11.0R) PrintResult("24US Xor ""12""", 24US Xor "12") PrintResult("24US Xor TypeCode.Double", 24US Xor TypeCode.Double) PrintResult("-5I Xor False", -5I Xor False) PrintResult("-5I Xor True", -5I Xor True) PrintResult("-5I Xor System.SByte.MinValue", -5I Xor System.SByte.MinValue) PrintResult("-5I Xor System.Byte.MaxValue", -5I Xor System.Byte.MaxValue) PrintResult("-5I Xor -3S", -5I Xor -3S) PrintResult("-5I Xor 24US", -5I Xor 24US) PrintResult("-5I Xor -5I", -5I Xor -5I) PrintResult("-5I Xor 26UI", -5I Xor 26UI) PrintResult("-5I Xor -7L", -5I Xor -7L) PrintResult("-5I Xor 28UL", -5I Xor 28UL) PrintResult("-5I Xor -9D", -5I Xor -9D) PrintResult("-5I Xor 10.0F", -5I Xor 10.0F) PrintResult("-5I Xor -11.0R", -5I Xor -11.0R) PrintResult("-5I Xor ""12""", -5I Xor "12") PrintResult("-5I Xor TypeCode.Double", -5I Xor TypeCode.Double) PrintResult("26UI Xor False", 26UI Xor False) PrintResult("26UI Xor True", 26UI Xor True) PrintResult("26UI Xor System.SByte.MinValue", 26UI Xor System.SByte.MinValue) PrintResult("26UI Xor System.Byte.MaxValue", 26UI Xor System.Byte.MaxValue) PrintResult("26UI Xor -3S", 26UI Xor -3S) PrintResult("26UI Xor 24US", 26UI Xor 24US) PrintResult("26UI Xor -5I", 26UI Xor -5I) PrintResult("26UI Xor 26UI", 26UI Xor 26UI) PrintResult("26UI Xor -7L", 26UI Xor -7L) PrintResult("26UI Xor 28UL", 26UI Xor 28UL) PrintResult("26UI Xor -9D", 26UI Xor -9D) PrintResult("26UI Xor 10.0F", 26UI Xor 10.0F) PrintResult("26UI Xor -11.0R", 26UI Xor -11.0R) PrintResult("26UI Xor ""12""", 26UI Xor "12") PrintResult("26UI Xor TypeCode.Double", 26UI Xor TypeCode.Double) PrintResult("-7L Xor False", -7L Xor False) PrintResult("-7L Xor True", -7L Xor True) PrintResult("-7L Xor System.SByte.MinValue", -7L Xor System.SByte.MinValue) PrintResult("-7L Xor System.Byte.MaxValue", -7L Xor System.Byte.MaxValue) PrintResult("-7L Xor -3S", -7L Xor -3S) PrintResult("-7L Xor 24US", -7L Xor 24US) PrintResult("-7L Xor -5I", -7L Xor -5I) PrintResult("-7L Xor 26UI", -7L Xor 26UI) PrintResult("-7L Xor -7L", -7L Xor -7L) PrintResult("-7L Xor 28UL", -7L Xor 28UL) PrintResult("-7L Xor -9D", -7L Xor -9D) PrintResult("-7L Xor 10.0F", -7L Xor 10.0F) PrintResult("-7L Xor -11.0R", -7L Xor -11.0R) PrintResult("-7L Xor ""12""", -7L Xor "12") PrintResult("-7L Xor TypeCode.Double", -7L Xor TypeCode.Double) PrintResult("28UL Xor False", 28UL Xor False) PrintResult("28UL Xor True", 28UL Xor True) PrintResult("28UL Xor System.SByte.MinValue", 28UL Xor System.SByte.MinValue) PrintResult("28UL Xor System.Byte.MaxValue", 28UL Xor System.Byte.MaxValue) PrintResult("28UL Xor -3S", 28UL Xor -3S) PrintResult("28UL Xor 24US", 28UL Xor 24US) PrintResult("28UL Xor -5I", 28UL Xor -5I) PrintResult("28UL Xor 26UI", 28UL Xor 26UI) PrintResult("28UL Xor -7L", 28UL Xor -7L) PrintResult("28UL Xor 28UL", 28UL Xor 28UL) PrintResult("28UL Xor -9D", 28UL Xor -9D) PrintResult("28UL Xor 10.0F", 28UL Xor 10.0F) PrintResult("28UL Xor -11.0R", 28UL Xor -11.0R) PrintResult("28UL Xor ""12""", 28UL Xor "12") PrintResult("28UL Xor TypeCode.Double", 28UL Xor TypeCode.Double) PrintResult("-9D Xor False", -9D Xor False) PrintResult("-9D Xor True", -9D Xor True) PrintResult("-9D Xor System.SByte.MinValue", -9D Xor System.SByte.MinValue) PrintResult("-9D Xor System.Byte.MaxValue", -9D Xor System.Byte.MaxValue) PrintResult("-9D Xor -3S", -9D Xor -3S) PrintResult("-9D Xor 24US", -9D Xor 24US) PrintResult("-9D Xor -5I", -9D Xor -5I) PrintResult("-9D Xor 26UI", -9D Xor 26UI) PrintResult("-9D Xor -7L", -9D Xor -7L) PrintResult("-9D Xor 28UL", -9D Xor 28UL) PrintResult("-9D Xor -9D", -9D Xor -9D) PrintResult("-9D Xor 10.0F", -9D Xor 10.0F) PrintResult("-9D Xor -11.0R", -9D Xor -11.0R) PrintResult("-9D Xor ""12""", -9D Xor "12") PrintResult("-9D Xor TypeCode.Double", -9D Xor TypeCode.Double) PrintResult("10.0F Xor False", 10.0F Xor False) PrintResult("10.0F Xor True", 10.0F Xor True) PrintResult("10.0F Xor System.SByte.MinValue", 10.0F Xor System.SByte.MinValue) PrintResult("10.0F Xor System.Byte.MaxValue", 10.0F Xor System.Byte.MaxValue) PrintResult("10.0F Xor -3S", 10.0F Xor -3S) PrintResult("10.0F Xor 24US", 10.0F Xor 24US) PrintResult("10.0F Xor -5I", 10.0F Xor -5I) PrintResult("10.0F Xor 26UI", 10.0F Xor 26UI) PrintResult("10.0F Xor -7L", 10.0F Xor -7L) PrintResult("10.0F Xor 28UL", 10.0F Xor 28UL) PrintResult("10.0F Xor -9D", 10.0F Xor -9D) PrintResult("10.0F Xor 10.0F", 10.0F Xor 10.0F) PrintResult("10.0F Xor -11.0R", 10.0F Xor -11.0R) PrintResult("10.0F Xor ""12""", 10.0F Xor "12") PrintResult("10.0F Xor TypeCode.Double", 10.0F Xor TypeCode.Double) PrintResult("-11.0R Xor False", -11.0R Xor False) PrintResult("-11.0R Xor True", -11.0R Xor True) PrintResult("-11.0R Xor System.SByte.MinValue", -11.0R Xor System.SByte.MinValue) PrintResult("-11.0R Xor System.Byte.MaxValue", -11.0R Xor System.Byte.MaxValue) PrintResult("-11.0R Xor -3S", -11.0R Xor -3S) PrintResult("-11.0R Xor 24US", -11.0R Xor 24US) PrintResult("-11.0R Xor -5I", -11.0R Xor -5I) PrintResult("-11.0R Xor 26UI", -11.0R Xor 26UI) PrintResult("-11.0R Xor -7L", -11.0R Xor -7L) PrintResult("-11.0R Xor 28UL", -11.0R Xor 28UL) PrintResult("-11.0R Xor -9D", -11.0R Xor -9D) PrintResult("-11.0R Xor 10.0F", -11.0R Xor 10.0F) PrintResult("-11.0R Xor -11.0R", -11.0R Xor -11.0R) PrintResult("-11.0R Xor ""12""", -11.0R Xor "12") PrintResult("-11.0R Xor TypeCode.Double", -11.0R Xor TypeCode.Double) PrintResult("""12"" Xor False", "12" Xor False) PrintResult("""12"" Xor True", "12" Xor True) PrintResult("""12"" Xor System.SByte.MinValue", "12" Xor System.SByte.MinValue) PrintResult("""12"" Xor System.Byte.MaxValue", "12" Xor System.Byte.MaxValue) PrintResult("""12"" Xor -3S", "12" Xor -3S) PrintResult("""12"" Xor 24US", "12" Xor 24US) PrintResult("""12"" Xor -5I", "12" Xor -5I) PrintResult("""12"" Xor 26UI", "12" Xor 26UI) PrintResult("""12"" Xor -7L", "12" Xor -7L) PrintResult("""12"" Xor 28UL", "12" Xor 28UL) PrintResult("""12"" Xor -9D", "12" Xor -9D) PrintResult("""12"" Xor 10.0F", "12" Xor 10.0F) PrintResult("""12"" Xor -11.0R", "12" Xor -11.0R) PrintResult("""12"" Xor ""12""", "12" Xor "12") PrintResult("""12"" Xor TypeCode.Double", "12" Xor TypeCode.Double) PrintResult("TypeCode.Double Xor False", TypeCode.Double Xor False) PrintResult("TypeCode.Double Xor True", TypeCode.Double Xor True) PrintResult("TypeCode.Double Xor System.SByte.MinValue", TypeCode.Double Xor System.SByte.MinValue) PrintResult("TypeCode.Double Xor System.Byte.MaxValue", TypeCode.Double Xor System.Byte.MaxValue) PrintResult("TypeCode.Double Xor -3S", TypeCode.Double Xor -3S) PrintResult("TypeCode.Double Xor 24US", TypeCode.Double Xor 24US) PrintResult("TypeCode.Double Xor -5I", TypeCode.Double Xor -5I) PrintResult("TypeCode.Double Xor 26UI", TypeCode.Double Xor 26UI) PrintResult("TypeCode.Double Xor -7L", TypeCode.Double Xor -7L) PrintResult("TypeCode.Double Xor 28UL", TypeCode.Double Xor 28UL) PrintResult("TypeCode.Double Xor -9D", TypeCode.Double Xor -9D) PrintResult("TypeCode.Double Xor 10.0F", TypeCode.Double Xor 10.0F) PrintResult("TypeCode.Double Xor -11.0R", TypeCode.Double Xor -11.0R) PrintResult("TypeCode.Double Xor ""12""", TypeCode.Double Xor "12") PrintResult("TypeCode.Double Xor TypeCode.Double", TypeCode.Double Xor TypeCode.Double) PrintResult("False Or False", False Or False) PrintResult("False Or True", False Or True) PrintResult("False Or System.SByte.MinValue", False Or System.SByte.MinValue) PrintResult("False Or System.Byte.MaxValue", False Or System.Byte.MaxValue) PrintResult("False Or -3S", False Or -3S) PrintResult("False Or 24US", False Or 24US) PrintResult("False Or -5I", False Or -5I) PrintResult("False Or 26UI", False Or 26UI) PrintResult("False Or -7L", False Or -7L) PrintResult("False Or 28UL", False Or 28UL) PrintResult("False Or -9D", False Or -9D) PrintResult("False Or 10.0F", False Or 10.0F) PrintResult("False Or -11.0R", False Or -11.0R) PrintResult("False Or ""12""", False Or "12") PrintResult("False Or TypeCode.Double", False Or TypeCode.Double) PrintResult("True Or False", True Or False) PrintResult("True Or True", True Or True) PrintResult("True Or System.SByte.MinValue", True Or System.SByte.MinValue) PrintResult("True Or System.Byte.MaxValue", True Or System.Byte.MaxValue) PrintResult("True Or -3S", True Or -3S) PrintResult("True Or 24US", True Or 24US) PrintResult("True Or -5I", True Or -5I) PrintResult("True Or 26UI", True Or 26UI) PrintResult("True Or -7L", True Or -7L) PrintResult("True Or 28UL", True Or 28UL) PrintResult("True Or -9D", True Or -9D) PrintResult("True Or 10.0F", True Or 10.0F) PrintResult("True Or -11.0R", True Or -11.0R) PrintResult("True Or ""12""", True Or "12") PrintResult("True Or TypeCode.Double", True Or TypeCode.Double) PrintResult("System.SByte.MinValue Or False", System.SByte.MinValue Or False) PrintResult("System.SByte.MinValue Or True", System.SByte.MinValue Or True) PrintResult("System.SByte.MinValue Or System.SByte.MinValue", System.SByte.MinValue Or System.SByte.MinValue) PrintResult("System.SByte.MinValue Or System.Byte.MaxValue", System.SByte.MinValue Or System.Byte.MaxValue) PrintResult("System.SByte.MinValue Or -3S", System.SByte.MinValue Or -3S) PrintResult("System.SByte.MinValue Or 24US", System.SByte.MinValue Or 24US) PrintResult("System.SByte.MinValue Or -5I", System.SByte.MinValue Or -5I) PrintResult("System.SByte.MinValue Or 26UI", System.SByte.MinValue Or 26UI) PrintResult("System.SByte.MinValue Or -7L", System.SByte.MinValue Or -7L) PrintResult("System.SByte.MinValue Or 28UL", System.SByte.MinValue Or 28UL) PrintResult("System.SByte.MinValue Or -9D", System.SByte.MinValue Or -9D) PrintResult("System.SByte.MinValue Or 10.0F", System.SByte.MinValue Or 10.0F) PrintResult("System.SByte.MinValue Or -11.0R", System.SByte.MinValue Or -11.0R) PrintResult("System.SByte.MinValue Or ""12""", System.SByte.MinValue Or "12") PrintResult("System.SByte.MinValue Or TypeCode.Double", System.SByte.MinValue Or TypeCode.Double) PrintResult("System.Byte.MaxValue Or False", System.Byte.MaxValue Or False) PrintResult("System.Byte.MaxValue Or True", System.Byte.MaxValue Or True) PrintResult("System.Byte.MaxValue Or System.SByte.MinValue", System.Byte.MaxValue Or System.SByte.MinValue) PrintResult("System.Byte.MaxValue Or System.Byte.MaxValue", System.Byte.MaxValue Or System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Or -3S", System.Byte.MaxValue Or -3S) PrintResult("System.Byte.MaxValue Or 24US", System.Byte.MaxValue Or 24US) PrintResult("System.Byte.MaxValue Or -5I", System.Byte.MaxValue Or -5I) PrintResult("System.Byte.MaxValue Or 26UI", System.Byte.MaxValue Or 26UI) PrintResult("System.Byte.MaxValue Or -7L", System.Byte.MaxValue Or -7L) PrintResult("System.Byte.MaxValue Or 28UL", System.Byte.MaxValue Or 28UL) PrintResult("System.Byte.MaxValue Or -9D", System.Byte.MaxValue Or -9D) PrintResult("System.Byte.MaxValue Or 10.0F", System.Byte.MaxValue Or 10.0F) PrintResult("System.Byte.MaxValue Or -11.0R", System.Byte.MaxValue Or -11.0R) PrintResult("System.Byte.MaxValue Or ""12""", System.Byte.MaxValue Or "12") PrintResult("System.Byte.MaxValue Or TypeCode.Double", System.Byte.MaxValue Or TypeCode.Double) PrintResult("-3S Or False", -3S Or False) PrintResult("-3S Or True", -3S Or True) PrintResult("-3S Or System.SByte.MinValue", -3S Or System.SByte.MinValue) PrintResult("-3S Or System.Byte.MaxValue", -3S Or System.Byte.MaxValue) PrintResult("-3S Or -3S", -3S Or -3S) PrintResult("-3S Or 24US", -3S Or 24US) PrintResult("-3S Or -5I", -3S Or -5I) PrintResult("-3S Or 26UI", -3S Or 26UI) PrintResult("-3S Or -7L", -3S Or -7L) PrintResult("-3S Or 28UL", -3S Or 28UL) PrintResult("-3S Or -9D", -3S Or -9D) PrintResult("-3S Or 10.0F", -3S Or 10.0F) PrintResult("-3S Or -11.0R", -3S Or -11.0R) PrintResult("-3S Or ""12""", -3S Or "12") PrintResult("-3S Or TypeCode.Double", -3S Or TypeCode.Double) PrintResult("24US Or False", 24US Or False) PrintResult("24US Or True", 24US Or True) PrintResult("24US Or System.SByte.MinValue", 24US Or System.SByte.MinValue) PrintResult("24US Or System.Byte.MaxValue", 24US Or System.Byte.MaxValue) PrintResult("24US Or -3S", 24US Or -3S) PrintResult("24US Or 24US", 24US Or 24US) PrintResult("24US Or -5I", 24US Or -5I) PrintResult("24US Or 26UI", 24US Or 26UI) PrintResult("24US Or -7L", 24US Or -7L) PrintResult("24US Or 28UL", 24US Or 28UL) PrintResult("24US Or -9D", 24US Or -9D) PrintResult("24US Or 10.0F", 24US Or 10.0F) PrintResult("24US Or -11.0R", 24US Or -11.0R) PrintResult("24US Or ""12""", 24US Or "12") PrintResult("24US Or TypeCode.Double", 24US Or TypeCode.Double) PrintResult("-5I Or False", -5I Or False) PrintResult("-5I Or True", -5I Or True) PrintResult("-5I Or System.SByte.MinValue", -5I Or System.SByte.MinValue) PrintResult("-5I Or System.Byte.MaxValue", -5I Or System.Byte.MaxValue) PrintResult("-5I Or -3S", -5I Or -3S) PrintResult("-5I Or 24US", -5I Or 24US) PrintResult("-5I Or -5I", -5I Or -5I) PrintResult("-5I Or 26UI", -5I Or 26UI) PrintResult("-5I Or -7L", -5I Or -7L) PrintResult("-5I Or 28UL", -5I Or 28UL) PrintResult("-5I Or -9D", -5I Or -9D) PrintResult("-5I Or 10.0F", -5I Or 10.0F) PrintResult("-5I Or -11.0R", -5I Or -11.0R) PrintResult("-5I Or ""12""", -5I Or "12") PrintResult("-5I Or TypeCode.Double", -5I Or TypeCode.Double) PrintResult("26UI Or False", 26UI Or False) PrintResult("26UI Or True", 26UI Or True) PrintResult("26UI Or System.SByte.MinValue", 26UI Or System.SByte.MinValue) PrintResult("26UI Or System.Byte.MaxValue", 26UI Or System.Byte.MaxValue) PrintResult("26UI Or -3S", 26UI Or -3S) PrintResult("26UI Or 24US", 26UI Or 24US) PrintResult("26UI Or -5I", 26UI Or -5I) PrintResult("26UI Or 26UI", 26UI Or 26UI) PrintResult("26UI Or -7L", 26UI Or -7L) PrintResult("26UI Or 28UL", 26UI Or 28UL) PrintResult("26UI Or -9D", 26UI Or -9D) PrintResult("26UI Or 10.0F", 26UI Or 10.0F) PrintResult("26UI Or -11.0R", 26UI Or -11.0R) PrintResult("26UI Or ""12""", 26UI Or "12") PrintResult("26UI Or TypeCode.Double", 26UI Or TypeCode.Double) PrintResult("-7L Or False", -7L Or False) PrintResult("-7L Or True", -7L Or True) PrintResult("-7L Or System.SByte.MinValue", -7L Or System.SByte.MinValue) PrintResult("-7L Or System.Byte.MaxValue", -7L Or System.Byte.MaxValue) PrintResult("-7L Or -3S", -7L Or -3S) PrintResult("-7L Or 24US", -7L Or 24US) PrintResult("-7L Or -5I", -7L Or -5I) PrintResult("-7L Or 26UI", -7L Or 26UI) PrintResult("-7L Or -7L", -7L Or -7L) PrintResult("-7L Or 28UL", -7L Or 28UL) PrintResult("-7L Or -9D", -7L Or -9D) PrintResult("-7L Or 10.0F", -7L Or 10.0F) PrintResult("-7L Or -11.0R", -7L Or -11.0R) PrintResult("-7L Or ""12""", -7L Or "12") PrintResult("-7L Or TypeCode.Double", -7L Or TypeCode.Double) PrintResult("28UL Or False", 28UL Or False) PrintResult("28UL Or True", 28UL Or True) PrintResult("28UL Or System.SByte.MinValue", 28UL Or System.SByte.MinValue) PrintResult("28UL Or System.Byte.MaxValue", 28UL Or System.Byte.MaxValue) PrintResult("28UL Or -3S", 28UL Or -3S) PrintResult("28UL Or 24US", 28UL Or 24US) PrintResult("28UL Or -5I", 28UL Or -5I) PrintResult("28UL Or 26UI", 28UL Or 26UI) PrintResult("28UL Or -7L", 28UL Or -7L) PrintResult("28UL Or 28UL", 28UL Or 28UL) PrintResult("28UL Or -9D", 28UL Or -9D) PrintResult("28UL Or 10.0F", 28UL Or 10.0F) PrintResult("28UL Or -11.0R", 28UL Or -11.0R) PrintResult("28UL Or ""12""", 28UL Or "12") PrintResult("28UL Or TypeCode.Double", 28UL Or TypeCode.Double) PrintResult("-9D Or False", -9D Or False) PrintResult("-9D Or True", -9D Or True) PrintResult("-9D Or System.SByte.MinValue", -9D Or System.SByte.MinValue) PrintResult("-9D Or System.Byte.MaxValue", -9D Or System.Byte.MaxValue) PrintResult("-9D Or -3S", -9D Or -3S) PrintResult("-9D Or 24US", -9D Or 24US) PrintResult("-9D Or -5I", -9D Or -5I) PrintResult("-9D Or 26UI", -9D Or 26UI) PrintResult("-9D Or -7L", -9D Or -7L) PrintResult("-9D Or 28UL", -9D Or 28UL) PrintResult("-9D Or -9D", -9D Or -9D) PrintResult("-9D Or 10.0F", -9D Or 10.0F) PrintResult("-9D Or -11.0R", -9D Or -11.0R) PrintResult("-9D Or ""12""", -9D Or "12") PrintResult("-9D Or TypeCode.Double", -9D Or TypeCode.Double) PrintResult("10.0F Or False", 10.0F Or False) PrintResult("10.0F Or True", 10.0F Or True) PrintResult("10.0F Or System.SByte.MinValue", 10.0F Or System.SByte.MinValue) PrintResult("10.0F Or System.Byte.MaxValue", 10.0F Or System.Byte.MaxValue) PrintResult("10.0F Or -3S", 10.0F Or -3S) PrintResult("10.0F Or 24US", 10.0F Or 24US) PrintResult("10.0F Or -5I", 10.0F Or -5I) PrintResult("10.0F Or 26UI", 10.0F Or 26UI) PrintResult("10.0F Or -7L", 10.0F Or -7L) PrintResult("10.0F Or 28UL", 10.0F Or 28UL) PrintResult("10.0F Or -9D", 10.0F Or -9D) PrintResult("10.0F Or 10.0F", 10.0F Or 10.0F) PrintResult("10.0F Or -11.0R", 10.0F Or -11.0R) PrintResult("10.0F Or ""12""", 10.0F Or "12") PrintResult("10.0F Or TypeCode.Double", 10.0F Or TypeCode.Double) PrintResult("-11.0R Or False", -11.0R Or False) PrintResult("-11.0R Or True", -11.0R Or True) PrintResult("-11.0R Or System.SByte.MinValue", -11.0R Or System.SByte.MinValue) PrintResult("-11.0R Or System.Byte.MaxValue", -11.0R Or System.Byte.MaxValue) PrintResult("-11.0R Or -3S", -11.0R Or -3S) PrintResult("-11.0R Or 24US", -11.0R Or 24US) PrintResult("-11.0R Or -5I", -11.0R Or -5I) PrintResult("-11.0R Or 26UI", -11.0R Or 26UI) PrintResult("-11.0R Or -7L", -11.0R Or -7L) PrintResult("-11.0R Or 28UL", -11.0R Or 28UL) PrintResult("-11.0R Or -9D", -11.0R Or -9D) PrintResult("-11.0R Or 10.0F", -11.0R Or 10.0F) PrintResult("-11.0R Or -11.0R", -11.0R Or -11.0R) PrintResult("-11.0R Or ""12""", -11.0R Or "12") PrintResult("-11.0R Or TypeCode.Double", -11.0R Or TypeCode.Double) PrintResult("""12"" Or False", "12" Or False) PrintResult("""12"" Or True", "12" Or True) PrintResult("""12"" Or System.SByte.MinValue", "12" Or System.SByte.MinValue) PrintResult("""12"" Or System.Byte.MaxValue", "12" Or System.Byte.MaxValue) PrintResult("""12"" Or -3S", "12" Or -3S) PrintResult("""12"" Or 24US", "12" Or 24US) PrintResult("""12"" Or -5I", "12" Or -5I) PrintResult("""12"" Or 26UI", "12" Or 26UI) PrintResult("""12"" Or -7L", "12" Or -7L) PrintResult("""12"" Or 28UL", "12" Or 28UL) PrintResult("""12"" Or -9D", "12" Or -9D) PrintResult("""12"" Or 10.0F", "12" Or 10.0F) PrintResult("""12"" Or -11.0R", "12" Or -11.0R) PrintResult("""12"" Or ""12""", "12" Or "12") PrintResult("""12"" Or TypeCode.Double", "12" Or TypeCode.Double) PrintResult("TypeCode.Double Or False", TypeCode.Double Or False) PrintResult("TypeCode.Double Or True", TypeCode.Double Or True) PrintResult("TypeCode.Double Or System.SByte.MinValue", TypeCode.Double Or System.SByte.MinValue) PrintResult("TypeCode.Double Or System.Byte.MaxValue", TypeCode.Double Or System.Byte.MaxValue) PrintResult("TypeCode.Double Or -3S", TypeCode.Double Or -3S) PrintResult("TypeCode.Double Or 24US", TypeCode.Double Or 24US) PrintResult("TypeCode.Double Or -5I", TypeCode.Double Or -5I) PrintResult("TypeCode.Double Or 26UI", TypeCode.Double Or 26UI) PrintResult("TypeCode.Double Or -7L", TypeCode.Double Or -7L) PrintResult("TypeCode.Double Or 28UL", TypeCode.Double Or 28UL) PrintResult("TypeCode.Double Or -9D", TypeCode.Double Or -9D) PrintResult("TypeCode.Double Or 10.0F", TypeCode.Double Or 10.0F) PrintResult("TypeCode.Double Or -11.0R", TypeCode.Double Or -11.0R) PrintResult("TypeCode.Double Or ""12""", TypeCode.Double Or "12") PrintResult("TypeCode.Double Or TypeCode.Double", TypeCode.Double Or TypeCode.Double) PrintResult("False And False", False And False) PrintResult("False And True", False And True) PrintResult("False And System.SByte.MinValue", False And System.SByte.MinValue) PrintResult("False And System.Byte.MaxValue", False And System.Byte.MaxValue) PrintResult("False And -3S", False And -3S) PrintResult("False And 24US", False And 24US) PrintResult("False And -5I", False And -5I) PrintResult("False And 26UI", False And 26UI) PrintResult("False And -7L", False And -7L) PrintResult("False And 28UL", False And 28UL) PrintResult("False And -9D", False And -9D) PrintResult("False And 10.0F", False And 10.0F) PrintResult("False And -11.0R", False And -11.0R) PrintResult("False And ""12""", False And "12") PrintResult("False And TypeCode.Double", False And TypeCode.Double) PrintResult("True And False", True And False) PrintResult("True And True", True And True) PrintResult("True And System.SByte.MinValue", True And System.SByte.MinValue) PrintResult("True And System.Byte.MaxValue", True And System.Byte.MaxValue) PrintResult("True And -3S", True And -3S) PrintResult("True And 24US", True And 24US) PrintResult("True And -5I", True And -5I) PrintResult("True And 26UI", True And 26UI) PrintResult("True And -7L", True And -7L) PrintResult("True And 28UL", True And 28UL) PrintResult("True And -9D", True And -9D) PrintResult("True And 10.0F", True And 10.0F) PrintResult("True And -11.0R", True And -11.0R) PrintResult("True And ""12""", True And "12") PrintResult("True And TypeCode.Double", True And TypeCode.Double) PrintResult("System.SByte.MinValue And False", System.SByte.MinValue And False) PrintResult("System.SByte.MinValue And True", System.SByte.MinValue And True) PrintResult("System.SByte.MinValue And System.SByte.MinValue", System.SByte.MinValue And System.SByte.MinValue) PrintResult("System.SByte.MinValue And System.Byte.MaxValue", System.SByte.MinValue And System.Byte.MaxValue) PrintResult("System.SByte.MinValue And -3S", System.SByte.MinValue And -3S) PrintResult("System.SByte.MinValue And 24US", System.SByte.MinValue And 24US) PrintResult("System.SByte.MinValue And -5I", System.SByte.MinValue And -5I) PrintResult("System.SByte.MinValue And 26UI", System.SByte.MinValue And 26UI) PrintResult("System.SByte.MinValue And -7L", System.SByte.MinValue And -7L) PrintResult("System.SByte.MinValue And 28UL", System.SByte.MinValue And 28UL) PrintResult("System.SByte.MinValue And -9D", System.SByte.MinValue And -9D) PrintResult("System.SByte.MinValue And 10.0F", System.SByte.MinValue And 10.0F) PrintResult("System.SByte.MinValue And -11.0R", System.SByte.MinValue And -11.0R) PrintResult("System.SByte.MinValue And ""12""", System.SByte.MinValue And "12") PrintResult("System.SByte.MinValue And TypeCode.Double", System.SByte.MinValue And TypeCode.Double) PrintResult("System.Byte.MaxValue And False", System.Byte.MaxValue And False) PrintResult("System.Byte.MaxValue And True", System.Byte.MaxValue And True) PrintResult("System.Byte.MaxValue And System.SByte.MinValue", System.Byte.MaxValue And System.SByte.MinValue) PrintResult("System.Byte.MaxValue And System.Byte.MaxValue", System.Byte.MaxValue And System.Byte.MaxValue) PrintResult("System.Byte.MaxValue And -3S", System.Byte.MaxValue And -3S) PrintResult("System.Byte.MaxValue And 24US", System.Byte.MaxValue And 24US) PrintResult("System.Byte.MaxValue And -5I", System.Byte.MaxValue And -5I) PrintResult("System.Byte.MaxValue And 26UI", System.Byte.MaxValue And 26UI) PrintResult("System.Byte.MaxValue And -7L", System.Byte.MaxValue And -7L) PrintResult("System.Byte.MaxValue And 28UL", System.Byte.MaxValue And 28UL) PrintResult("System.Byte.MaxValue And -9D", System.Byte.MaxValue And -9D) PrintResult("System.Byte.MaxValue And 10.0F", System.Byte.MaxValue And 10.0F) PrintResult("System.Byte.MaxValue And -11.0R", System.Byte.MaxValue And -11.0R) PrintResult("System.Byte.MaxValue And ""12""", System.Byte.MaxValue And "12") PrintResult("System.Byte.MaxValue And TypeCode.Double", System.Byte.MaxValue And TypeCode.Double) PrintResult("-3S And False", -3S And False) PrintResult("-3S And True", -3S And True) PrintResult("-3S And System.SByte.MinValue", -3S And System.SByte.MinValue) PrintResult("-3S And System.Byte.MaxValue", -3S And System.Byte.MaxValue) PrintResult("-3S And -3S", -3S And -3S) PrintResult("-3S And 24US", -3S And 24US) PrintResult("-3S And -5I", -3S And -5I) PrintResult("-3S And 26UI", -3S And 26UI) PrintResult("-3S And -7L", -3S And -7L) PrintResult("-3S And 28UL", -3S And 28UL) PrintResult("-3S And -9D", -3S And -9D) PrintResult("-3S And 10.0F", -3S And 10.0F) PrintResult("-3S And -11.0R", -3S And -11.0R) PrintResult("-3S And ""12""", -3S And "12") PrintResult("-3S And TypeCode.Double", -3S And TypeCode.Double) PrintResult("24US And False", 24US And False) PrintResult("24US And True", 24US And True) PrintResult("24US And System.SByte.MinValue", 24US And System.SByte.MinValue) PrintResult("24US And System.Byte.MaxValue", 24US And System.Byte.MaxValue) PrintResult("24US And -3S", 24US And -3S) PrintResult("24US And 24US", 24US And 24US) PrintResult("24US And -5I", 24US And -5I) PrintResult("24US And 26UI", 24US And 26UI) PrintResult("24US And -7L", 24US And -7L) PrintResult("24US And 28UL", 24US And 28UL) PrintResult("24US And -9D", 24US And -9D) PrintResult("24US And 10.0F", 24US And 10.0F) PrintResult("24US And -11.0R", 24US And -11.0R) PrintResult("24US And ""12""", 24US And "12") PrintResult("24US And TypeCode.Double", 24US And TypeCode.Double) PrintResult("-5I And False", -5I And False) PrintResult("-5I And True", -5I And True) PrintResult("-5I And System.SByte.MinValue", -5I And System.SByte.MinValue) PrintResult("-5I And System.Byte.MaxValue", -5I And System.Byte.MaxValue) PrintResult("-5I And -3S", -5I And -3S) PrintResult("-5I And 24US", -5I And 24US) PrintResult("-5I And -5I", -5I And -5I) PrintResult("-5I And 26UI", -5I And 26UI) PrintResult("-5I And -7L", -5I And -7L) PrintResult("-5I And 28UL", -5I And 28UL) PrintResult("-5I And -9D", -5I And -9D) PrintResult("-5I And 10.0F", -5I And 10.0F) PrintResult("-5I And -11.0R", -5I And -11.0R) PrintResult("-5I And ""12""", -5I And "12") PrintResult("-5I And TypeCode.Double", -5I And TypeCode.Double) PrintResult("26UI And False", 26UI And False) PrintResult("26UI And True", 26UI And True) PrintResult("26UI And System.SByte.MinValue", 26UI And System.SByte.MinValue) PrintResult("26UI And System.Byte.MaxValue", 26UI And System.Byte.MaxValue) PrintResult("26UI And -3S", 26UI And -3S) PrintResult("26UI And 24US", 26UI And 24US) PrintResult("26UI And -5I", 26UI And -5I) PrintResult("26UI And 26UI", 26UI And 26UI) PrintResult("26UI And -7L", 26UI And -7L) PrintResult("26UI And 28UL", 26UI And 28UL) PrintResult("26UI And -9D", 26UI And -9D) PrintResult("26UI And 10.0F", 26UI And 10.0F) PrintResult("26UI And -11.0R", 26UI And -11.0R) PrintResult("26UI And ""12""", 26UI And "12") PrintResult("26UI And TypeCode.Double", 26UI And TypeCode.Double) PrintResult("-7L And False", -7L And False) PrintResult("-7L And True", -7L And True) PrintResult("-7L And System.SByte.MinValue", -7L And System.SByte.MinValue) PrintResult("-7L And System.Byte.MaxValue", -7L And System.Byte.MaxValue) PrintResult("-7L And -3S", -7L And -3S) PrintResult("-7L And 24US", -7L And 24US) PrintResult("-7L And -5I", -7L And -5I) PrintResult("-7L And 26UI", -7L And 26UI) PrintResult("-7L And -7L", -7L And -7L) PrintResult("-7L And 28UL", -7L And 28UL) PrintResult("-7L And -9D", -7L And -9D) PrintResult("-7L And 10.0F", -7L And 10.0F) PrintResult("-7L And -11.0R", -7L And -11.0R) PrintResult("-7L And ""12""", -7L And "12") PrintResult("-7L And TypeCode.Double", -7L And TypeCode.Double) PrintResult("28UL And False", 28UL And False) PrintResult("28UL And True", 28UL And True) PrintResult("28UL And System.SByte.MinValue", 28UL And System.SByte.MinValue) PrintResult("28UL And System.Byte.MaxValue", 28UL And System.Byte.MaxValue) PrintResult("28UL And -3S", 28UL And -3S) PrintResult("28UL And 24US", 28UL And 24US) PrintResult("28UL And -5I", 28UL And -5I) PrintResult("28UL And 26UI", 28UL And 26UI) PrintResult("28UL And -7L", 28UL And -7L) PrintResult("28UL And 28UL", 28UL And 28UL) PrintResult("28UL And -9D", 28UL And -9D) PrintResult("28UL And 10.0F", 28UL And 10.0F) PrintResult("28UL And -11.0R", 28UL And -11.0R) PrintResult("28UL And ""12""", 28UL And "12") PrintResult("28UL And TypeCode.Double", 28UL And TypeCode.Double) PrintResult("-9D And False", -9D And False) PrintResult("-9D And True", -9D And True) PrintResult("-9D And System.SByte.MinValue", -9D And System.SByte.MinValue) PrintResult("-9D And System.Byte.MaxValue", -9D And System.Byte.MaxValue) PrintResult("-9D And -3S", -9D And -3S) PrintResult("-9D And 24US", -9D And 24US) PrintResult("-9D And -5I", -9D And -5I) PrintResult("-9D And 26UI", -9D And 26UI) PrintResult("-9D And -7L", -9D And -7L) PrintResult("-9D And 28UL", -9D And 28UL) PrintResult("-9D And -9D", -9D And -9D) PrintResult("-9D And 10.0F", -9D And 10.0F) PrintResult("-9D And -11.0R", -9D And -11.0R) PrintResult("-9D And ""12""", -9D And "12") PrintResult("-9D And TypeCode.Double", -9D And TypeCode.Double) PrintResult("10.0F And False", 10.0F And False) PrintResult("10.0F And True", 10.0F And True) PrintResult("10.0F And System.SByte.MinValue", 10.0F And System.SByte.MinValue) PrintResult("10.0F And System.Byte.MaxValue", 10.0F And System.Byte.MaxValue) PrintResult("10.0F And -3S", 10.0F And -3S) PrintResult("10.0F And 24US", 10.0F And 24US) PrintResult("10.0F And -5I", 10.0F And -5I) PrintResult("10.0F And 26UI", 10.0F And 26UI) PrintResult("10.0F And -7L", 10.0F And -7L) PrintResult("10.0F And 28UL", 10.0F And 28UL) PrintResult("10.0F And -9D", 10.0F And -9D) PrintResult("10.0F And 10.0F", 10.0F And 10.0F) PrintResult("10.0F And -11.0R", 10.0F And -11.0R) PrintResult("10.0F And ""12""", 10.0F And "12") PrintResult("10.0F And TypeCode.Double", 10.0F And TypeCode.Double) PrintResult("-11.0R And False", -11.0R And False) PrintResult("-11.0R And True", -11.0R And True) PrintResult("-11.0R And System.SByte.MinValue", -11.0R And System.SByte.MinValue) PrintResult("-11.0R And System.Byte.MaxValue", -11.0R And System.Byte.MaxValue) PrintResult("-11.0R And -3S", -11.0R And -3S) PrintResult("-11.0R And 24US", -11.0R And 24US) PrintResult("-11.0R And -5I", -11.0R And -5I) PrintResult("-11.0R And 26UI", -11.0R And 26UI) PrintResult("-11.0R And -7L", -11.0R And -7L) PrintResult("-11.0R And 28UL", -11.0R And 28UL) PrintResult("-11.0R And -9D", -11.0R And -9D) PrintResult("-11.0R And 10.0F", -11.0R And 10.0F) PrintResult("-11.0R And -11.0R", -11.0R And -11.0R) PrintResult("-11.0R And ""12""", -11.0R And "12") PrintResult("-11.0R And TypeCode.Double", -11.0R And TypeCode.Double) PrintResult("""12"" And False", "12" And False) PrintResult("""12"" And True", "12" And True) PrintResult("""12"" And System.SByte.MinValue", "12" And System.SByte.MinValue) PrintResult("""12"" And System.Byte.MaxValue", "12" And System.Byte.MaxValue) PrintResult("""12"" And -3S", "12" And -3S) PrintResult("""12"" And 24US", "12" And 24US) PrintResult("""12"" And -5I", "12" And -5I) PrintResult("""12"" And 26UI", "12" And 26UI) PrintResult("""12"" And -7L", "12" And -7L) PrintResult("""12"" And 28UL", "12" And 28UL) PrintResult("""12"" And -9D", "12" And -9D) PrintResult("""12"" And 10.0F", "12" And 10.0F) PrintResult("""12"" And -11.0R", "12" And -11.0R) PrintResult("""12"" And ""12""", "12" And "12") PrintResult("""12"" And TypeCode.Double", "12" And TypeCode.Double) PrintResult("TypeCode.Double And False", TypeCode.Double And False) PrintResult("TypeCode.Double And True", TypeCode.Double And True) PrintResult("TypeCode.Double And System.SByte.MinValue", TypeCode.Double And System.SByte.MinValue) PrintResult("TypeCode.Double And System.Byte.MaxValue", TypeCode.Double And System.Byte.MaxValue) PrintResult("TypeCode.Double And -3S", TypeCode.Double And -3S) PrintResult("TypeCode.Double And 24US", TypeCode.Double And 24US) PrintResult("TypeCode.Double And -5I", TypeCode.Double And -5I) PrintResult("TypeCode.Double And 26UI", TypeCode.Double And 26UI) PrintResult("TypeCode.Double And -7L", TypeCode.Double And -7L) PrintResult("TypeCode.Double And 28UL", TypeCode.Double And 28UL) PrintResult("TypeCode.Double And -9D", TypeCode.Double And -9D) PrintResult("TypeCode.Double And 10.0F", TypeCode.Double And 10.0F) PrintResult("TypeCode.Double And -11.0R", TypeCode.Double And -11.0R) PrintResult("TypeCode.Double And ""12""", TypeCode.Double And "12") PrintResult("TypeCode.Double And TypeCode.Double", TypeCode.Double And TypeCode.Double) 'PrintResult("#8:30:00 AM# + ""12""", #8:30:00 AM# + "12") 'PrintResult("#8:30:00 AM# + #8:30:00 AM#", #8:30:00 AM# + #8:30:00 AM#) PrintResult("""c""c + ""12""", "c"c + "12") PrintResult("""c""c + ""c""c", "c"c + "c"c) 'PrintResult("""12"" + #8:30:00 AM#", "12" + #8:30:00 AM#) PrintResult("""12"" + ""c""c", "12" + "c"c) 'PrintResult("#8:30:00 AM# & False", #8:30:00 AM# & False) 'PrintResult("#8:30:00 AM# & True", #8:30:00 AM# & True) 'PrintResult("#8:30:00 AM# & System.SByte.MinValue", #8:30:00 AM# & System.SByte.MinValue) 'PrintResult("#8:30:00 AM# & System.Byte.MaxValue", #8:30:00 AM# & System.Byte.MaxValue) 'PrintResult("#8:30:00 AM# & -3S", #8:30:00 AM# & -3S) 'PrintResult("#8:30:00 AM# & 24US", #8:30:00 AM# & 24US) 'PrintResult("#8:30:00 AM# & -5I", #8:30:00 AM# & -5I) 'PrintResult("#8:30:00 AM# & 26UI", #8:30:00 AM# & 26UI) 'PrintResult("#8:30:00 AM# & -7L", #8:30:00 AM# & -7L) 'PrintResult("#8:30:00 AM# & 28UL", #8:30:00 AM# & 28UL) 'PrintResult("#8:30:00 AM# & -9D", #8:30:00 AM# & -9D) 'PrintResult("#8:30:00 AM# & 10.0F", #8:30:00 AM# & 10.0F) 'PrintResult("#8:30:00 AM# & -11.0R", #8:30:00 AM# & -11.0R) 'PrintResult("#8:30:00 AM# & ""12""", #8:30:00 AM# & "12") 'PrintResult("#8:30:00 AM# & TypeCode.Double", #8:30:00 AM# & TypeCode.Double) 'PrintResult("#8:30:00 AM# & #8:30:00 AM#", #8:30:00 AM# & #8:30:00 AM#) 'PrintResult("#8:30:00 AM# & ""c""c", #8:30:00 AM# & "c"c) PrintResult("""c""c & False", "c"c & False) PrintResult("""c""c & True", "c"c & True) PrintResult("""c""c & System.SByte.MinValue", "c"c & System.SByte.MinValue) PrintResult("""c""c & System.Byte.MaxValue", "c"c & System.Byte.MaxValue) PrintResult("""c""c & -3S", "c"c & -3S) PrintResult("""c""c & 24US", "c"c & 24US) PrintResult("""c""c & -5I", "c"c & -5I) PrintResult("""c""c & 26UI", "c"c & 26UI) PrintResult("""c""c & -7L", "c"c & -7L) PrintResult("""c""c & 28UL", "c"c & 28UL) PrintResult("""c""c & -9D", "c"c & -9D) PrintResult("""c""c & 10.0F", "c"c & 10.0F) PrintResult("""c""c & -11.0R", "c"c & -11.0R) PrintResult("""c""c & ""12""", "c"c & "12") PrintResult("""c""c & TypeCode.Double", "c"c & TypeCode.Double) 'PrintResult("""c""c & #8:30:00 AM#", "c"c & #8:30:00 AM#) PrintResult("""c""c & ""c""c", "c"c & "c"c) 'PrintResult("False & #8:30:00 AM#", False & #8:30:00 AM#) PrintResult("False & ""c""c", False & "c"c) 'PrintResult("True & #8:30:00 AM#", True & #8:30:00 AM#) PrintResult("True & ""c""c", True & "c"c) 'PrintResult("System.SByte.MinValue & #8:30:00 AM#", System.SByte.MinValue & #8:30:00 AM#) PrintResult("System.SByte.MinValue & ""c""c", System.SByte.MinValue & "c"c) 'PrintResult("System.Byte.MaxValue & #8:30:00 AM#", System.Byte.MaxValue & #8:30:00 AM#) PrintResult("System.Byte.MaxValue & ""c""c", System.Byte.MaxValue & "c"c) 'PrintResult("-3S & #8:30:00 AM#", -3S & #8:30:00 AM#) PrintResult("-3S & ""c""c", -3S & "c"c) 'PrintResult("24US & #8:30:00 AM#", 24US & #8:30:00 AM#) PrintResult("24US & ""c""c", 24US & "c"c) 'PrintResult("-5I & #8:30:00 AM#", -5I & #8:30:00 AM#) PrintResult("-5I & ""c""c", -5I & "c"c) 'PrintResult("26UI & #8:30:00 AM#", 26UI & #8:30:00 AM#) PrintResult("26UI & ""c""c", 26UI & "c"c) 'PrintResult("-7L & #8:30:00 AM#", -7L & #8:30:00 AM#) PrintResult("-7L & ""c""c", -7L & "c"c) 'PrintResult("28UL & #8:30:00 AM#", 28UL & #8:30:00 AM#) PrintResult("28UL & ""c""c", 28UL & "c"c) 'PrintResult("-9D & #8:30:00 AM#", -9D & #8:30:00 AM#) PrintResult("-9D & ""c""c", -9D & "c"c) 'PrintResult("10.0F & #8:30:00 AM#", 10.0F & #8:30:00 AM#) PrintResult("10.0F & ""c""c", 10.0F & "c"c) 'PrintResult("-11.0R & #8:30:00 AM#", -11.0R & #8:30:00 AM#) PrintResult("-11.0R & ""c""c", -11.0R & "c"c) 'PrintResult("""12"" & #8:30:00 AM#", "12" & #8:30:00 AM#) PrintResult("""12"" & ""c""c", "12" & "c"c) 'PrintResult("TypeCode.Double & #8:30:00 AM#", TypeCode.Double & #8:30:00 AM#) PrintResult("TypeCode.Double & ""c""c", TypeCode.Double & "c"c) PrintResult("#8:30:00 AM# Like False", #8:30:00 AM# Like False) PrintResult("#8:30:00 AM# Like True", #8:30:00 AM# Like True) PrintResult("#8:30:00 AM# Like System.SByte.MinValue", #8:30:00 AM# Like System.SByte.MinValue) PrintResult("#8:30:00 AM# Like System.Byte.MaxValue", #8:30:00 AM# Like System.Byte.MaxValue) PrintResult("#8:30:00 AM# Like -3S", #8:30:00 AM# Like -3S) PrintResult("#8:30:00 AM# Like 24US", #8:30:00 AM# Like 24US) PrintResult("#8:30:00 AM# Like -5I", #8:30:00 AM# Like -5I) PrintResult("#8:30:00 AM# Like 26UI", #8:30:00 AM# Like 26UI) PrintResult("#8:30:00 AM# Like -7L", #8:30:00 AM# Like -7L) PrintResult("#8:30:00 AM# Like 28UL", #8:30:00 AM# Like 28UL) PrintResult("#8:30:00 AM# Like -9D", #8:30:00 AM# Like -9D) PrintResult("#8:30:00 AM# Like 10.0F", #8:30:00 AM# Like 10.0F) PrintResult("#8:30:00 AM# Like -11.0R", #8:30:00 AM# Like -11.0R) PrintResult("#8:30:00 AM# Like ""12""", #8:30:00 AM# Like "12") PrintResult("#8:30:00 AM# Like TypeCode.Double", #8:30:00 AM# Like TypeCode.Double) PrintResult("#8:30:00 AM# Like #8:30:00 AM#", #8:30:00 AM# Like #8:30:00 AM#) PrintResult("#8:30:00 AM# Like ""c""c", #8:30:00 AM# Like "c"c) PrintResult("""c""c Like False", "c"c Like False) PrintResult("""c""c Like True", "c"c Like True) PrintResult("""c""c Like System.SByte.MinValue", "c"c Like System.SByte.MinValue) PrintResult("""c""c Like System.Byte.MaxValue", "c"c Like System.Byte.MaxValue) PrintResult("""c""c Like -3S", "c"c Like -3S) PrintResult("""c""c Like 24US", "c"c Like 24US) PrintResult("""c""c Like -5I", "c"c Like -5I) PrintResult("""c""c Like 26UI", "c"c Like 26UI) PrintResult("""c""c Like -7L", "c"c Like -7L) PrintResult("""c""c Like 28UL", "c"c Like 28UL) PrintResult("""c""c Like -9D", "c"c Like -9D) PrintResult("""c""c Like 10.0F", "c"c Like 10.0F) PrintResult("""c""c Like -11.0R", "c"c Like -11.0R) PrintResult("""c""c Like ""12""", "c"c Like "12") PrintResult("""c""c Like TypeCode.Double", "c"c Like TypeCode.Double) PrintResult("""c""c Like #8:30:00 AM#", "c"c Like #8:30:00 AM#) PrintResult("""c""c Like ""c""c", "c"c Like "c"c) PrintResult("False Like #8:30:00 AM#", False Like #8:30:00 AM#) PrintResult("False Like ""c""c", False Like "c"c) PrintResult("True Like #8:30:00 AM#", True Like #8:30:00 AM#) PrintResult("True Like ""c""c", True Like "c"c) PrintResult("System.SByte.MinValue Like #8:30:00 AM#", System.SByte.MinValue Like #8:30:00 AM#) PrintResult("System.SByte.MinValue Like ""c""c", System.SByte.MinValue Like "c"c) PrintResult("System.Byte.MaxValue Like #8:30:00 AM#", System.Byte.MaxValue Like #8:30:00 AM#) PrintResult("System.Byte.MaxValue Like ""c""c", System.Byte.MaxValue Like "c"c) PrintResult("-3S Like #8:30:00 AM#", -3S Like #8:30:00 AM#) PrintResult("-3S Like ""c""c", -3S Like "c"c) PrintResult("24US Like #8:30:00 AM#", 24US Like #8:30:00 AM#) PrintResult("24US Like ""c""c", 24US Like "c"c) PrintResult("-5I Like #8:30:00 AM#", -5I Like #8:30:00 AM#) PrintResult("-5I Like ""c""c", -5I Like "c"c) PrintResult("26UI Like #8:30:00 AM#", 26UI Like #8:30:00 AM#) PrintResult("26UI Like ""c""c", 26UI Like "c"c) PrintResult("-7L Like #8:30:00 AM#", -7L Like #8:30:00 AM#) PrintResult("-7L Like ""c""c", -7L Like "c"c) PrintResult("28UL Like #8:30:00 AM#", 28UL Like #8:30:00 AM#) PrintResult("28UL Like ""c""c", 28UL Like "c"c) PrintResult("-9D Like #8:30:00 AM#", -9D Like #8:30:00 AM#) PrintResult("-9D Like ""c""c", -9D Like "c"c) PrintResult("10.0F Like #8:30:00 AM#", 10.0F Like #8:30:00 AM#) PrintResult("10.0F Like ""c""c", 10.0F Like "c"c) PrintResult("-11.0R Like #8:30:00 AM#", -11.0R Like #8:30:00 AM#) PrintResult("-11.0R Like ""c""c", -11.0R Like "c"c) PrintResult("""12"" Like #8:30:00 AM#", "12" Like #8:30:00 AM#) PrintResult("""12"" Like ""c""c", "12" Like "c"c) PrintResult("TypeCode.Double Like #8:30:00 AM#", TypeCode.Double Like #8:30:00 AM#) PrintResult("TypeCode.Double Like ""c""c", TypeCode.Double Like "c"c) PrintResult("#8:30:00 AM# = #8:30:00 AM#", #8:30:00 AM# = #8:30:00 AM#) PrintResult("""c""c = ""12""", "c"c = "12") PrintResult("""c""c = ""c""c", "c"c = "c"c) PrintResult("""12"" = ""c""c", "12" = "c"c) PrintResult("#8:30:00 AM# <> #8:30:00 AM#", #8:30:00 AM# <> #8:30:00 AM#) PrintResult("""c""c <> ""12""", "c"c <> "12") PrintResult("""c""c <> ""c""c", "c"c <> "c"c) PrintResult("""12"" <> ""c""c", "12" <> "c"c) PrintResult("#8:30:00 AM# <= #8:30:00 AM#", #8:30:00 AM# <= #8:30:00 AM#) PrintResult("""c""c <= ""12""", "c"c <= "12") PrintResult("""c""c <= ""c""c", "c"c <= "c"c) PrintResult("""12"" <= ""c""c", "12" <= "c"c) PrintResult("#8:30:00 AM# >= #8:30:00 AM#", #8:30:00 AM# >= #8:30:00 AM#) PrintResult("""c""c >= ""12""", "c"c >= "12") PrintResult("""c""c >= ""c""c", "c"c >= "c"c) PrintResult("""12"" >= ""c""c", "12" >= "c"c) PrintResult("#8:30:00 AM# < #8:30:00 AM#", #8:30:00 AM# < #8:30:00 AM#) PrintResult("""c""c < ""12""", "c"c < "12") PrintResult("""c""c < ""c""c", "c"c < "c"c) PrintResult("""12"" < ""c""c", "12" < "c"c) PrintResult("#8:30:00 AM# > #8:30:00 AM#", #8:30:00 AM# > #8:30:00 AM#) PrintResult("""c""c > ""12""", "c"c > "12") PrintResult("""c""c > ""c""c", "c"c > "c"c) PrintResult("""12"" > ""c""c", "12" > "c"c) PrintResult("System.Byte.MaxValue - 24US", System.Byte.MaxValue - 24US) PrintResult("System.Byte.MaxValue - 26UI", System.Byte.MaxValue - 26UI) PrintResult("System.Byte.MaxValue - 28UL", System.Byte.MaxValue - 28UL) PrintResult("44US - 26UI", 44US - 26UI) PrintResult("44US - 28UL", 44US - 28UL) PrintResult("46UI - 28UL", 46UI - 28UL) PrintResult("System.Byte.MaxValue * (System.Byte.MaxValue \ System.Byte.MaxValue)", System.Byte.MaxValue * (System.Byte.MaxValue \ System.Byte.MaxValue)) PrintResult("#8:31:00 AM# = ""8:30:00 AM""", #8:31:00 AM# = "8:30:00 AM") PrintResult("""8:30:00 AM"" = #8:31:00 AM#", "8:30:00 AM" = #8:31:00 AM#) PrintResult("#8:31:00 AM# <> ""8:30:00 AM""", #8:31:00 AM# <> "8:30:00 AM") PrintResult("""8:30:00 AM"" <> #8:31:00 AM#", "8:30:00 AM" <> #8:31:00 AM#) PrintResult("#8:31:00 AM# <= ""8:30:00 AM""", #8:31:00 AM# <= "8:30:00 AM") PrintResult("""8:30:00 AM"" <= #8:31:00 AM#", "8:30:00 AM" <= #8:31:00 AM#) PrintResult("#8:31:00 AM# >= ""8:30:00 AM""", #8:31:00 AM# >= "8:30:00 AM") PrintResult("""8:30:00 AM"" >= #8:31:00 AM#", "8:30:00 AM" >= #8:31:00 AM#) PrintResult("#8:31:00 AM# < ""8:30:00 AM""", #8:31:00 AM# < "8:30:00 AM") PrintResult("""8:30:00 AM"" < #8:31:00 AM#", "8:30:00 AM" < #8:31:00 AM#) PrintResult("#8:31:00 AM# > ""8:30:00 AM""", #8:31:00 AM# > "8:30:00 AM") PrintResult("""8:30:00 AM"" > #8:31:00 AM#", "8:30:00 AM" > #8:31:00 AM#) PrintResult("-5I + Nothing", -5I + Nothing) PrintResult("""12"" + Nothing", "12" + Nothing) PrintResult("""12"" + DBNull.Value", "12" + DBNull.Value) PrintResult("Nothing + Nothing", Nothing + Nothing) PrintResult("Nothing + -5I", Nothing + -5I) PrintResult("Nothing + ""12""", Nothing + "12") PrintResult("DBNull.Value + ""12""", DBNull.Value + "12") PrintResult("-5I - Nothing", -5I - Nothing) PrintResult("""12"" - Nothing", "12" - Nothing) PrintResult("Nothing - Nothing", Nothing - Nothing) PrintResult("Nothing - -5I", Nothing - -5I) PrintResult("Nothing - ""12""", Nothing - "12") PrintResult("-5I * Nothing", -5I * Nothing) PrintResult("""12"" * Nothing", "12" * Nothing) PrintResult("Nothing * Nothing", Nothing * Nothing) PrintResult("Nothing * -5I", Nothing * -5I) PrintResult("Nothing * ""12""", Nothing * "12") PrintResult("-5I / Nothing", -5I / Nothing) PrintResult("""12"" / Nothing", "12" / Nothing) PrintResult("Nothing / Nothing", Nothing / Nothing) PrintResult("Nothing / -5I", Nothing / -5I) PrintResult("Nothing / ""12""", Nothing / "12") PrintResult("Nothing \ -5I", Nothing \ -5I) PrintResult("Nothing \ ""12""", Nothing \ "12") PrintResult("""12"" Mod Nothing", "12" Mod Nothing) PrintResult("Nothing Mod -5I", Nothing Mod -5I) PrintResult("Nothing Mod ""12""", Nothing Mod "12") PrintResult("-5I ^ Nothing", -5I ^ Nothing) PrintResult("""12"" ^ Nothing", "12" ^ Nothing) PrintResult("Nothing ^ Nothing", Nothing ^ Nothing) PrintResult("Nothing ^ -5I", Nothing ^ -5I) PrintResult("Nothing ^ ""12""", Nothing ^ "12") PrintResult("-5I << Nothing", -5I << Nothing) PrintResult("""12"" << Nothing", "12" << Nothing) PrintResult("Nothing << Nothing", Nothing << Nothing) PrintResult("Nothing << -5I", Nothing << -5I) PrintResult("Nothing << ""12""", Nothing << "12") PrintResult("-5I >> Nothing", -5I >> Nothing) PrintResult("""12"" >> Nothing", "12" >> Nothing) PrintResult("Nothing >> Nothing", Nothing >> Nothing) PrintResult("Nothing >> -5I", Nothing >> -5I) PrintResult("Nothing >> ""12""", Nothing >> "12") PrintResult("-5I OrElse Nothing", -5I OrElse Nothing) PrintResult("""12"" OrElse Nothing", "12" OrElse Nothing) PrintResult("Nothing OrElse Nothing", Nothing OrElse Nothing) PrintResult("Nothing OrElse -5I", Nothing OrElse -5I) PrintResult("-5I AndAlso Nothing", -5I AndAlso Nothing) PrintResult("Nothing AndAlso Nothing", Nothing AndAlso Nothing) PrintResult("Nothing AndAlso -5I", Nothing AndAlso -5I) PrintResult("-5I & Nothing", -5I & Nothing) PrintResult("-5I & DBNull.Value", -5I & DBNull.Value) PrintResult("""12"" & Nothing", "12" & Nothing) PrintResult("""12"" & DBNull.Value", "12" & DBNull.Value) PrintResult("Nothing & Nothing", Nothing & Nothing) PrintResult("Nothing & DBNull.Value", Nothing & DBNull.Value) PrintResult("DBNull.Value & Nothing", DBNull.Value & Nothing) PrintResult("Nothing & -5I", Nothing & -5I) PrintResult("Nothing & ""12""", Nothing & "12") PrintResult("DBNull.Value & -5I", DBNull.Value & -5I) PrintResult("DBNull.Value & ""12""", DBNull.Value & "12") PrintResult("-5I Like Nothing", -5I Like Nothing) PrintResult("""12"" Like Nothing", "12" Like Nothing) PrintResult("Nothing Like Nothing", Nothing Like Nothing) PrintResult("Nothing Like -5I", Nothing Like -5I) PrintResult("Nothing Like ""12""", Nothing Like "12") PrintResult("-5I = Nothing", -5I = Nothing) PrintResult("""12"" = Nothing", "12" = Nothing) PrintResult("Nothing = Nothing", Nothing = Nothing) PrintResult("Nothing = -5I", Nothing = -5I) PrintResult("Nothing = ""12""", Nothing = "12") PrintResult("-5I <> Nothing", -5I <> Nothing) PrintResult("""12"" <> Nothing", "12" <> Nothing) PrintResult("Nothing <> Nothing", Nothing <> Nothing) PrintResult("Nothing <> -5I", Nothing <> -5I) PrintResult("Nothing <> ""12""", Nothing <> "12") PrintResult("-5I <= Nothing", -5I <= Nothing) PrintResult("""12"" <= Nothing", "12" <= Nothing) PrintResult("Nothing <= Nothing", Nothing <= Nothing) PrintResult("Nothing <= -5I", Nothing <= -5I) PrintResult("Nothing <= ""12""", Nothing <= "12") PrintResult("-5I >= Nothing", -5I >= Nothing) PrintResult("""12"" >= Nothing", "12" >= Nothing) PrintResult("Nothing >= Nothing", Nothing >= Nothing) PrintResult("Nothing >= -5I", Nothing >= -5I) PrintResult("Nothing >= ""12""", Nothing >= "12") PrintResult("-5I < Nothing", -5I < Nothing) PrintResult("""12"" < Nothing", "12" < Nothing) PrintResult("Nothing < Nothing", Nothing < Nothing) PrintResult("Nothing < -5I", Nothing < -5I) PrintResult("Nothing < ""12""", Nothing < "12") PrintResult("-5I > Nothing", -5I > Nothing) PrintResult("""12"" > Nothing", "12" > Nothing) PrintResult("Nothing > Nothing", Nothing > Nothing) PrintResult("Nothing > -5I", Nothing > -5I) PrintResult("Nothing > ""12""", Nothing > "12") PrintResult("-5I Xor Nothing", -5I Xor Nothing) PrintResult("""12"" Xor Nothing", "12" Xor Nothing) PrintResult("Nothing Xor Nothing", Nothing Xor Nothing) PrintResult("Nothing Xor -5I", Nothing Xor -5I) PrintResult("Nothing Xor ""12""", Nothing Xor "12") PrintResult("-5I Or Nothing", -5I Or Nothing) PrintResult("""12"" Or Nothing", "12" Or Nothing) PrintResult("Nothing Or Nothing", Nothing Or Nothing) PrintResult("Nothing Or -5I", Nothing Or -5I) PrintResult("Nothing Or ""12""", Nothing Or "12") PrintResult("-5I And Nothing", -5I And Nothing) PrintResult("""12"" And Nothing", "12" And Nothing) PrintResult("Nothing And Nothing", Nothing And Nothing) PrintResult("Nothing And -5I", Nothing And -5I) PrintResult("Nothing And ""12""", Nothing And "12") PrintResult("2I / 0", 2I / 0) PrintResult("1.5F / 0", 1.5F / 0) PrintResult("2.5R / 0", 2.5R / 0) PrintResult("1.5F Mod 0", 1.5F Mod 0) PrintResult("2.5R Mod 0", 2.5R Mod 0) PrintResult("2I / 0", 2I / Nothing) PrintResult("1.5F / 0", 1.5F / Nothing) PrintResult("2.5R / 0", 2.5R / Nothing) PrintResult("1.5F Mod 0", 1.5F Mod Nothing) PrintResult("2.5R Mod 0", 2.5R Mod Nothing) PrintResult("System.Single.MinValue - 1.0F", System.Single.MinValue - 1.0F) PrintResult("System.Double.MinValue - 1.0R", System.Double.MinValue - 1.0R) PrintResult("System.Single.MaxValue + 1.0F", System.Single.MaxValue + 1.0F) PrintResult("System.Double.MaxValue + 1.0R", System.Double.MaxValue + 1.0R) PrintResult("1.0F ^ System.Single.NegativeInfinity", 1.0F ^ System.Single.NegativeInfinity) PrintResult("1.0F ^ System.Single.PositiveInfinity", 1.0F ^ System.Single.PositiveInfinity) PrintResult("1.0R ^ System.Double.NegativeInfinity", 1.0R ^ System.Double.NegativeInfinity) PrintResult("1.0R ^ System.Double.PositiveInfinity", 1.0R ^ System.Double.PositiveInfinity) PrintResult("-1.0F ^ System.Single.NegativeInfinity", -1.0F ^ System.Single.NegativeInfinity) PrintResult("-1.0F ^ System.Single.PositiveInfinity", -1.0F ^ System.Single.PositiveInfinity) PrintResult("-1.0R ^ System.Double.NegativeInfinity", -1.0R ^ System.Double.NegativeInfinity) PrintResult("-1.0R ^ System.Double.PositiveInfinity", -1.0R ^ System.Double.PositiveInfinity) PrintResult("2.0F ^ System.Single.NaN", 2.0F ^ System.Single.NaN) PrintResult("2.0R ^ System.Double.NaN", 2.0R ^ System.Double.NaN) PrintResult("(-1.0F) ^ System.Single.NegativeInfinity", (-1.0F) ^ System.Single.NegativeInfinity) PrintResult("(-1.0F) ^ System.Single.PositiveInfinity", (-1.0F) ^ System.Single.PositiveInfinity) PrintResult("(-1.0F) ^ System.Double.NegativeInfinity", (-1.0F) ^ System.Double.NegativeInfinity) PrintResult("(-1.0F) ^ System.Double.PositiveInfinity", (-1.0F) ^ System.Double.PositiveInfinity) End Sub End Module
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Option Strict Off Imports System Module Module1 Sub Main() PrintResult("False + False", False + False) PrintResult("False + True", False + True) PrintResult("False + System.SByte.MinValue", False + System.SByte.MinValue) PrintResult("False + System.Byte.MaxValue", False + System.Byte.MaxValue) PrintResult("False + -3S", False + -3S) PrintResult("False + 24US", False + 24US) PrintResult("False + -5I", False + -5I) PrintResult("False + 26UI", False + 26UI) PrintResult("False + -7L", False + -7L) PrintResult("False + 28UL", False + 28UL) PrintResult("False + -9D", False + -9D) PrintResult("False + 10.0F", False + 10.0F) PrintResult("False + -11.0R", False + -11.0R) PrintResult("False + ""12""", False + "12") PrintResult("False + TypeCode.Double", False + TypeCode.Double) PrintResult("True + False", True + False) PrintResult("True + True", True + True) PrintResult("True + System.SByte.MaxValue", True + System.SByte.MaxValue) PrintResult("True + System.Byte.MaxValue", True + System.Byte.MaxValue) PrintResult("True + -3S", True + -3S) PrintResult("True + 24US", True + 24US) PrintResult("True + -5I", True + -5I) PrintResult("True + 26UI", True + 26UI) PrintResult("True + -7L", True + -7L) PrintResult("True + 28UL", True + 28UL) PrintResult("True + -9D", True + -9D) PrintResult("True + 10.0F", True + 10.0F) PrintResult("True + -11.0R", True + -11.0R) PrintResult("True + ""12""", True + "12") PrintResult("True + TypeCode.Double", True + TypeCode.Double) PrintResult("System.SByte.MinValue + False", System.SByte.MinValue + False) PrintResult("System.SByte.MaxValue + True", System.SByte.MaxValue + True) PrintResult("System.SByte.MinValue + System.SByte.MaxValue", System.SByte.MinValue + System.SByte.MaxValue) PrintResult("System.SByte.MinValue + System.Byte.MaxValue", System.SByte.MinValue + System.Byte.MaxValue) PrintResult("System.SByte.MinValue + -3S", System.SByte.MinValue + -3S) PrintResult("System.SByte.MinValue + 24US", System.SByte.MinValue + 24US) PrintResult("System.SByte.MinValue + -5I", System.SByte.MinValue + -5I) PrintResult("System.SByte.MinValue + 26UI", System.SByte.MinValue + 26UI) PrintResult("System.SByte.MinValue + -7L", System.SByte.MinValue + -7L) PrintResult("System.SByte.MinValue + 28UL", System.SByte.MinValue + 28UL) PrintResult("System.SByte.MinValue + -9D", System.SByte.MinValue + -9D) PrintResult("System.SByte.MinValue + 10.0F", System.SByte.MinValue + 10.0F) PrintResult("System.SByte.MinValue + -11.0R", System.SByte.MinValue + -11.0R) PrintResult("System.SByte.MinValue + ""12""", System.SByte.MinValue + "12") PrintResult("System.SByte.MinValue + TypeCode.Double", System.SByte.MinValue + TypeCode.Double) PrintResult("System.Byte.MaxValue + False", System.Byte.MaxValue + False) PrintResult("System.Byte.MaxValue + True", System.Byte.MaxValue + True) PrintResult("System.Byte.MaxValue + System.SByte.MinValue", System.Byte.MaxValue + System.SByte.MinValue) PrintResult("System.Byte.MaxValue + System.Byte.MinValue", System.Byte.MaxValue + System.Byte.MinValue) PrintResult("System.Byte.MaxValue + -3S", System.Byte.MaxValue + -3S) PrintResult("System.Byte.MaxValue + 24US", System.Byte.MaxValue + 24US) PrintResult("System.Byte.MaxValue + -5I", System.Byte.MaxValue + -5I) PrintResult("System.Byte.MaxValue + 26UI", System.Byte.MaxValue + 26UI) PrintResult("System.Byte.MaxValue + -7L", System.Byte.MaxValue + -7L) PrintResult("System.Byte.MaxValue + 28UL", System.Byte.MaxValue + 28UL) PrintResult("System.Byte.MaxValue + -9D", System.Byte.MaxValue + -9D) PrintResult("System.Byte.MaxValue + 10.0F", System.Byte.MaxValue + 10.0F) PrintResult("System.Byte.MaxValue + -11.0R", System.Byte.MaxValue + -11.0R) PrintResult("System.Byte.MaxValue + ""12""", System.Byte.MaxValue + "12") PrintResult("System.Byte.MaxValue + TypeCode.Double", System.Byte.MaxValue + TypeCode.Double) PrintResult("-3S + False", -3S + False) PrintResult("-3S + True", -3S + True) PrintResult("-3S + System.SByte.MinValue", -3S + System.SByte.MinValue) PrintResult("-3S + System.Byte.MaxValue", -3S + System.Byte.MaxValue) PrintResult("-3S + -3S", -3S + -3S) PrintResult("-3S + 24US", -3S + 24US) PrintResult("-3S + -5I", -3S + -5I) PrintResult("-3S + 26UI", -3S + 26UI) PrintResult("-3S + -7L", -3S + -7L) PrintResult("-3S + 28UL", -3S + 28UL) PrintResult("-3S + -9D", -3S + -9D) PrintResult("-3S + 10.0F", -3S + 10.0F) PrintResult("-3S + -11.0R", -3S + -11.0R) PrintResult("-3S + ""12""", -3S + "12") PrintResult("-3S + TypeCode.Double", -3S + TypeCode.Double) PrintResult("24US + False", 24US + False) PrintResult("24US + True", 24US + True) PrintResult("24US + System.SByte.MinValue", 24US + System.SByte.MinValue) PrintResult("24US + System.Byte.MaxValue", 24US + System.Byte.MaxValue) PrintResult("24US + -3S", 24US + -3S) PrintResult("24US + 24US", 24US + 24US) PrintResult("24US + -5I", 24US + -5I) PrintResult("24US + 26UI", 24US + 26UI) PrintResult("24US + -7L", 24US + -7L) PrintResult("24US + 28UL", 24US + 28UL) PrintResult("24US + -9D", 24US + -9D) PrintResult("24US + 10.0F", 24US + 10.0F) PrintResult("24US + -11.0R", 24US + -11.0R) PrintResult("24US + ""12""", 24US + "12") PrintResult("24US + TypeCode.Double", 24US + TypeCode.Double) PrintResult("-5I + False", -5I + False) PrintResult("-5I + True", -5I + True) PrintResult("-5I + System.SByte.MinValue", -5I + System.SByte.MinValue) PrintResult("-5I + System.Byte.MaxValue", -5I + System.Byte.MaxValue) PrintResult("-5I + -3S", -5I + -3S) PrintResult("-5I + 24US", -5I + 24US) PrintResult("-5I + -5I", -5I + -5I) PrintResult("-5I + 26UI", -5I + 26UI) PrintResult("-5I + -7L", -5I + -7L) PrintResult("-5I + 28UL", -5I + 28UL) PrintResult("-5I + -9D", -5I + -9D) PrintResult("-5I + 10.0F", -5I + 10.0F) PrintResult("-5I + -11.0R", -5I + -11.0R) PrintResult("-5I + ""12""", -5I + "12") PrintResult("-5I + TypeCode.Double", -5I + TypeCode.Double) PrintResult("26UI + False", 26UI + False) PrintResult("26UI + True", 26UI + True) PrintResult("26UI + System.SByte.MinValue", 26UI + System.SByte.MinValue) PrintResult("26UI + System.Byte.MaxValue", 26UI + System.Byte.MaxValue) PrintResult("26UI + -3S", 26UI + -3S) PrintResult("26UI + 24US", 26UI + 24US) PrintResult("26UI + -5I", 26UI + -5I) PrintResult("26UI + 26UI", 26UI + 26UI) PrintResult("26UI + -7L", 26UI + -7L) PrintResult("26UI + 28UL", 26UI + 28UL) PrintResult("26UI + -9D", 26UI + -9D) PrintResult("26UI + 10.0F", 26UI + 10.0F) PrintResult("26UI + -11.0R", 26UI + -11.0R) PrintResult("26UI + ""12""", 26UI + "12") PrintResult("26UI + TypeCode.Double", 26UI + TypeCode.Double) PrintResult("-7L + False", -7L + False) PrintResult("-7L + True", -7L + True) PrintResult("-7L + System.SByte.MinValue", -7L + System.SByte.MinValue) PrintResult("-7L + System.Byte.MaxValue", -7L + System.Byte.MaxValue) PrintResult("-7L + -3S", -7L + -3S) PrintResult("-7L + 24US", -7L + 24US) PrintResult("-7L + -5I", -7L + -5I) PrintResult("-7L + 26UI", -7L + 26UI) PrintResult("-7L + -7L", -7L + -7L) PrintResult("-7L + 28UL", -7L + 28UL) PrintResult("-7L + -9D", -7L + -9D) PrintResult("-7L + 10.0F", -7L + 10.0F) PrintResult("-7L + -11.0R", -7L + -11.0R) PrintResult("-7L + ""12""", -7L + "12") PrintResult("-7L + TypeCode.Double", -7L + TypeCode.Double) PrintResult("28UL + False", 28UL + False) PrintResult("28UL + True", 28UL + True) PrintResult("28UL + System.SByte.MinValue", 28UL + System.SByte.MinValue) PrintResult("28UL + System.Byte.MaxValue", 28UL + System.Byte.MaxValue) PrintResult("28UL + -3S", 28UL + -3S) PrintResult("28UL + 24US", 28UL + 24US) PrintResult("28UL + -5I", 28UL + -5I) PrintResult("28UL + 26UI", 28UL + 26UI) PrintResult("28UL + -7L", 28UL + -7L) PrintResult("28UL + 28UL", 28UL + 28UL) PrintResult("28UL + -9D", 28UL + -9D) PrintResult("28UL + 10.0F", 28UL + 10.0F) PrintResult("28UL + -11.0R", 28UL + -11.0R) PrintResult("28UL + ""12""", 28UL + "12") PrintResult("28UL + TypeCode.Double", 28UL + TypeCode.Double) PrintResult("-9D + False", -9D + False) PrintResult("-9D + True", -9D + True) PrintResult("-9D + System.SByte.MinValue", -9D + System.SByte.MinValue) PrintResult("-9D + System.Byte.MaxValue", -9D + System.Byte.MaxValue) PrintResult("-9D + -3S", -9D + -3S) PrintResult("-9D + 24US", -9D + 24US) PrintResult("-9D + -5I", -9D + -5I) PrintResult("-9D + 26UI", -9D + 26UI) PrintResult("-9D + -7L", -9D + -7L) PrintResult("-9D + 28UL", -9D + 28UL) PrintResult("-9D + -9D", -9D + -9D) PrintResult("-9D + 10.0F", -9D + 10.0F) PrintResult("-9D + -11.0R", -9D + -11.0R) PrintResult("-9D + ""12""", -9D + "12") PrintResult("-9D + TypeCode.Double", -9D + TypeCode.Double) PrintResult("10.0F + False", 10.0F + False) PrintResult("10.0F + True", 10.0F + True) PrintResult("10.0F + System.SByte.MinValue", 10.0F + System.SByte.MinValue) PrintResult("10.0F + System.Byte.MaxValue", 10.0F + System.Byte.MaxValue) PrintResult("10.0F + -3S", 10.0F + -3S) PrintResult("10.0F + 24US", 10.0F + 24US) PrintResult("10.0F + -5I", 10.0F + -5I) PrintResult("10.0F + 26UI", 10.0F + 26UI) PrintResult("10.0F + -7L", 10.0F + -7L) PrintResult("10.0F + 28UL", 10.0F + 28UL) PrintResult("10.0F + -9D", 10.0F + -9D) PrintResult("10.0F + 10.0F", 10.0F + 10.0F) PrintResult("10.0F + -11.0R", 10.0F + -11.0R) PrintResult("10.0F + ""12""", 10.0F + "12") PrintResult("10.0F + TypeCode.Double", 10.0F + TypeCode.Double) PrintResult("-11.0R + False", -11.0R + False) PrintResult("-11.0R + True", -11.0R + True) PrintResult("-11.0R + System.SByte.MinValue", -11.0R + System.SByte.MinValue) PrintResult("-11.0R + System.Byte.MaxValue", -11.0R + System.Byte.MaxValue) PrintResult("-11.0R + -3S", -11.0R + -3S) PrintResult("-11.0R + 24US", -11.0R + 24US) PrintResult("-11.0R + -5I", -11.0R + -5I) PrintResult("-11.0R + 26UI", -11.0R + 26UI) PrintResult("-11.0R + -7L", -11.0R + -7L) PrintResult("-11.0R + 28UL", -11.0R + 28UL) PrintResult("-11.0R + -9D", -11.0R + -9D) PrintResult("-11.0R + 10.0F", -11.0R + 10.0F) PrintResult("-11.0R + -11.0R", -11.0R + -11.0R) PrintResult("-11.0R + ""12""", -11.0R + "12") PrintResult("-11.0R + TypeCode.Double", -11.0R + TypeCode.Double) PrintResult("""12"" + False", "12" + False) PrintResult("""12"" + True", "12" + True) PrintResult("""12"" + System.SByte.MinValue", "12" + System.SByte.MinValue) PrintResult("""12"" + System.Byte.MaxValue", "12" + System.Byte.MaxValue) PrintResult("""12"" + -3S", "12" + -3S) PrintResult("""12"" + 24US", "12" + 24US) PrintResult("""12"" + -5I", "12" + -5I) PrintResult("""12"" + 26UI", "12" + 26UI) PrintResult("""12"" + -7L", "12" + -7L) PrintResult("""12"" + 28UL", "12" + 28UL) PrintResult("""12"" + -9D", "12" + -9D) PrintResult("""12"" + 10.0F", "12" + 10.0F) PrintResult("""12"" + -11.0R", "12" + -11.0R) PrintResult("""12"" + ""12""", "12" + "12") PrintResult("""12"" + TypeCode.Double", "12" + TypeCode.Double) PrintResult("TypeCode.Double + False", TypeCode.Double + False) PrintResult("TypeCode.Double + True", TypeCode.Double + True) PrintResult("TypeCode.Double + System.SByte.MinValue", TypeCode.Double + System.SByte.MinValue) PrintResult("TypeCode.Double + System.Byte.MaxValue", TypeCode.Double + System.Byte.MaxValue) PrintResult("TypeCode.Double + -3S", TypeCode.Double + -3S) PrintResult("TypeCode.Double + 24US", TypeCode.Double + 24US) PrintResult("TypeCode.Double + -5I", TypeCode.Double + -5I) PrintResult("TypeCode.Double + 26UI", TypeCode.Double + 26UI) PrintResult("TypeCode.Double + -7L", TypeCode.Double + -7L) PrintResult("TypeCode.Double + 28UL", TypeCode.Double + 28UL) PrintResult("TypeCode.Double + -9D", TypeCode.Double + -9D) PrintResult("TypeCode.Double + 10.0F", TypeCode.Double + 10.0F) PrintResult("TypeCode.Double + -11.0R", TypeCode.Double + -11.0R) PrintResult("TypeCode.Double + ""12""", TypeCode.Double + "12") PrintResult("TypeCode.Double + TypeCode.Double", TypeCode.Double + TypeCode.Double) PrintResult("False - False", False - False) PrintResult("False - True", False - True) PrintResult("False - System.SByte.MaxValue", False - System.SByte.MaxValue) PrintResult("False - System.Byte.MaxValue", False - System.Byte.MaxValue) PrintResult("False - -3S", False - -3S) PrintResult("False - 24US", False - 24US) PrintResult("False - -5I", False - -5I) PrintResult("False - 26UI", False - 26UI) PrintResult("False - -7L", False - -7L) PrintResult("False - 28UL", False - 28UL) PrintResult("False - -9D", False - -9D) PrintResult("False - 10.0F", False - 10.0F) PrintResult("False - -11.0R", False - -11.0R) PrintResult("False - ""12""", False - "12") PrintResult("False - TypeCode.Double", False - TypeCode.Double) PrintResult("True - False", True - False) PrintResult("True - True", True - True) PrintResult("True - System.SByte.MinValue", True - System.SByte.MinValue) PrintResult("True - System.Byte.MaxValue", True - System.Byte.MaxValue) PrintResult("True - -3S", True - -3S) PrintResult("True - 24US", True - 24US) PrintResult("True - -5I", True - -5I) PrintResult("True - 26UI", True - 26UI) PrintResult("True - -7L", True - -7L) PrintResult("True - 28UL", True - 28UL) PrintResult("True - -9D", True - -9D) PrintResult("True - 10.0F", True - 10.0F) PrintResult("True - -11.0R", True - -11.0R) PrintResult("True - ""12""", True - "12") PrintResult("True - TypeCode.Double", True - TypeCode.Double) PrintResult("System.SByte.MinValue - False", System.SByte.MinValue - False) PrintResult("System.SByte.MinValue - True", System.SByte.MinValue - True) PrintResult("System.SByte.MinValue - System.SByte.MinValue", System.SByte.MinValue - System.SByte.MinValue) PrintResult("System.SByte.MinValue - System.Byte.MaxValue", System.SByte.MinValue - System.Byte.MaxValue) PrintResult("System.SByte.MinValue - -3S", System.SByte.MinValue - -3S) PrintResult("System.SByte.MinValue - 24US", System.SByte.MinValue - 24US) PrintResult("System.SByte.MinValue - -5I", System.SByte.MinValue - -5I) PrintResult("System.SByte.MinValue - 26UI", System.SByte.MinValue - 26UI) PrintResult("System.SByte.MinValue - -7L", System.SByte.MinValue - -7L) PrintResult("System.SByte.MinValue - 28UL", System.SByte.MinValue - 28UL) PrintResult("System.SByte.MinValue - -9D", System.SByte.MinValue - -9D) PrintResult("System.SByte.MinValue - 10.0F", System.SByte.MinValue - 10.0F) PrintResult("System.SByte.MinValue - -11.0R", System.SByte.MinValue - -11.0R) PrintResult("System.SByte.MinValue - ""12""", System.SByte.MinValue - "12") PrintResult("System.SByte.MinValue - TypeCode.Double", System.SByte.MinValue - TypeCode.Double) PrintResult("System.Byte.MaxValue - False", System.Byte.MaxValue - False) PrintResult("System.Byte.MaxValue - True", System.Byte.MaxValue - True) PrintResult("System.Byte.MaxValue - System.SByte.MinValue", System.Byte.MaxValue - System.SByte.MinValue) PrintResult("System.Byte.MaxValue - System.Byte.MaxValue", System.Byte.MaxValue - System.Byte.MaxValue) PrintResult("System.Byte.MaxValue - -3S", System.Byte.MaxValue - -3S) PrintResult("System.Byte.MaxValue - -5I", System.Byte.MaxValue - -5I) PrintResult("System.Byte.MaxValue - -7L", System.Byte.MaxValue - -7L) PrintResult("System.Byte.MaxValue - -9D", System.Byte.MaxValue - -9D) PrintResult("System.Byte.MaxValue - 10.0F", System.Byte.MaxValue - 10.0F) PrintResult("System.Byte.MaxValue - -11.0R", System.Byte.MaxValue - -11.0R) PrintResult("System.Byte.MaxValue - ""12""", System.Byte.MaxValue - "12") PrintResult("System.Byte.MaxValue - TypeCode.Double", System.Byte.MaxValue - TypeCode.Double) PrintResult("-3S - False", -3S - False) PrintResult("-3S - True", -3S - True) PrintResult("-3S - System.SByte.MinValue", -3S - System.SByte.MinValue) PrintResult("-3S - System.Byte.MaxValue", -3S - System.Byte.MaxValue) PrintResult("-3S - -3S", -3S - -3S) PrintResult("-3S - 24US", -3S - 24US) PrintResult("-3S - -5I", -3S - -5I) PrintResult("-3S - 26UI", -3S - 26UI) PrintResult("-3S - -7L", -3S - -7L) PrintResult("-3S - 28UL", -3S - 28UL) PrintResult("-3S - -9D", -3S - -9D) PrintResult("-3S - 10.0F", -3S - 10.0F) PrintResult("-3S - -11.0R", -3S - -11.0R) PrintResult("-3S - ""12""", -3S - "12") PrintResult("-3S - TypeCode.Double", -3S - TypeCode.Double) PrintResult("24US - False", 24US - False) PrintResult("24US - True", 24US - True) PrintResult("24US - System.SByte.MinValue", 24US - System.SByte.MinValue) PrintResult("System.UInt16.MaxValue - System.Byte.MaxValue", System.UInt16.MaxValue - System.Byte.MaxValue) PrintResult("24US - -3S", 24US - -3S) PrintResult("24US - 24US", 24US - 24US) PrintResult("24US - -5I", 24US - -5I) PrintResult("24US - -7L", 24US - -7L) PrintResult("24US - -9D", 24US - -9D) PrintResult("24US - 10.0F", 24US - 10.0F) PrintResult("24US - -11.0R", 24US - -11.0R) PrintResult("24US - ""12""", 24US - "12") PrintResult("24US - TypeCode.Double", 24US - TypeCode.Double) PrintResult("-5I - False", -5I - False) PrintResult("-5I - True", -5I - True) PrintResult("-5I - System.SByte.MinValue", -5I - System.SByte.MinValue) PrintResult("-5I - System.Byte.MaxValue", -5I - System.Byte.MaxValue) PrintResult("-5I - -3S", -5I - -3S) PrintResult("-5I - 24US", -5I - 24US) PrintResult("-5I - -5I", -5I - -5I) PrintResult("-5I - 26UI", -5I - 26UI) PrintResult("-5I - -7L", -5I - -7L) PrintResult("-5I - 28UL", -5I - 28UL) PrintResult("-5I - -9D", -5I - -9D) PrintResult("-5I - 10.0F", -5I - 10.0F) PrintResult("-5I - -11.0R", -5I - -11.0R) PrintResult("-5I - ""12""", -5I - "12") PrintResult("-5I - TypeCode.Double", -5I - TypeCode.Double) PrintResult("26UI - False", 26UI - False) PrintResult("26UI - True", 26UI - True) PrintResult("26UI - System.SByte.MinValue", 26UI - System.SByte.MinValue) PrintResult("System.UInt32.MaxValue - System.Byte.MaxValue", System.UInt32.MaxValue - System.Byte.MaxValue) PrintResult("26UI - -3S", 26UI - -3S) PrintResult("26UI - 24US", 26UI - 24US) PrintResult("26UI - -5I", 26UI - -5I) PrintResult("26UI - 26UI", 26UI - 26UI) PrintResult("26UI - -7L", 26UI - -7L) PrintResult("26UI - -9D", 26UI - -9D) PrintResult("26UI - 10.0F", 26UI - 10.0F) PrintResult("26UI - -11.0R", 26UI - -11.0R) PrintResult("26UI - ""12""", 26UI - "12") PrintResult("26UI - TypeCode.Double", 26UI - TypeCode.Double) PrintResult("-7L - False", -7L - False) PrintResult("-7L - True", -7L - True) PrintResult("-7L - System.SByte.MinValue", -7L - System.SByte.MinValue) PrintResult("-7L - System.Byte.MaxValue", -7L - System.Byte.MaxValue) PrintResult("-7L - -3S", -7L - -3S) PrintResult("-7L - 24US", -7L - 24US) PrintResult("-7L - -5I", -7L - -5I) PrintResult("-7L - 26UI", -7L - 26UI) PrintResult("-7L - -7L", -7L - -7L) PrintResult("-7L - 28UL", -7L - 28UL) PrintResult("-7L - -9D", -7L - -9D) PrintResult("-7L - 10.0F", -7L - 10.0F) PrintResult("-7L - -11.0R", -7L - -11.0R) PrintResult("-7L - ""12""", -7L - "12") PrintResult("-7L - TypeCode.Double", -7L - TypeCode.Double) PrintResult("28UL - False", 28UL - False) PrintResult("28UL - True", 28UL - True) PrintResult("28UL - System.SByte.MinValue", 28UL - System.SByte.MinValue) PrintResult("System.UInt64.MaxValue - System.Byte.MaxValue", System.UInt64.MaxValue - System.Byte.MaxValue) PrintResult("28UL - -3S", 28UL - -3S) PrintResult("28UL - 24US", 28UL - 24US) PrintResult("28UL - -5I", 28UL - -5I) PrintResult("28UL - 26UI", 28UL - 26UI) PrintResult("28UL - -7L", 28UL - -7L) PrintResult("28UL - 28UL", 28UL - 28UL) PrintResult("28UL - -9D", 28UL - -9D) PrintResult("28UL - 10.0F", 28UL - 10.0F) PrintResult("28UL - -11.0R", 28UL - -11.0R) PrintResult("28UL - ""12""", 28UL - "12") PrintResult("28UL - TypeCode.Double", 28UL - TypeCode.Double) PrintResult("-9D - False", -9D - False) PrintResult("-9D - True", -9D - True) PrintResult("-9D - System.SByte.MinValue", -9D - System.SByte.MinValue) PrintResult("-9D - System.Byte.MaxValue", -9D - System.Byte.MaxValue) PrintResult("-9D - -3S", -9D - -3S) PrintResult("-9D - 24US", -9D - 24US) PrintResult("-9D - -5I", -9D - -5I) PrintResult("-9D - 26UI", -9D - 26UI) PrintResult("-9D - -7L", -9D - -7L) PrintResult("-9D - 28UL", -9D - 28UL) PrintResult("-9D - -9D", -9D - -9D) PrintResult("-9D - 10.0F", -9D - 10.0F) PrintResult("-9D - -11.0R", -9D - -11.0R) PrintResult("-9D - ""12""", -9D - "12") PrintResult("-9D - TypeCode.Double", -9D - TypeCode.Double) PrintResult("10.0F - False", 10.0F - False) PrintResult("10.0F - True", 10.0F - True) PrintResult("10.0F - System.SByte.MinValue", 10.0F - System.SByte.MinValue) PrintResult("10.0F - System.Byte.MaxValue", 10.0F - System.Byte.MaxValue) PrintResult("10.0F - -3S", 10.0F - -3S) PrintResult("10.0F - 24US", 10.0F - 24US) PrintResult("10.0F - -5I", 10.0F - -5I) PrintResult("10.0F - 26UI", 10.0F - 26UI) PrintResult("10.0F - -7L", 10.0F - -7L) PrintResult("10.0F - 28UL", 10.0F - 28UL) PrintResult("10.0F - -9D", 10.0F - -9D) PrintResult("10.0F - 10.0F", 10.0F - 10.0F) PrintResult("10.0F - -11.0R", 10.0F - -11.0R) PrintResult("10.0F - ""12""", 10.0F - "12") PrintResult("10.0F - TypeCode.Double", 10.0F - TypeCode.Double) PrintResult("-11.0R - False", -11.0R - False) PrintResult("-11.0R - True", -11.0R - True) PrintResult("-11.0R - System.SByte.MinValue", -11.0R - System.SByte.MinValue) PrintResult("-11.0R - System.Byte.MaxValue", -11.0R - System.Byte.MaxValue) PrintResult("-11.0R - -3S", -11.0R - -3S) PrintResult("-11.0R - 24US", -11.0R - 24US) PrintResult("-11.0R - -5I", -11.0R - -5I) PrintResult("-11.0R - 26UI", -11.0R - 26UI) PrintResult("-11.0R - -7L", -11.0R - -7L) PrintResult("-11.0R - 28UL", -11.0R - 28UL) PrintResult("-11.0R - -9D", -11.0R - -9D) PrintResult("-11.0R - 10.0F", -11.0R - 10.0F) PrintResult("-11.0R - -11.0R", -11.0R - -11.0R) PrintResult("-11.0R - ""12""", -11.0R - "12") PrintResult("-11.0R - TypeCode.Double", -11.0R - TypeCode.Double) PrintResult("""12"" - False", "12" - False) PrintResult("""12"" - True", "12" - True) PrintResult("""12"" - System.SByte.MinValue", "12" - System.SByte.MinValue) PrintResult("""12"" - System.Byte.MaxValue", "12" - System.Byte.MaxValue) PrintResult("""12"" - -3S", "12" - -3S) PrintResult("""12"" - 24US", "12" - 24US) PrintResult("""12"" - -5I", "12" - -5I) PrintResult("""12"" - 26UI", "12" - 26UI) PrintResult("""12"" - -7L", "12" - -7L) PrintResult("""12"" - 28UL", "12" - 28UL) PrintResult("""12"" - -9D", "12" - -9D) PrintResult("""12"" - 10.0F", "12" - 10.0F) PrintResult("""12"" - -11.0R", "12" - -11.0R) PrintResult("""12"" - ""12""", "12" - "12") PrintResult("""12"" - TypeCode.Double", "12" - TypeCode.Double) PrintResult("TypeCode.Double - False", TypeCode.Double - False) PrintResult("TypeCode.Double - True", TypeCode.Double - True) PrintResult("TypeCode.Double - System.SByte.MinValue", TypeCode.Double - System.SByte.MinValue) PrintResult("TypeCode.Double - System.Byte.MaxValue", TypeCode.Double - System.Byte.MaxValue) PrintResult("TypeCode.Double - -3S", TypeCode.Double - -3S) PrintResult("TypeCode.Double - 24US", TypeCode.Double - 24US) PrintResult("TypeCode.Double - -5I", TypeCode.Double - -5I) PrintResult("TypeCode.Double - 26UI", TypeCode.Double - 26UI) PrintResult("TypeCode.Double - -7L", TypeCode.Double - -7L) PrintResult("TypeCode.Double - 28UL", TypeCode.Double - 28UL) PrintResult("TypeCode.Double - -9D", TypeCode.Double - -9D) PrintResult("TypeCode.Double - 10.0F", TypeCode.Double - 10.0F) PrintResult("TypeCode.Double - -11.0R", TypeCode.Double - -11.0R) PrintResult("TypeCode.Double - ""12""", TypeCode.Double - "12") PrintResult("TypeCode.Double - TypeCode.Double", TypeCode.Double - TypeCode.Double) PrintResult("False * False", False * False) PrintResult("False * True", False * True) PrintResult("False * System.SByte.MinValue", False * System.SByte.MinValue) PrintResult("False * System.Byte.MaxValue", False * System.Byte.MaxValue) PrintResult("False * -3S", False * -3S) PrintResult("False * 24US", False * 24US) PrintResult("False * -5I", False * -5I) PrintResult("False * 26UI", False * 26UI) PrintResult("False * -7L", False * -7L) PrintResult("False * 28UL", False * 28UL) PrintResult("False * -9D", False * -9D) PrintResult("False * 10.0F", False * 10.0F) PrintResult("False * -11.0R", False * -11.0R) PrintResult("False * ""12""", False * "12") PrintResult("False * TypeCode.Double", False * TypeCode.Double) PrintResult("True * False", True * False) PrintResult("True * True", True * True) PrintResult("True * System.SByte.MaxValue", True * System.SByte.MaxValue) PrintResult("True * System.Byte.MaxValue", True * System.Byte.MaxValue) PrintResult("True * -3S", True * -3S) PrintResult("True * 24US", True * 24US) PrintResult("True * -5I", True * -5I) PrintResult("True * 26UI", True * 26UI) PrintResult("True * -7L", True * -7L) PrintResult("True * 28UL", True * 28UL) PrintResult("True * -9D", True * -9D) PrintResult("True * 10.0F", True * 10.0F) PrintResult("True * -11.0R", True * -11.0R) PrintResult("True * ""12""", True * "12") PrintResult("True * TypeCode.Double", True * TypeCode.Double) PrintResult("System.SByte.MinValue * False", System.SByte.MinValue * False) PrintResult("System.SByte.MaxValue * True", System.SByte.MaxValue * True) PrintResult("System.SByte.MinValue * (-(System.SByte.MinValue + System.SByte.MaxValue))", System.SByte.MinValue * (-(System.SByte.MinValue + System.SByte.MaxValue))) PrintResult("System.SByte.MinValue * System.Byte.MaxValue", System.SByte.MinValue * System.Byte.MaxValue) PrintResult("System.SByte.MinValue * -3S", System.SByte.MinValue * -3S) PrintResult("System.SByte.MinValue * 24US", System.SByte.MinValue * 24US) PrintResult("System.SByte.MinValue * -5I", System.SByte.MinValue * -5I) PrintResult("System.SByte.MinValue * 26UI", System.SByte.MinValue * 26UI) PrintResult("System.SByte.MinValue * -7L", System.SByte.MinValue * -7L) PrintResult("System.SByte.MinValue * 28UL", System.SByte.MinValue * 28UL) PrintResult("System.SByte.MinValue * -9D", System.SByte.MinValue * -9D) PrintResult("System.SByte.MinValue * 10.0F", System.SByte.MinValue * 10.0F) PrintResult("System.SByte.MinValue * -11.0R", System.SByte.MinValue * -11.0R) PrintResult("System.SByte.MinValue * ""12""", System.SByte.MinValue * "12") PrintResult("System.SByte.MinValue * TypeCode.Double", System.SByte.MinValue * TypeCode.Double) PrintResult("System.Byte.MaxValue * False", System.Byte.MaxValue * False) PrintResult("System.Byte.MaxValue * True", System.Byte.MaxValue * True) PrintResult("System.Byte.MaxValue * System.SByte.MinValue", System.Byte.MaxValue * System.SByte.MinValue) PrintResult("System.Byte.MaxValue * -3S", System.Byte.MaxValue * -3S) PrintResult("System.Byte.MaxValue * 24US", System.Byte.MaxValue * 24US) PrintResult("System.Byte.MaxValue * -5I", System.Byte.MaxValue * -5I) PrintResult("System.Byte.MaxValue * 26UI", System.Byte.MaxValue * 26UI) PrintResult("System.Byte.MaxValue * -7L", System.Byte.MaxValue * -7L) PrintResult("System.Byte.MaxValue * 28UL", System.Byte.MaxValue * 28UL) PrintResult("System.Byte.MaxValue * -9D", System.Byte.MaxValue * -9D) PrintResult("System.Byte.MaxValue * 10.0F", System.Byte.MaxValue * 10.0F) PrintResult("System.Byte.MaxValue * -11.0R", System.Byte.MaxValue * -11.0R) PrintResult("System.Byte.MaxValue * ""12""", System.Byte.MaxValue * "12") PrintResult("System.Byte.MaxValue * TypeCode.Double", System.Byte.MaxValue * TypeCode.Double) PrintResult("-3S * False", -3S * False) PrintResult("-3S * True", -3S * True) PrintResult("-3S * System.SByte.MinValue", -3S * System.SByte.MinValue) PrintResult("-3S * System.Byte.MaxValue", -3S * System.Byte.MaxValue) PrintResult("-3S * -3S", -3S * -3S) PrintResult("-3S * 24US", -3S * 24US) PrintResult("-3S * -5I", -3S * -5I) PrintResult("-3S * 26UI", -3S * 26UI) PrintResult("-3S * -7L", -3S * -7L) PrintResult("-3S * 28UL", -3S * 28UL) PrintResult("-3S * -9D", -3S * -9D) PrintResult("-3S * 10.0F", -3S * 10.0F) PrintResult("-3S * -11.0R", -3S * -11.0R) PrintResult("-3S * ""12""", -3S * "12") PrintResult("-3S * TypeCode.Double", -3S * TypeCode.Double) PrintResult("24US * False", 24US * False) PrintResult("24US * True", 24US * True) PrintResult("24US * System.SByte.MinValue", 24US * System.SByte.MinValue) PrintResult("24US * System.Byte.MaxValue", 24US * System.Byte.MaxValue) PrintResult("24US * -3S", 24US * -3S) PrintResult("24US * 24US", 24US * 24US) PrintResult("24US * -5I", 24US * -5I) PrintResult("24US * 26UI", 24US * 26UI) PrintResult("24US * -7L", 24US * -7L) PrintResult("24US * 28UL", 24US * 28UL) PrintResult("24US * -9D", 24US * -9D) PrintResult("24US * 10.0F", 24US * 10.0F) PrintResult("24US * -11.0R", 24US * -11.0R) PrintResult("24US * ""12""", 24US * "12") PrintResult("24US * TypeCode.Double", 24US * TypeCode.Double) PrintResult("-5I * False", -5I * False) PrintResult("-5I * True", -5I * True) PrintResult("-5I * System.SByte.MinValue", -5I * System.SByte.MinValue) PrintResult("-5I * System.Byte.MaxValue", -5I * System.Byte.MaxValue) PrintResult("-5I * -3S", -5I * -3S) PrintResult("-5I * 24US", -5I * 24US) PrintResult("-5I * -5I", -5I * -5I) PrintResult("-5I * 26UI", -5I * 26UI) PrintResult("-5I * -7L", -5I * -7L) PrintResult("-5I * 28UL", -5I * 28UL) PrintResult("-5I * -9D", -5I * -9D) PrintResult("-5I * 10.0F", -5I * 10.0F) PrintResult("-5I * -11.0R", -5I * -11.0R) PrintResult("-5I * ""12""", -5I * "12") PrintResult("-5I * TypeCode.Double", -5I * TypeCode.Double) PrintResult("26UI * False", 26UI * False) PrintResult("26UI * True", 26UI * True) PrintResult("26UI * System.SByte.MinValue", 26UI * System.SByte.MinValue) PrintResult("26UI * System.Byte.MaxValue", 26UI * System.Byte.MaxValue) PrintResult("26UI * -3S", 26UI * -3S) PrintResult("26UI * 24US", 26UI * 24US) PrintResult("26UI * -5I", 26UI * -5I) PrintResult("26UI * 26UI", 26UI * 26UI) PrintResult("26UI * -7L", 26UI * -7L) PrintResult("26UI * 28UL", 26UI * 28UL) PrintResult("26UI * -9D", 26UI * -9D) PrintResult("26UI * 10.0F", 26UI * 10.0F) PrintResult("26UI * -11.0R", 26UI * -11.0R) PrintResult("26UI * ""12""", 26UI * "12") PrintResult("26UI * TypeCode.Double", 26UI * TypeCode.Double) PrintResult("-7L * False", -7L * False) PrintResult("-7L * True", -7L * True) PrintResult("-7L * System.SByte.MinValue", -7L * System.SByte.MinValue) PrintResult("-7L * System.Byte.MaxValue", -7L * System.Byte.MaxValue) PrintResult("-7L * -3S", -7L * -3S) PrintResult("-7L * 24US", -7L * 24US) PrintResult("-7L * -5I", -7L * -5I) PrintResult("-7L * 26UI", -7L * 26UI) PrintResult("-7L * -7L", -7L * -7L) PrintResult("-7L * 28UL", -7L * 28UL) PrintResult("-7L * -9D", -7L * -9D) PrintResult("-7L * 10.0F", -7L * 10.0F) PrintResult("-7L * -11.0R", -7L * -11.0R) PrintResult("-7L * ""12""", -7L * "12") PrintResult("-7L * TypeCode.Double", -7L * TypeCode.Double) PrintResult("28UL * False", 28UL * False) PrintResult("28UL * True", 28UL * True) PrintResult("28UL * System.SByte.MinValue", 28UL * System.SByte.MinValue) PrintResult("28UL * System.Byte.MaxValue", 28UL * System.Byte.MaxValue) PrintResult("28UL * -3S", 28UL * -3S) PrintResult("28UL * 24US", 28UL * 24US) PrintResult("28UL * -5I", 28UL * -5I) PrintResult("28UL * 26UI", 28UL * 26UI) PrintResult("28UL * -7L", 28UL * -7L) PrintResult("28UL * 28UL", 28UL * 28UL) PrintResult("28UL * -9D", 28UL * -9D) PrintResult("28UL * 10.0F", 28UL * 10.0F) PrintResult("28UL * -11.0R", 28UL * -11.0R) PrintResult("28UL * ""12""", 28UL * "12") PrintResult("28UL * TypeCode.Double", 28UL * TypeCode.Double) PrintResult("-9D * False", -9D * False) PrintResult("-9D * True", -9D * True) PrintResult("-9D * System.SByte.MinValue", -9D * System.SByte.MinValue) PrintResult("-9D * System.Byte.MaxValue", -9D * System.Byte.MaxValue) PrintResult("-9D * -3S", -9D * -3S) PrintResult("-9D * 24US", -9D * 24US) PrintResult("-9D * -5I", -9D * -5I) PrintResult("-9D * 26UI", -9D * 26UI) PrintResult("-9D * -7L", -9D * -7L) PrintResult("-9D * 28UL", -9D * 28UL) PrintResult("-9D * -9D", -9D * -9D) PrintResult("-9D * 10.0F", -9D * 10.0F) PrintResult("-9D * -11.0R", -9D * -11.0R) PrintResult("-9D * ""12""", -9D * "12") PrintResult("-9D * TypeCode.Double", -9D * TypeCode.Double) PrintResult("10.0F * False", 10.0F * False) PrintResult("10.0F * True", 10.0F * True) PrintResult("10.0F * System.SByte.MinValue", 10.0F * System.SByte.MinValue) PrintResult("10.0F * System.Byte.MaxValue", 10.0F * System.Byte.MaxValue) PrintResult("10.0F * -3S", 10.0F * -3S) PrintResult("10.0F * 24US", 10.0F * 24US) PrintResult("10.0F * -5I", 10.0F * -5I) PrintResult("10.0F * 26UI", 10.0F * 26UI) PrintResult("10.0F * -7L", 10.0F * -7L) PrintResult("10.0F * 28UL", 10.0F * 28UL) PrintResult("10.0F * -9D", 10.0F * -9D) PrintResult("10.0F * 10.0F", 10.0F * 10.0F) PrintResult("10.0F * -11.0R", 10.0F * -11.0R) PrintResult("10.0F * ""12""", 10.0F * "12") PrintResult("10.0F * TypeCode.Double", 10.0F * TypeCode.Double) PrintResult("-11.0R * False", -11.0R * False) PrintResult("-11.0R * True", -11.0R * True) PrintResult("-11.0R * System.SByte.MinValue", -11.0R * System.SByte.MinValue) PrintResult("-11.0R * System.Byte.MaxValue", -11.0R * System.Byte.MaxValue) PrintResult("-11.0R * -3S", -11.0R * -3S) PrintResult("-11.0R * 24US", -11.0R * 24US) PrintResult("-11.0R * -5I", -11.0R * -5I) PrintResult("-11.0R * 26UI", -11.0R * 26UI) PrintResult("-11.0R * -7L", -11.0R * -7L) PrintResult("-11.0R * 28UL", -11.0R * 28UL) PrintResult("-11.0R * -9D", -11.0R * -9D) PrintResult("-11.0R * 10.0F", -11.0R * 10.0F) PrintResult("-11.0R * -11.0R", -11.0R * -11.0R) PrintResult("-11.0R * ""12""", -11.0R * "12") PrintResult("-11.0R * TypeCode.Double", -11.0R * TypeCode.Double) PrintResult("""12"" * False", "12" * False) PrintResult("""12"" * True", "12" * True) PrintResult("""12"" * System.SByte.MinValue", "12" * System.SByte.MinValue) PrintResult("""12"" * System.Byte.MaxValue", "12" * System.Byte.MaxValue) PrintResult("""12"" * -3S", "12" * -3S) PrintResult("""12"" * 24US", "12" * 24US) PrintResult("""12"" * -5I", "12" * -5I) PrintResult("""12"" * 26UI", "12" * 26UI) PrintResult("""12"" * -7L", "12" * -7L) PrintResult("""12"" * 28UL", "12" * 28UL) PrintResult("""12"" * -9D", "12" * -9D) PrintResult("""12"" * 10.0F", "12" * 10.0F) PrintResult("""12"" * -11.0R", "12" * -11.0R) PrintResult("""12"" * ""12""", "12" * "12") PrintResult("""12"" * TypeCode.Double", "12" * TypeCode.Double) PrintResult("TypeCode.Double * False", TypeCode.Double * False) PrintResult("TypeCode.Double * True", TypeCode.Double * True) PrintResult("TypeCode.Double * System.SByte.MinValue", TypeCode.Double * System.SByte.MinValue) PrintResult("TypeCode.Double * System.Byte.MaxValue", TypeCode.Double * System.Byte.MaxValue) PrintResult("TypeCode.Double * -3S", TypeCode.Double * -3S) PrintResult("TypeCode.Double * 24US", TypeCode.Double * 24US) PrintResult("TypeCode.Double * -5I", TypeCode.Double * -5I) PrintResult("TypeCode.Double * 26UI", TypeCode.Double * 26UI) PrintResult("TypeCode.Double * -7L", TypeCode.Double * -7L) PrintResult("TypeCode.Double * 28UL", TypeCode.Double * 28UL) PrintResult("TypeCode.Double * -9D", TypeCode.Double * -9D) PrintResult("TypeCode.Double * 10.0F", TypeCode.Double * 10.0F) PrintResult("TypeCode.Double * -11.0R", TypeCode.Double * -11.0R) PrintResult("TypeCode.Double * ""12""", TypeCode.Double * "12") PrintResult("TypeCode.Double * TypeCode.Double", TypeCode.Double * TypeCode.Double) PrintResult("False / False", False / False) PrintResult("False / True", False / True) PrintResult("False / System.SByte.MinValue", False / System.SByte.MinValue) PrintResult("False / System.Byte.MaxValue", False / System.Byte.MaxValue) PrintResult("False / -3S", False / -3S) PrintResult("False / 24US", False / 24US) PrintResult("False / -5I", False / -5I) PrintResult("False / 26UI", False / 26UI) PrintResult("False / -7L", False / -7L) PrintResult("False / 28UL", False / 28UL) PrintResult("False / -9D", False / -9D) PrintResult("False / 10.0F", False / 10.0F) PrintResult("False / -11.0R", False / -11.0R) PrintResult("False / ""12""", False / "12") PrintResult("False / TypeCode.Double", False / TypeCode.Double) PrintResult("True / False", True / False) PrintResult("True / True", True / True) PrintResult("True / System.SByte.MinValue", True / System.SByte.MinValue) PrintResult("True / System.Byte.MaxValue", True / System.Byte.MaxValue) PrintResult("True / -3S", True / -3S) PrintResult("True / 24US", True / 24US) PrintResult("True / -5I", True / -5I) PrintResult("True / 26UI", True / 26UI) PrintResult("True / -7L", True / -7L) PrintResult("True / 28UL", True / 28UL) PrintResult("True / -9D", True / -9D) PrintResult("True / 10.0F", True / 10.0F) PrintResult("True / -11.0R", True / -11.0R) PrintResult("True / ""12""", True / "12") PrintResult("True / TypeCode.Double", True / TypeCode.Double) PrintResult("System.SByte.MinValue / False", System.SByte.MinValue / False) PrintResult("System.SByte.MinValue / True", System.SByte.MinValue / True) PrintResult("System.SByte.MinValue / System.SByte.MinValue", System.SByte.MinValue / System.SByte.MinValue) PrintResult("System.SByte.MinValue / System.Byte.MaxValue", System.SByte.MinValue / System.Byte.MaxValue) PrintResult("System.SByte.MinValue / -3S", System.SByte.MinValue / -3S) PrintResult("System.SByte.MinValue / 24US", System.SByte.MinValue / 24US) PrintResult("System.SByte.MinValue / -5I", System.SByte.MinValue / -5I) PrintResult("System.SByte.MinValue / 26UI", System.SByte.MinValue / 26UI) PrintResult("System.SByte.MinValue / -7L", System.SByte.MinValue / -7L) PrintResult("System.SByte.MinValue / 28UL", System.SByte.MinValue / 28UL) PrintResult("System.SByte.MinValue / -9D", System.SByte.MinValue / -9D) PrintResult("System.SByte.MinValue / 10.0F", System.SByte.MinValue / 10.0F) PrintResult("System.SByte.MinValue / -11.0R", System.SByte.MinValue / -11.0R) PrintResult("System.SByte.MinValue / ""12""", System.SByte.MinValue / "12") PrintResult("System.SByte.MinValue / TypeCode.Double", System.SByte.MinValue / TypeCode.Double) PrintResult("System.Byte.MaxValue / False", System.Byte.MaxValue / False) PrintResult("System.Byte.MaxValue / True", System.Byte.MaxValue / True) PrintResult("System.Byte.MaxValue / System.SByte.MinValue", System.Byte.MaxValue / System.SByte.MinValue) PrintResult("System.Byte.MaxValue / System.Byte.MaxValue", System.Byte.MaxValue / System.Byte.MaxValue) PrintResult("System.Byte.MaxValue / -3S", System.Byte.MaxValue / -3S) PrintResult("System.Byte.MaxValue / 24US", System.Byte.MaxValue / 24US) PrintResult("System.Byte.MaxValue / -5I", System.Byte.MaxValue / -5I) PrintResult("System.Byte.MaxValue / 26UI", System.Byte.MaxValue / 26UI) PrintResult("System.Byte.MaxValue / -7L", System.Byte.MaxValue / -7L) PrintResult("System.Byte.MaxValue / 28UL", System.Byte.MaxValue / 28UL) PrintResult("System.Byte.MaxValue / -9D", System.Byte.MaxValue / -9D) PrintResult("System.Byte.MaxValue / 10.0F", System.Byte.MaxValue / 10.0F) PrintResult("System.Byte.MaxValue / -11.0R", System.Byte.MaxValue / -11.0R) PrintResult("System.Byte.MaxValue / ""12""", System.Byte.MaxValue / "12") PrintResult("System.Byte.MaxValue / TypeCode.Double", System.Byte.MaxValue / TypeCode.Double) PrintResult("-3S / False", -3S / False) PrintResult("-3S / True", -3S / True) PrintResult("-3S / System.SByte.MinValue", -3S / System.SByte.MinValue) PrintResult("-3S / System.Byte.MaxValue", -3S / System.Byte.MaxValue) PrintResult("-3S / -3S", -3S / -3S) PrintResult("-3S / 24US", -3S / 24US) PrintResult("-3S / -5I", -3S / -5I) PrintResult("-3S / 26UI", -3S / 26UI) PrintResult("-3S / -7L", -3S / -7L) PrintResult("-3S / 28UL", -3S / 28UL) PrintResult("-3S / -9D", -3S / -9D) PrintResult("-3S / 10.0F", -3S / 10.0F) PrintResult("-3S / -11.0R", -3S / -11.0R) PrintResult("-3S / ""12""", -3S / "12") PrintResult("-3S / TypeCode.Double", -3S / TypeCode.Double) PrintResult("24US / False", 24US / False) PrintResult("24US / True", 24US / True) PrintResult("24US / System.SByte.MinValue", 24US / System.SByte.MinValue) PrintResult("24US / System.Byte.MaxValue", 24US / System.Byte.MaxValue) PrintResult("24US / -3S", 24US / -3S) PrintResult("24US / 24US", 24US / 24US) PrintResult("24US / -5I", 24US / -5I) PrintResult("24US / 26UI", 24US / 26UI) PrintResult("24US / -7L", 24US / -7L) PrintResult("24US / 28UL", 24US / 28UL) PrintResult("24US / -9D", 24US / -9D) PrintResult("24US / 10.0F", 24US / 10.0F) PrintResult("24US / -11.0R", 24US / -11.0R) PrintResult("24US / ""12""", 24US / "12") PrintResult("24US / TypeCode.Double", 24US / TypeCode.Double) PrintResult("-5I / False", -5I / False) PrintResult("-5I / True", -5I / True) PrintResult("-5I / System.SByte.MinValue", -5I / System.SByte.MinValue) PrintResult("-5I / System.Byte.MaxValue", -5I / System.Byte.MaxValue) PrintResult("-5I / -3S", -5I / -3S) PrintResult("-5I / 24US", -5I / 24US) PrintResult("-5I / -5I", -5I / -5I) PrintResult("-5I / 26UI", -5I / 26UI) PrintResult("-5I / -7L", -5I / -7L) PrintResult("-5I / 28UL", -5I / 28UL) PrintResult("-5I / -9D", -5I / -9D) PrintResult("-5I / 10.0F", -5I / 10.0F) PrintResult("-5I / -11.0R", -5I / -11.0R) PrintResult("-5I / ""12""", -5I / "12") PrintResult("-5I / TypeCode.Double", -5I / TypeCode.Double) PrintResult("26UI / False", 26UI / False) PrintResult("26UI / True", 26UI / True) PrintResult("26UI / System.SByte.MinValue", 26UI / System.SByte.MinValue) PrintResult("26UI / System.Byte.MaxValue", 26UI / System.Byte.MaxValue) PrintResult("26UI / -3S", 26UI / -3S) PrintResult("26UI / 24US", 26UI / 24US) PrintResult("26UI / -5I", 26UI / -5I) PrintResult("26UI / 26UI", 26UI / 26UI) PrintResult("26UI / -7L", 26UI / -7L) PrintResult("26UI / 28UL", 26UI / 28UL) PrintResult("26UI / -9D", 26UI / -9D) PrintResult("26UI / 10.0F", 26UI / 10.0F) PrintResult("26UI / -11.0R", 26UI / -11.0R) PrintResult("26UI / ""12""", 26UI / "12") PrintResult("26UI / TypeCode.Double", 26UI / TypeCode.Double) PrintResult("-7L / False", -7L / False) PrintResult("-7L / True", -7L / True) PrintResult("-7L / System.SByte.MinValue", -7L / System.SByte.MinValue) PrintResult("-7L / System.Byte.MaxValue", -7L / System.Byte.MaxValue) PrintResult("-7L / -3S", -7L / -3S) PrintResult("-7L / 24US", -7L / 24US) PrintResult("-7L / -5I", -7L / -5I) PrintResult("-7L / 26UI", -7L / 26UI) PrintResult("-7L / -7L", -7L / -7L) PrintResult("-7L / 28UL", -7L / 28UL) PrintResult("-7L / -9D", -7L / -9D) PrintResult("-7L / 10.0F", -7L / 10.0F) PrintResult("-7L / -11.0R", -7L / -11.0R) PrintResult("-7L / ""12""", -7L / "12") PrintResult("-7L / TypeCode.Double", -7L / TypeCode.Double) PrintResult("28UL / False", 28UL / False) PrintResult("28UL / True", 28UL / True) PrintResult("28UL / System.SByte.MinValue", 28UL / System.SByte.MinValue) PrintResult("28UL / System.Byte.MaxValue", 28UL / System.Byte.MaxValue) PrintResult("28UL / -3S", 28UL / -3S) PrintResult("28UL / 24US", 28UL / 24US) PrintResult("28UL / -5I", 28UL / -5I) PrintResult("28UL / 26UI", 28UL / 26UI) PrintResult("28UL / -7L", 28UL / -7L) PrintResult("28UL / 28UL", 28UL / 28UL) PrintResult("28UL / -9D", 28UL / -9D) PrintResult("28UL / 10.0F", 28UL / 10.0F) PrintResult("28UL / -11.0R", 28UL / -11.0R) PrintResult("28UL / ""12""", 28UL / "12") PrintResult("28UL / TypeCode.Double", 28UL / TypeCode.Double) PrintResult("-9D / True", -9D / True) PrintResult("-9D / System.SByte.MinValue", -9D / System.SByte.MinValue) PrintResult("-9D / System.Byte.MaxValue", -9D / System.Byte.MaxValue) PrintResult("-9D / -3S", -9D / -3S) PrintResult("-9D / 24US", -9D / 24US) PrintResult("-9D / -5I", -9D / -5I) PrintResult("-9D / 26UI", -9D / 26UI) PrintResult("-9D / -7L", -9D / -7L) PrintResult("-9D / 28UL", -9D / 28UL) PrintResult("-9D / -9D", -9D / -9D) PrintResult("-9D / 10.0F", -9D / 10.0F) PrintResult("-9D / -11.0R", -9D / -11.0R) PrintResult("-9D / ""12""", -9D / "12") PrintResult("-9D / TypeCode.Double", -9D / TypeCode.Double) PrintResult("10.0F / False", 10.0F / False) PrintResult("10.0F / True", 10.0F / True) PrintResult("10.0F / System.SByte.MinValue", 10.0F / System.SByte.MinValue) PrintResult("10.0F / System.Byte.MaxValue", 10.0F / System.Byte.MaxValue) PrintResult("10.0F / -3S", 10.0F / -3S) PrintResult("10.0F / 24US", 10.0F / 24US) PrintResult("10.0F / -5I", 10.0F / -5I) PrintResult("10.0F / 26UI", 10.0F / 26UI) PrintResult("10.0F / -7L", 10.0F / -7L) PrintResult("10.0F / 28UL", 10.0F / 28UL) PrintResult("10.0F / -9D", 10.0F / -9D) PrintResult("10.0F / 10.0F", 10.0F / 10.0F) PrintResult("10.0F / -11.0R", 10.0F / -11.0R) PrintResult("10.0F / ""12""", 10.0F / "12") PrintResult("10.0F / TypeCode.Double", 10.0F / TypeCode.Double) PrintResult("-11.0R / False", -11.0R / False) PrintResult("-11.0R / True", -11.0R / True) PrintResult("-11.0R / System.SByte.MinValue", -11.0R / System.SByte.MinValue) PrintResult("-11.0R / System.Byte.MaxValue", -11.0R / System.Byte.MaxValue) PrintResult("-11.0R / -3S", -11.0R / -3S) PrintResult("-11.0R / 24US", -11.0R / 24US) PrintResult("-11.0R / -5I", -11.0R / -5I) PrintResult("-11.0R / 26UI", -11.0R / 26UI) PrintResult("-11.0R / -7L", -11.0R / -7L) PrintResult("-11.0R / 28UL", -11.0R / 28UL) PrintResult("-11.0R / -9D", -11.0R / -9D) PrintResult("-11.0R / 10.0F", -11.0R / 10.0F) PrintResult("-11.0R / -11.0R", -11.0R / -11.0R) PrintResult("-11.0R / ""12""", -11.0R / "12") PrintResult("-11.0R / TypeCode.Double", -11.0R / TypeCode.Double) PrintResult("""12"" / False", "12" / False) PrintResult("""12"" / True", "12" / True) PrintResult("""12"" / System.SByte.MinValue", "12" / System.SByte.MinValue) PrintResult("""12"" / System.Byte.MaxValue", "12" / System.Byte.MaxValue) PrintResult("""12"" / -3S", "12" / -3S) PrintResult("""12"" / 24US", "12" / 24US) PrintResult("""12"" / -5I", "12" / -5I) PrintResult("""12"" / 26UI", "12" / 26UI) PrintResult("""12"" / -7L", "12" / -7L) PrintResult("""12"" / 28UL", "12" / 28UL) PrintResult("""12"" / -9D", "12" / -9D) PrintResult("""12"" / 10.0F", "12" / 10.0F) PrintResult("""12"" / -11.0R", "12" / -11.0R) PrintResult("""12"" / ""12""", "12" / "12") PrintResult("""12"" / TypeCode.Double", "12" / TypeCode.Double) PrintResult("TypeCode.Double / False", TypeCode.Double / False) PrintResult("TypeCode.Double / True", TypeCode.Double / True) PrintResult("TypeCode.Double / System.SByte.MinValue", TypeCode.Double / System.SByte.MinValue) PrintResult("TypeCode.Double / System.Byte.MaxValue", TypeCode.Double / System.Byte.MaxValue) PrintResult("TypeCode.Double / -3S", TypeCode.Double / -3S) PrintResult("TypeCode.Double / 24US", TypeCode.Double / 24US) PrintResult("TypeCode.Double / -5I", TypeCode.Double / -5I) PrintResult("TypeCode.Double / 26UI", TypeCode.Double / 26UI) PrintResult("TypeCode.Double / -7L", TypeCode.Double / -7L) PrintResult("TypeCode.Double / 28UL", TypeCode.Double / 28UL) PrintResult("TypeCode.Double / -9D", TypeCode.Double / -9D) PrintResult("TypeCode.Double / 10.0F", TypeCode.Double / 10.0F) PrintResult("TypeCode.Double / -11.0R", TypeCode.Double / -11.0R) PrintResult("TypeCode.Double / ""12""", TypeCode.Double / "12") PrintResult("TypeCode.Double / TypeCode.Double", TypeCode.Double / TypeCode.Double) PrintResult("False \ True", False \ True) PrintResult("False \ System.SByte.MinValue", False \ System.SByte.MinValue) PrintResult("False \ System.Byte.MaxValue", False \ System.Byte.MaxValue) PrintResult("False \ -3S", False \ -3S) PrintResult("False \ 24US", False \ 24US) PrintResult("False \ -5I", False \ -5I) PrintResult("False \ 26UI", False \ 26UI) PrintResult("False \ -7L", False \ -7L) PrintResult("False \ 28UL", False \ 28UL) PrintResult("False \ -9D", False \ -9D) PrintResult("False \ 10.0F", False \ 10.0F) PrintResult("False \ -11.0R", False \ -11.0R) PrintResult("False \ ""12""", False \ "12") PrintResult("False \ TypeCode.Double", False \ TypeCode.Double) PrintResult("True \ True", True \ True) PrintResult("True \ System.SByte.MinValue", True \ System.SByte.MinValue) PrintResult("True \ System.Byte.MaxValue", True \ System.Byte.MaxValue) PrintResult("True \ -3S", True \ -3S) PrintResult("True \ 24US", True \ 24US) PrintResult("True \ -5I", True \ -5I) PrintResult("True \ 26UI", True \ 26UI) PrintResult("True \ -7L", True \ -7L) PrintResult("True \ 28UL", True \ 28UL) PrintResult("True \ -9D", True \ -9D) PrintResult("True \ 10.0F", True \ 10.0F) PrintResult("True \ -11.0R", True \ -11.0R) PrintResult("True \ ""12""", True \ "12") PrintResult("True \ TypeCode.Double", True \ TypeCode.Double) PrintResult("System.SByte.MaxValue \ True", System.SByte.MaxValue \ True) PrintResult("System.SByte.MinValue \ System.SByte.MinValue", System.SByte.MinValue \ System.SByte.MinValue) PrintResult("System.SByte.MinValue \ System.Byte.MaxValue", System.SByte.MinValue \ System.Byte.MaxValue) PrintResult("System.SByte.MinValue \ -3S", System.SByte.MinValue \ -3S) PrintResult("System.SByte.MinValue \ 24US", System.SByte.MinValue \ 24US) PrintResult("System.SByte.MinValue \ -5I", System.SByte.MinValue \ -5I) PrintResult("System.SByte.MinValue \ 26UI", System.SByte.MinValue \ 26UI) PrintResult("System.SByte.MinValue \ -7L", System.SByte.MinValue \ -7L) PrintResult("System.SByte.MinValue \ 28UL", System.SByte.MinValue \ 28UL) PrintResult("System.SByte.MinValue \ -9D", System.SByte.MinValue \ -9D) PrintResult("System.SByte.MinValue \ 10.0F", System.SByte.MinValue \ 10.0F) PrintResult("System.SByte.MinValue \ -11.0R", System.SByte.MinValue \ -11.0R) PrintResult("System.SByte.MinValue \ ""12""", System.SByte.MinValue \ "12") PrintResult("System.SByte.MinValue \ TypeCode.Double", System.SByte.MinValue \ TypeCode.Double) PrintResult("System.Byte.MaxValue \ True", System.Byte.MaxValue \ True) PrintResult("System.Byte.MaxValue \ System.SByte.MinValue", System.Byte.MaxValue \ System.SByte.MinValue) PrintResult("System.Byte.MaxValue \ System.Byte.MaxValue", System.Byte.MaxValue \ System.Byte.MaxValue) PrintResult("System.Byte.MaxValue \ -3S", System.Byte.MaxValue \ -3S) PrintResult("System.Byte.MaxValue \ 24US", System.Byte.MaxValue \ 24US) PrintResult("System.Byte.MaxValue \ -5I", System.Byte.MaxValue \ -5I) PrintResult("System.Byte.MaxValue \ 26UI", System.Byte.MaxValue \ 26UI) PrintResult("System.Byte.MaxValue \ -7L", System.Byte.MaxValue \ -7L) PrintResult("System.Byte.MaxValue \ 28UL", System.Byte.MaxValue \ 28UL) PrintResult("System.Byte.MaxValue \ -9D", System.Byte.MaxValue \ -9D) PrintResult("System.Byte.MaxValue \ 10.0F", System.Byte.MaxValue \ 10.0F) PrintResult("System.Byte.MaxValue \ -11.0R", System.Byte.MaxValue \ -11.0R) PrintResult("System.Byte.MaxValue \ ""12""", System.Byte.MaxValue \ "12") PrintResult("System.Byte.MaxValue \ TypeCode.Double", System.Byte.MaxValue \ TypeCode.Double) PrintResult("-3S \ True", -3S \ True) PrintResult("-3S \ System.SByte.MinValue", -3S \ System.SByte.MinValue) PrintResult("-3S \ System.Byte.MaxValue", -3S \ System.Byte.MaxValue) PrintResult("-3S \ -3S", -3S \ -3S) PrintResult("-3S \ 24US", -3S \ 24US) PrintResult("-3S \ -5I", -3S \ -5I) PrintResult("-3S \ 26UI", -3S \ 26UI) PrintResult("-3S \ -7L", -3S \ -7L) PrintResult("-3S \ 28UL", -3S \ 28UL) PrintResult("-3S \ -9D", -3S \ -9D) PrintResult("-3S \ 10.0F", -3S \ 10.0F) PrintResult("-3S \ -11.0R", -3S \ -11.0R) PrintResult("-3S \ ""12""", -3S \ "12") PrintResult("-3S \ TypeCode.Double", -3S \ TypeCode.Double) PrintResult("24US \ True", 24US \ True) PrintResult("24US \ System.SByte.MinValue", 24US \ System.SByte.MinValue) PrintResult("24US \ System.Byte.MaxValue", 24US \ System.Byte.MaxValue) PrintResult("24US \ -3S", 24US \ -3S) PrintResult("24US \ 24US", 24US \ 24US) PrintResult("24US \ -5I", 24US \ -5I) PrintResult("24US \ 26UI", 24US \ 26UI) PrintResult("24US \ -7L", 24US \ -7L) PrintResult("24US \ 28UL", 24US \ 28UL) PrintResult("24US \ -9D", 24US \ -9D) PrintResult("24US \ 10.0F", 24US \ 10.0F) PrintResult("24US \ -11.0R", 24US \ -11.0R) PrintResult("24US \ ""12""", 24US \ "12") PrintResult("24US \ TypeCode.Double", 24US \ TypeCode.Double) PrintResult("-5I \ True", -5I \ True) PrintResult("-5I \ System.SByte.MinValue", -5I \ System.SByte.MinValue) PrintResult("-5I \ System.Byte.MaxValue", -5I \ System.Byte.MaxValue) PrintResult("-5I \ -3S", -5I \ -3S) PrintResult("-5I \ 24US", -5I \ 24US) PrintResult("-5I \ -5I", -5I \ -5I) PrintResult("-5I \ 26UI", -5I \ 26UI) PrintResult("-5I \ -7L", -5I \ -7L) PrintResult("-5I \ 28UL", -5I \ 28UL) PrintResult("-5I \ -9D", -5I \ -9D) PrintResult("-5I \ 10.0F", -5I \ 10.0F) PrintResult("-5I \ -11.0R", -5I \ -11.0R) PrintResult("-5I \ ""12""", -5I \ "12") PrintResult("-5I \ TypeCode.Double", -5I \ TypeCode.Double) PrintResult("26UI \ True", 26UI \ True) PrintResult("26UI \ System.SByte.MinValue", 26UI \ System.SByte.MinValue) PrintResult("26UI \ System.Byte.MaxValue", 26UI \ System.Byte.MaxValue) PrintResult("26UI \ -3S", 26UI \ -3S) PrintResult("26UI \ 24US", 26UI \ 24US) PrintResult("26UI \ -5I", 26UI \ -5I) PrintResult("26UI \ 26UI", 26UI \ 26UI) PrintResult("26UI \ -7L", 26UI \ -7L) PrintResult("26UI \ 28UL", 26UI \ 28UL) PrintResult("26UI \ -9D", 26UI \ -9D) PrintResult("26UI \ 10.0F", 26UI \ 10.0F) PrintResult("26UI \ -11.0R", 26UI \ -11.0R) PrintResult("26UI \ ""12""", 26UI \ "12") PrintResult("26UI \ TypeCode.Double", 26UI \ TypeCode.Double) PrintResult("-7L \ True", -7L \ True) PrintResult("-7L \ System.SByte.MinValue", -7L \ System.SByte.MinValue) PrintResult("-7L \ System.Byte.MaxValue", -7L \ System.Byte.MaxValue) PrintResult("-7L \ -3S", -7L \ -3S) PrintResult("-7L \ 24US", -7L \ 24US) PrintResult("-7L \ -5I", -7L \ -5I) PrintResult("-7L \ 26UI", -7L \ 26UI) PrintResult("-7L \ -7L", -7L \ -7L) PrintResult("-7L \ 28UL", -7L \ 28UL) PrintResult("-7L \ -9D", -7L \ -9D) PrintResult("-7L \ 10.0F", -7L \ 10.0F) PrintResult("-7L \ -11.0R", -7L \ -11.0R) PrintResult("-7L \ ""12""", -7L \ "12") PrintResult("-7L \ TypeCode.Double", -7L \ TypeCode.Double) PrintResult("28UL \ True", 28UL \ True) PrintResult("28UL \ System.SByte.MinValue", 28UL \ System.SByte.MinValue) PrintResult("28UL \ System.Byte.MaxValue", 28UL \ System.Byte.MaxValue) PrintResult("28UL \ -3S", 28UL \ -3S) PrintResult("28UL \ 24US", 28UL \ 24US) PrintResult("28UL \ -5I", 28UL \ -5I) PrintResult("28UL \ 26UI", 28UL \ 26UI) PrintResult("28UL \ -7L", 28UL \ -7L) PrintResult("28UL \ 28UL", 28UL \ 28UL) PrintResult("28UL \ -9D", 28UL \ -9D) PrintResult("28UL \ 10.0F", 28UL \ 10.0F) PrintResult("28UL \ -11.0R", 28UL \ -11.0R) PrintResult("28UL \ ""12""", 28UL \ "12") PrintResult("28UL \ TypeCode.Double", 28UL \ TypeCode.Double) PrintResult("-9D \ True", -9D \ True) PrintResult("-9D \ System.SByte.MinValue", -9D \ System.SByte.MinValue) PrintResult("-9D \ System.Byte.MaxValue", -9D \ System.Byte.MaxValue) PrintResult("-9D \ -3S", -9D \ -3S) PrintResult("-9D \ 24US", -9D \ 24US) PrintResult("-9D \ -5I", -9D \ -5I) PrintResult("-9D \ 26UI", -9D \ 26UI) PrintResult("-9D \ -7L", -9D \ -7L) PrintResult("-9D \ 28UL", -9D \ 28UL) PrintResult("-9D \ -9D", -9D \ -9D) PrintResult("-9D \ 10.0F", -9D \ 10.0F) PrintResult("-9D \ -11.0R", -9D \ -11.0R) PrintResult("-9D \ ""12""", -9D \ "12") PrintResult("-9D \ TypeCode.Double", -9D \ TypeCode.Double) PrintResult("10.0F \ True", 10.0F \ True) PrintResult("10.0F \ System.SByte.MinValue", 10.0F \ System.SByte.MinValue) PrintResult("10.0F \ System.Byte.MaxValue", 10.0F \ System.Byte.MaxValue) PrintResult("10.0F \ -3S", 10.0F \ -3S) PrintResult("10.0F \ 24US", 10.0F \ 24US) PrintResult("10.0F \ -5I", 10.0F \ -5I) PrintResult("10.0F \ 26UI", 10.0F \ 26UI) PrintResult("10.0F \ -7L", 10.0F \ -7L) PrintResult("10.0F \ 28UL", 10.0F \ 28UL) PrintResult("10.0F \ -9D", 10.0F \ -9D) PrintResult("10.0F \ 10.0F", 10.0F \ 10.0F) PrintResult("10.0F \ -11.0R", 10.0F \ -11.0R) PrintResult("10.0F \ ""12""", 10.0F \ "12") PrintResult("10.0F \ TypeCode.Double", 10.0F \ TypeCode.Double) PrintResult("-11.0R \ True", -11.0R \ True) PrintResult("-11.0R \ System.SByte.MinValue", -11.0R \ System.SByte.MinValue) PrintResult("-11.0R \ System.Byte.MaxValue", -11.0R \ System.Byte.MaxValue) PrintResult("-11.0R \ -3S", -11.0R \ -3S) PrintResult("-11.0R \ 24US", -11.0R \ 24US) PrintResult("-11.0R \ -5I", -11.0R \ -5I) PrintResult("-11.0R \ 26UI", -11.0R \ 26UI) PrintResult("-11.0R \ -7L", -11.0R \ -7L) PrintResult("-11.0R \ 28UL", -11.0R \ 28UL) PrintResult("-11.0R \ -9D", -11.0R \ -9D) PrintResult("-11.0R \ 10.0F", -11.0R \ 10.0F) PrintResult("-11.0R \ -11.0R", -11.0R \ -11.0R) PrintResult("-11.0R \ ""12""", -11.0R \ "12") PrintResult("-11.0R \ TypeCode.Double", -11.0R \ TypeCode.Double) PrintResult("""12"" \ True", "12" \ True) PrintResult("""12"" \ System.SByte.MinValue", "12" \ System.SByte.MinValue) PrintResult("""12"" \ System.Byte.MaxValue", "12" \ System.Byte.MaxValue) PrintResult("""12"" \ -3S", "12" \ -3S) PrintResult("""12"" \ 24US", "12" \ 24US) PrintResult("""12"" \ -5I", "12" \ -5I) PrintResult("""12"" \ 26UI", "12" \ 26UI) PrintResult("""12"" \ -7L", "12" \ -7L) PrintResult("""12"" \ 28UL", "12" \ 28UL) PrintResult("""12"" \ -9D", "12" \ -9D) PrintResult("""12"" \ 10.0F", "12" \ 10.0F) PrintResult("""12"" \ -11.0R", "12" \ -11.0R) PrintResult("""12"" \ ""12""", "12" \ "12") PrintResult("""12"" \ TypeCode.Double", "12" \ TypeCode.Double) PrintResult("TypeCode.Double \ True", TypeCode.Double \ True) PrintResult("TypeCode.Double \ System.SByte.MinValue", TypeCode.Double \ System.SByte.MinValue) PrintResult("TypeCode.Double \ System.Byte.MaxValue", TypeCode.Double \ System.Byte.MaxValue) PrintResult("TypeCode.Double \ -3S", TypeCode.Double \ -3S) PrintResult("TypeCode.Double \ 24US", TypeCode.Double \ 24US) PrintResult("TypeCode.Double \ -5I", TypeCode.Double \ -5I) PrintResult("TypeCode.Double \ 26UI", TypeCode.Double \ 26UI) PrintResult("TypeCode.Double \ -7L", TypeCode.Double \ -7L) PrintResult("TypeCode.Double \ 28UL", TypeCode.Double \ 28UL) PrintResult("TypeCode.Double \ -9D", TypeCode.Double \ -9D) PrintResult("TypeCode.Double \ 10.0F", TypeCode.Double \ 10.0F) PrintResult("TypeCode.Double \ -11.0R", TypeCode.Double \ -11.0R) PrintResult("TypeCode.Double \ ""12""", TypeCode.Double \ "12") PrintResult("TypeCode.Double \ TypeCode.Double", TypeCode.Double \ TypeCode.Double) PrintResult("False Mod True", False Mod True) PrintResult("False Mod System.SByte.MinValue", False Mod System.SByte.MinValue) PrintResult("False Mod System.Byte.MaxValue", False Mod System.Byte.MaxValue) PrintResult("False Mod -3S", False Mod -3S) PrintResult("False Mod 24US", False Mod 24US) PrintResult("False Mod -5I", False Mod -5I) PrintResult("False Mod 26UI", False Mod 26UI) PrintResult("False Mod -7L", False Mod -7L) PrintResult("False Mod 28UL", False Mod 28UL) PrintResult("False Mod -9D", False Mod -9D) PrintResult("False Mod 10.0F", False Mod 10.0F) PrintResult("False Mod -11.0R", False Mod -11.0R) PrintResult("False Mod ""12""", False Mod "12") PrintResult("False Mod TypeCode.Double", False Mod TypeCode.Double) PrintResult("True Mod True", True Mod True) PrintResult("True Mod System.SByte.MinValue", True Mod System.SByte.MinValue) PrintResult("True Mod System.Byte.MaxValue", True Mod System.Byte.MaxValue) PrintResult("True Mod -3S", True Mod -3S) PrintResult("True Mod 24US", True Mod 24US) PrintResult("True Mod -5I", True Mod -5I) PrintResult("True Mod 26UI", True Mod 26UI) PrintResult("True Mod -7L", True Mod -7L) PrintResult("True Mod 28UL", True Mod 28UL) PrintResult("True Mod -9D", True Mod -9D) PrintResult("True Mod 10.0F", True Mod 10.0F) PrintResult("True Mod -11.0R", True Mod -11.0R) PrintResult("True Mod ""12""", True Mod "12") PrintResult("True Mod TypeCode.Double", True Mod TypeCode.Double) PrintResult("System.SByte.MinValue Mod True", System.SByte.MinValue Mod True) PrintResult("System.SByte.MinValue Mod System.SByte.MinValue", System.SByte.MinValue Mod System.SByte.MinValue) PrintResult("System.SByte.MinValue Mod System.Byte.MaxValue", System.SByte.MinValue Mod System.Byte.MaxValue) PrintResult("System.SByte.MinValue Mod -3S", System.SByte.MinValue Mod -3S) PrintResult("System.SByte.MinValue Mod 24US", System.SByte.MinValue Mod 24US) PrintResult("System.SByte.MinValue Mod -5I", System.SByte.MinValue Mod -5I) PrintResult("System.SByte.MinValue Mod 26UI", System.SByte.MinValue Mod 26UI) PrintResult("System.SByte.MinValue Mod -7L", System.SByte.MinValue Mod -7L) PrintResult("System.SByte.MinValue Mod 28UL", System.SByte.MinValue Mod 28UL) PrintResult("System.SByte.MinValue Mod -9D", System.SByte.MinValue Mod -9D) PrintResult("System.SByte.MinValue Mod 10.0F", System.SByte.MinValue Mod 10.0F) PrintResult("System.SByte.MinValue Mod -11.0R", System.SByte.MinValue Mod -11.0R) PrintResult("System.SByte.MinValue Mod ""12""", System.SByte.MinValue Mod "12") PrintResult("System.SByte.MinValue Mod TypeCode.Double", System.SByte.MinValue Mod TypeCode.Double) PrintResult("System.Byte.MaxValue Mod True", System.Byte.MaxValue Mod True) PrintResult("System.Byte.MaxValue Mod System.SByte.MinValue", System.Byte.MaxValue Mod System.SByte.MinValue) PrintResult("System.Byte.MaxValue Mod System.Byte.MaxValue", System.Byte.MaxValue Mod System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Mod -3S", System.Byte.MaxValue Mod -3S) PrintResult("System.Byte.MaxValue Mod 24US", System.Byte.MaxValue Mod 24US) PrintResult("System.Byte.MaxValue Mod -5I", System.Byte.MaxValue Mod -5I) PrintResult("System.Byte.MaxValue Mod 26UI", System.Byte.MaxValue Mod 26UI) PrintResult("System.Byte.MaxValue Mod -7L", System.Byte.MaxValue Mod -7L) PrintResult("System.Byte.MaxValue Mod 28UL", System.Byte.MaxValue Mod 28UL) PrintResult("System.Byte.MaxValue Mod -9D", System.Byte.MaxValue Mod -9D) PrintResult("System.Byte.MaxValue Mod 10.0F", System.Byte.MaxValue Mod 10.0F) PrintResult("System.Byte.MaxValue Mod -11.0R", System.Byte.MaxValue Mod -11.0R) PrintResult("System.Byte.MaxValue Mod ""12""", System.Byte.MaxValue Mod "12") PrintResult("System.Byte.MaxValue Mod TypeCode.Double", System.Byte.MaxValue Mod TypeCode.Double) PrintResult("-3S Mod True", -3S Mod True) PrintResult("-3S Mod System.SByte.MinValue", -3S Mod System.SByte.MinValue) PrintResult("-3S Mod System.Byte.MaxValue", -3S Mod System.Byte.MaxValue) PrintResult("-3S Mod -3S", -3S Mod -3S) PrintResult("-3S Mod 24US", -3S Mod 24US) PrintResult("-3S Mod -5I", -3S Mod -5I) PrintResult("-3S Mod 26UI", -3S Mod 26UI) PrintResult("-3S Mod -7L", -3S Mod -7L) PrintResult("-3S Mod 28UL", -3S Mod 28UL) PrintResult("-3S Mod -9D", -3S Mod -9D) PrintResult("-3S Mod 10.0F", -3S Mod 10.0F) PrintResult("-3S Mod -11.0R", -3S Mod -11.0R) PrintResult("-3S Mod ""12""", -3S Mod "12") PrintResult("-3S Mod TypeCode.Double", -3S Mod TypeCode.Double) PrintResult("24US Mod True", 24US Mod True) PrintResult("24US Mod System.SByte.MinValue", 24US Mod System.SByte.MinValue) PrintResult("24US Mod System.Byte.MaxValue", 24US Mod System.Byte.MaxValue) PrintResult("24US Mod -3S", 24US Mod -3S) PrintResult("24US Mod 24US", 24US Mod 24US) PrintResult("24US Mod -5I", 24US Mod -5I) PrintResult("24US Mod 26UI", 24US Mod 26UI) PrintResult("24US Mod -7L", 24US Mod -7L) PrintResult("24US Mod 28UL", 24US Mod 28UL) PrintResult("24US Mod -9D", 24US Mod -9D) PrintResult("24US Mod 10.0F", 24US Mod 10.0F) PrintResult("24US Mod -11.0R", 24US Mod -11.0R) PrintResult("24US Mod ""12""", 24US Mod "12") PrintResult("24US Mod TypeCode.Double", 24US Mod TypeCode.Double) PrintResult("-5I Mod True", -5I Mod True) PrintResult("-5I Mod System.SByte.MinValue", -5I Mod System.SByte.MinValue) PrintResult("-5I Mod System.Byte.MaxValue", -5I Mod System.Byte.MaxValue) PrintResult("-5I Mod -3S", -5I Mod -3S) PrintResult("-5I Mod 24US", -5I Mod 24US) PrintResult("-5I Mod -5I", -5I Mod -5I) PrintResult("-5I Mod 26UI", -5I Mod 26UI) PrintResult("-5I Mod -7L", -5I Mod -7L) PrintResult("-5I Mod 28UL", -5I Mod 28UL) PrintResult("-5I Mod -9D", -5I Mod -9D) PrintResult("-5I Mod 10.0F", -5I Mod 10.0F) PrintResult("-5I Mod -11.0R", -5I Mod -11.0R) PrintResult("-5I Mod ""12""", -5I Mod "12") PrintResult("-5I Mod TypeCode.Double", -5I Mod TypeCode.Double) PrintResult("26UI Mod True", 26UI Mod True) PrintResult("26UI Mod System.SByte.MinValue", 26UI Mod System.SByte.MinValue) PrintResult("26UI Mod System.Byte.MaxValue", 26UI Mod System.Byte.MaxValue) PrintResult("26UI Mod -3S", 26UI Mod -3S) PrintResult("26UI Mod 24US", 26UI Mod 24US) PrintResult("26UI Mod -5I", 26UI Mod -5I) PrintResult("26UI Mod 26UI", 26UI Mod 26UI) PrintResult("26UI Mod -7L", 26UI Mod -7L) PrintResult("26UI Mod 28UL", 26UI Mod 28UL) PrintResult("26UI Mod -9D", 26UI Mod -9D) PrintResult("26UI Mod 10.0F", 26UI Mod 10.0F) PrintResult("26UI Mod -11.0R", 26UI Mod -11.0R) PrintResult("26UI Mod ""12""", 26UI Mod "12") PrintResult("26UI Mod TypeCode.Double", 26UI Mod TypeCode.Double) PrintResult("-7L Mod True", -7L Mod True) PrintResult("-7L Mod System.SByte.MinValue", -7L Mod System.SByte.MinValue) PrintResult("-7L Mod System.Byte.MaxValue", -7L Mod System.Byte.MaxValue) PrintResult("-7L Mod -3S", -7L Mod -3S) PrintResult("-7L Mod 24US", -7L Mod 24US) PrintResult("-7L Mod -5I", -7L Mod -5I) PrintResult("-7L Mod 26UI", -7L Mod 26UI) PrintResult("-7L Mod -7L", -7L Mod -7L) PrintResult("-7L Mod 28UL", -7L Mod 28UL) PrintResult("-7L Mod -9D", -7L Mod -9D) PrintResult("-7L Mod 10.0F", -7L Mod 10.0F) PrintResult("-7L Mod -11.0R", -7L Mod -11.0R) PrintResult("-7L Mod ""12""", -7L Mod "12") PrintResult("-7L Mod TypeCode.Double", -7L Mod TypeCode.Double) PrintResult("28UL Mod True", 28UL Mod True) PrintResult("28UL Mod System.SByte.MinValue", 28UL Mod System.SByte.MinValue) PrintResult("28UL Mod System.Byte.MaxValue", 28UL Mod System.Byte.MaxValue) PrintResult("28UL Mod -3S", 28UL Mod -3S) PrintResult("28UL Mod 24US", 28UL Mod 24US) PrintResult("28UL Mod -5I", 28UL Mod -5I) PrintResult("28UL Mod 26UI", 28UL Mod 26UI) PrintResult("28UL Mod -7L", 28UL Mod -7L) PrintResult("28UL Mod 28UL", 28UL Mod 28UL) PrintResult("28UL Mod -9D", 28UL Mod -9D) PrintResult("28UL Mod 10.0F", 28UL Mod 10.0F) PrintResult("28UL Mod -11.0R", 28UL Mod -11.0R) PrintResult("28UL Mod ""12""", 28UL Mod "12") PrintResult("28UL Mod TypeCode.Double", 28UL Mod TypeCode.Double) PrintResult("-9D Mod True", -9D Mod True) PrintResult("-9D Mod System.SByte.MinValue", -9D Mod System.SByte.MinValue) PrintResult("-9D Mod System.Byte.MaxValue", -9D Mod System.Byte.MaxValue) PrintResult("-9D Mod -3S", -9D Mod -3S) PrintResult("-9D Mod 24US", -9D Mod 24US) PrintResult("-9D Mod -5I", -9D Mod -5I) PrintResult("-9D Mod 26UI", -9D Mod 26UI) PrintResult("-9D Mod -7L", -9D Mod -7L) PrintResult("-9D Mod 28UL", -9D Mod 28UL) PrintResult("-9D Mod -9D", -9D Mod -9D) PrintResult("-9D Mod 10.0F", -9D Mod 10.0F) PrintResult("-9D Mod -11.0R", -9D Mod -11.0R) PrintResult("-9D Mod ""12""", -9D Mod "12") PrintResult("-9D Mod TypeCode.Double", -9D Mod TypeCode.Double) PrintResult("10.0F Mod True", 10.0F Mod True) PrintResult("10.0F Mod System.SByte.MinValue", 10.0F Mod System.SByte.MinValue) PrintResult("10.0F Mod System.Byte.MaxValue", 10.0F Mod System.Byte.MaxValue) PrintResult("10.0F Mod -3S", 10.0F Mod -3S) PrintResult("10.0F Mod 24US", 10.0F Mod 24US) PrintResult("10.0F Mod -5I", 10.0F Mod -5I) PrintResult("10.0F Mod 26UI", 10.0F Mod 26UI) PrintResult("10.0F Mod -7L", 10.0F Mod -7L) PrintResult("10.0F Mod 28UL", 10.0F Mod 28UL) PrintResult("10.0F Mod -9D", 10.0F Mod -9D) PrintResult("10.0F Mod 10.0F", 10.0F Mod 10.0F) PrintResult("10.0F Mod -11.0R", 10.0F Mod -11.0R) PrintResult("10.0F Mod ""12""", 10.0F Mod "12") PrintResult("10.0F Mod TypeCode.Double", 10.0F Mod TypeCode.Double) PrintResult("-11.0R Mod True", -11.0R Mod True) PrintResult("-11.0R Mod System.SByte.MinValue", -11.0R Mod System.SByte.MinValue) PrintResult("-11.0R Mod System.Byte.MaxValue", -11.0R Mod System.Byte.MaxValue) PrintResult("-11.0R Mod -3S", -11.0R Mod -3S) PrintResult("-11.0R Mod 24US", -11.0R Mod 24US) PrintResult("-11.0R Mod -5I", -11.0R Mod -5I) PrintResult("-11.0R Mod 26UI", -11.0R Mod 26UI) PrintResult("-11.0R Mod -7L", -11.0R Mod -7L) PrintResult("-11.0R Mod 28UL", -11.0R Mod 28UL) PrintResult("-11.0R Mod -9D", -11.0R Mod -9D) PrintResult("-11.0R Mod 10.0F", -11.0R Mod 10.0F) PrintResult("-11.0R Mod -11.0R", -11.0R Mod -11.0R) PrintResult("-11.0R Mod ""12""", -11.0R Mod "12") PrintResult("-11.0R Mod TypeCode.Double", -11.0R Mod TypeCode.Double) PrintResult("""12"" Mod True", "12" Mod True) PrintResult("""12"" Mod System.SByte.MinValue", "12" Mod System.SByte.MinValue) PrintResult("""12"" Mod System.Byte.MaxValue", "12" Mod System.Byte.MaxValue) PrintResult("""12"" Mod -3S", "12" Mod -3S) PrintResult("""12"" Mod 24US", "12" Mod 24US) PrintResult("""12"" Mod -5I", "12" Mod -5I) PrintResult("""12"" Mod 26UI", "12" Mod 26UI) PrintResult("""12"" Mod -7L", "12" Mod -7L) PrintResult("""12"" Mod 28UL", "12" Mod 28UL) PrintResult("""12"" Mod -9D", "12" Mod -9D) PrintResult("""12"" Mod 10.0F", "12" Mod 10.0F) PrintResult("""12"" Mod -11.0R", "12" Mod -11.0R) PrintResult("""12"" Mod ""12""", "12" Mod "12") PrintResult("""12"" Mod TypeCode.Double", "12" Mod TypeCode.Double) PrintResult("TypeCode.Double Mod True", TypeCode.Double Mod True) PrintResult("TypeCode.Double Mod System.SByte.MinValue", TypeCode.Double Mod System.SByte.MinValue) PrintResult("TypeCode.Double Mod System.Byte.MaxValue", TypeCode.Double Mod System.Byte.MaxValue) PrintResult("TypeCode.Double Mod -3S", TypeCode.Double Mod -3S) PrintResult("TypeCode.Double Mod 24US", TypeCode.Double Mod 24US) PrintResult("TypeCode.Double Mod -5I", TypeCode.Double Mod -5I) PrintResult("TypeCode.Double Mod 26UI", TypeCode.Double Mod 26UI) PrintResult("TypeCode.Double Mod -7L", TypeCode.Double Mod -7L) PrintResult("TypeCode.Double Mod 28UL", TypeCode.Double Mod 28UL) PrintResult("TypeCode.Double Mod -9D", TypeCode.Double Mod -9D) PrintResult("TypeCode.Double Mod 10.0F", TypeCode.Double Mod 10.0F) PrintResult("TypeCode.Double Mod -11.0R", TypeCode.Double Mod -11.0R) PrintResult("TypeCode.Double Mod ""12""", TypeCode.Double Mod "12") PrintResult("TypeCode.Double Mod TypeCode.Double", TypeCode.Double Mod TypeCode.Double) PrintResult("False ^ False", False ^ False) PrintResult("False ^ True", False ^ True) PrintResult("False ^ System.SByte.MinValue", False ^ System.SByte.MinValue) PrintResult("False ^ System.Byte.MaxValue", False ^ System.Byte.MaxValue) PrintResult("False ^ -3S", False ^ -3S) PrintResult("False ^ 24US", False ^ 24US) PrintResult("False ^ -5I", False ^ -5I) PrintResult("False ^ 26UI", False ^ 26UI) PrintResult("False ^ -7L", False ^ -7L) PrintResult("False ^ 28UL", False ^ 28UL) PrintResult("False ^ -9D", False ^ -9D) PrintResult("False ^ 10.0F", False ^ 10.0F) PrintResult("False ^ -11.0R", False ^ -11.0R) PrintResult("False ^ ""12""", False ^ "12") PrintResult("False ^ TypeCode.Double", False ^ TypeCode.Double) PrintResult("True ^ False", True ^ False) PrintResult("True ^ True", True ^ True) PrintResult("True ^ System.SByte.MinValue", True ^ System.SByte.MinValue) PrintResult("True ^ System.Byte.MaxValue", True ^ System.Byte.MaxValue) PrintResult("True ^ -3S", True ^ -3S) PrintResult("True ^ 24US", True ^ 24US) PrintResult("True ^ -5I", True ^ -5I) PrintResult("True ^ 26UI", True ^ 26UI) PrintResult("True ^ -7L", True ^ -7L) PrintResult("True ^ 28UL", True ^ 28UL) PrintResult("True ^ -9D", True ^ -9D) PrintResult("True ^ 10.0F", True ^ 10.0F) PrintResult("True ^ -11.0R", True ^ -11.0R) PrintResult("True ^ ""12""", True ^ "12") PrintResult("True ^ TypeCode.Double", True ^ TypeCode.Double) PrintResult("System.SByte.MinValue ^ False", System.SByte.MinValue ^ False) PrintResult("System.SByte.MinValue ^ True", System.SByte.MinValue ^ True) PrintResult("System.SByte.MinValue ^ System.SByte.MinValue", System.SByte.MinValue ^ System.SByte.MinValue) PrintResult("System.SByte.MinValue ^ System.Byte.MaxValue", System.SByte.MinValue ^ System.Byte.MaxValue) PrintResult("System.SByte.MinValue ^ -3S", System.SByte.MinValue ^ -3S) PrintResult("System.SByte.MinValue ^ 24US", System.SByte.MinValue ^ 24US) PrintResult("System.SByte.MinValue ^ -5I", System.SByte.MinValue ^ -5I) PrintResult("System.SByte.MinValue ^ 26UI", System.SByte.MinValue ^ 26UI) PrintResult("System.SByte.MinValue ^ -7L", System.SByte.MinValue ^ -7L) PrintResult("System.SByte.MinValue ^ 28UL", System.SByte.MinValue ^ 28UL) PrintResult("System.SByte.MinValue ^ -9D", System.SByte.MinValue ^ -9D) PrintResult("System.SByte.MinValue ^ 10.0F", System.SByte.MinValue ^ 10.0F) PrintResult("System.SByte.MinValue ^ -11.0R", System.SByte.MinValue ^ -11.0R) PrintResult("System.SByte.MinValue ^ ""12""", System.SByte.MinValue ^ "12") PrintResult("System.SByte.MinValue ^ TypeCode.Double", System.SByte.MinValue ^ TypeCode.Double) PrintResult("System.Byte.MaxValue ^ False", System.Byte.MaxValue ^ False) PrintResult("System.Byte.MaxValue ^ True", System.Byte.MaxValue ^ True) PrintResult("System.Byte.MaxValue ^ System.SByte.MinValue", System.Byte.MaxValue ^ System.SByte.MinValue) PrintResult("System.Byte.MaxValue ^ System.Byte.MaxValue", System.Byte.MaxValue ^ System.Byte.MaxValue) PrintResult("System.Byte.MaxValue ^ -3S", System.Byte.MaxValue ^ -3S) PrintResult("System.Byte.MaxValue ^ 24US", System.Byte.MaxValue ^ 24US) PrintResult("System.Byte.MaxValue ^ -5I", System.Byte.MaxValue ^ -5I) PrintResult("System.Byte.MaxValue ^ 26UI", System.Byte.MaxValue ^ 26UI) PrintResult("System.Byte.MaxValue ^ -7L", System.Byte.MaxValue ^ -7L) PrintResult("System.Byte.MaxValue ^ 28UL", System.Byte.MaxValue ^ 28UL) PrintResult("System.Byte.MaxValue ^ -9D", System.Byte.MaxValue ^ -9D) PrintResult("System.Byte.MaxValue ^ 10.0F", System.Byte.MaxValue ^ 10.0F) PrintResult("System.Byte.MaxValue ^ -11.0R", System.Byte.MaxValue ^ -11.0R) PrintResult("System.Byte.MaxValue ^ ""12""", System.Byte.MaxValue ^ "12") PrintResult("System.Byte.MaxValue ^ TypeCode.Double", System.Byte.MaxValue ^ TypeCode.Double) PrintResult("-3S ^ False", -3S ^ False) PrintResult("-3S ^ True", -3S ^ True) PrintResult("-3S ^ System.SByte.MinValue", -3S ^ System.SByte.MinValue) PrintResult("-3S ^ System.Byte.MaxValue", -3S ^ System.Byte.MaxValue) PrintResult("-3S ^ -3S", -3S ^ -3S) PrintResult("-3S ^ 24US", -3S ^ 24US) PrintResult("-3S ^ -5I", -3S ^ -5I) PrintResult("-3S ^ 26UI", -3S ^ 26UI) PrintResult("-3S ^ -7L", -3S ^ -7L) PrintResult("-3S ^ 28UL", -3S ^ 28UL) PrintResult("-3S ^ -9D", -3S ^ -9D) PrintResult("-3S ^ 10.0F", -3S ^ 10.0F) PrintResult("-3S ^ -11.0R", -3S ^ -11.0R) PrintResult("-3S ^ ""12""", -3S ^ "12") PrintResult("-3S ^ TypeCode.Double", -3S ^ TypeCode.Double) PrintResult("24US ^ False", 24US ^ False) PrintResult("24US ^ True", 24US ^ True) PrintResult("24US ^ System.SByte.MinValue", 24US ^ System.SByte.MinValue) PrintResult("24US ^ System.Byte.MaxValue", 24US ^ System.Byte.MaxValue) PrintResult("24US ^ -3S", 24US ^ -3S) PrintResult("24US ^ 24US", 24US ^ 24US) PrintResult("24US ^ -5I", 24US ^ -5I) PrintResult("24US ^ 26UI", 24US ^ 26UI) PrintResult("24US ^ -7L", 24US ^ -7L) PrintResult("24US ^ 28UL", 24US ^ 28UL) PrintResult("24US ^ -9D", 24US ^ -9D) PrintResult("24US ^ 10.0F", 24US ^ 10.0F) PrintResult("24US ^ -11.0R", 24US ^ -11.0R) PrintResult("24US ^ ""12""", 24US ^ "12") PrintResult("24US ^ TypeCode.Double", 24US ^ TypeCode.Double) PrintResult("-5I ^ False", -5I ^ False) PrintResult("-5I ^ True", -5I ^ True) PrintResult("-5I ^ System.SByte.MinValue", -5I ^ System.SByte.MinValue) PrintResult("-5I ^ System.Byte.MaxValue", -5I ^ System.Byte.MaxValue) PrintResult("-5I ^ -3S", -5I ^ -3S) PrintResult("-5I ^ 24US", -5I ^ 24US) PrintResult("-5I ^ -5I", -5I ^ -5I) PrintResult("-5I ^ 26UI", -5I ^ 26UI) PrintResult("-5I ^ -7L", -5I ^ -7L) PrintResult("-5I ^ 28UL", -5I ^ 28UL) PrintResult("-5I ^ -9D", -5I ^ -9D) PrintResult("-5I ^ 10.0F", -5I ^ 10.0F) PrintResult("-5I ^ -11.0R", -5I ^ -11.0R) PrintResult("-5I ^ ""12""", -5I ^ "12") PrintResult("-5I ^ TypeCode.Double", -5I ^ TypeCode.Double) PrintResult("26UI ^ False", 26UI ^ False) PrintResult("26UI ^ True", 26UI ^ True) PrintResult("26UI ^ System.SByte.MinValue", 26UI ^ System.SByte.MinValue) PrintResult("26UI ^ System.Byte.MaxValue", 26UI ^ System.Byte.MaxValue) PrintResult("26UI ^ -3S", 26UI ^ -3S) PrintResult("26UI ^ 24US", 26UI ^ 24US) PrintResult("26UI ^ -5I", 26UI ^ -5I) PrintResult("26UI ^ 26UI", 26UI ^ 26UI) PrintResult("26UI ^ -7L", 26UI ^ -7L) PrintResult("26UI ^ 28UL", 26UI ^ 28UL) PrintResult("26UI ^ -9D", 26UI ^ -9D) PrintResult("26UI ^ 10.0F", 26UI ^ 10.0F) PrintResult("26UI ^ -11.0R", 26UI ^ -11.0R) PrintResult("26UI ^ ""12""", 26UI ^ "12") PrintResult("26UI ^ TypeCode.Double", 26UI ^ TypeCode.Double) PrintResult("-7L ^ False", -7L ^ False) PrintResult("-7L ^ True", -7L ^ True) PrintResult("-7L ^ System.SByte.MinValue", -7L ^ System.SByte.MinValue) PrintResult("-7L ^ System.Byte.MaxValue", -7L ^ System.Byte.MaxValue) PrintResult("-7L ^ -3S", -7L ^ -3S) PrintResult("-7L ^ 24US", -7L ^ 24US) PrintResult("-7L ^ -5I", -7L ^ -5I) PrintResult("-7L ^ 26UI", -7L ^ 26UI) PrintResult("-7L ^ -7L", -7L ^ -7L) PrintResult("-7L ^ 28UL", -7L ^ 28UL) PrintResult("-7L ^ -9D", -7L ^ -9D) PrintResult("-7L ^ 10.0F", -7L ^ 10.0F) PrintResult("-7L ^ -11.0R", -7L ^ -11.0R) PrintResult("-7L ^ ""12""", -7L ^ "12") PrintResult("-7L ^ TypeCode.Double", -7L ^ TypeCode.Double) PrintResult("28UL ^ False", 28UL ^ False) PrintResult("28UL ^ True", 28UL ^ True) PrintResult("28UL ^ System.SByte.MinValue", 28UL ^ System.SByte.MinValue) PrintResult("28UL ^ System.Byte.MaxValue", 28UL ^ System.Byte.MaxValue) PrintResult("28UL ^ -3S", 28UL ^ -3S) PrintResult("28UL ^ 24US", 28UL ^ 24US) PrintResult("28UL ^ -5I", 28UL ^ -5I) PrintResult("28UL ^ 26UI", 28UL ^ 26UI) PrintResult("28UL ^ -7L", 28UL ^ -7L) PrintResult("28UL ^ 28UL", 28UL ^ 28UL) PrintResult("28UL ^ -9D", 28UL ^ -9D) PrintResult("28UL ^ 10.0F", 28UL ^ 10.0F) PrintResult("28UL ^ -11.0R", 28UL ^ -11.0R) PrintResult("28UL ^ ""12""", 28UL ^ "12") PrintResult("28UL ^ TypeCode.Double", 28UL ^ TypeCode.Double) PrintResult("-9D ^ False", -9D ^ False) PrintResult("-9D ^ True", -9D ^ True) PrintResult("-9D ^ System.SByte.MinValue", -9D ^ System.SByte.MinValue) PrintResult("-9D ^ System.Byte.MaxValue", -9D ^ System.Byte.MaxValue) PrintResult("-9D ^ -3S", -9D ^ -3S) PrintResult("-9D ^ 24US", -9D ^ 24US) PrintResult("-9D ^ -5I", -9D ^ -5I) PrintResult("-9D ^ 26UI", -9D ^ 26UI) PrintResult("-9D ^ -7L", -9D ^ -7L) PrintResult("-9D ^ 28UL", -9D ^ 28UL) PrintResult("-9D ^ -9D", -9D ^ -9D) PrintResult("-9D ^ 10.0F", -9D ^ 10.0F) PrintResult("-9D ^ -11.0R", -9D ^ -11.0R) PrintResult("-9D ^ ""12""", -9D ^ "12") PrintResult("-9D ^ TypeCode.Double", -9D ^ TypeCode.Double) PrintResult("10.0F ^ False", 10.0F ^ False) PrintResult("10.0F ^ True", 10.0F ^ True) PrintResult("10.0F ^ System.SByte.MinValue", 10.0F ^ System.SByte.MinValue) PrintResult("10.0F ^ System.Byte.MaxValue", 10.0F ^ System.Byte.MaxValue) PrintResult("10.0F ^ -3S", 10.0F ^ -3S) PrintResult("10.0F ^ 24US", 10.0F ^ 24US) PrintResult("10.0F ^ -5I", 10.0F ^ -5I) PrintResult("10.0F ^ 26UI", 10.0F ^ 26UI) PrintResult("10.0F ^ -7L", 10.0F ^ -7L) PrintResult("10.0F ^ 28UL", 10.0F ^ 28UL) PrintResult("10.0F ^ -9D", 10.0F ^ -9D) PrintResult("10.0F ^ 10.0F", 10.0F ^ 10.0F) PrintResult("10.0F ^ -11.0R", 10.0F ^ -11.0R) PrintResult("10.0F ^ ""12""", 10.0F ^ "12") PrintResult("10.0F ^ TypeCode.Double", 10.0F ^ TypeCode.Double) PrintResult("-11.0R ^ False", -11.0R ^ False) PrintResult("-11.0R ^ True", -11.0R ^ True) PrintResult("-11.0R ^ System.SByte.MinValue", -11.0R ^ System.SByte.MinValue) PrintResult("-11.0R ^ System.Byte.MaxValue", -11.0R ^ System.Byte.MaxValue) PrintResult("-11.0R ^ -3S", -11.0R ^ -3S) PrintResult("-11.0R ^ 24US", -11.0R ^ 24US) PrintResult("-11.0R ^ -5I", -11.0R ^ -5I) PrintResult("-11.0R ^ 26UI", -11.0R ^ 26UI) PrintResult("-11.0R ^ -7L", -11.0R ^ -7L) PrintResult("-11.0R ^ 28UL", -11.0R ^ 28UL) PrintResult("-11.0R ^ -9D", -11.0R ^ -9D) PrintResult("-11.0R ^ 10.0F", -11.0R ^ 10.0F) PrintResult("-11.0R ^ -11.0R", -11.0R ^ -11.0R) PrintResult("-11.0R ^ ""12""", -11.0R ^ "12") PrintResult("-11.0R ^ TypeCode.Double", -11.0R ^ TypeCode.Double) PrintResult("""12"" ^ False", "12" ^ False) PrintResult("""12"" ^ True", "12" ^ True) PrintResult("""12"" ^ System.SByte.MinValue", "12" ^ System.SByte.MinValue) PrintResult("""12"" ^ System.Byte.MaxValue", "12" ^ System.Byte.MaxValue) PrintResult("""12"" ^ -3S", "12" ^ -3S) PrintResult("""12"" ^ 24US", "12" ^ 24US) PrintResult("""12"" ^ -5I", "12" ^ -5I) PrintResult("""12"" ^ 26UI", "12" ^ 26UI) PrintResult("""12"" ^ -7L", "12" ^ -7L) PrintResult("""12"" ^ 28UL", "12" ^ 28UL) PrintResult("""12"" ^ -9D", "12" ^ -9D) PrintResult("""12"" ^ 10.0F", "12" ^ 10.0F) PrintResult("""12"" ^ -11.0R", "12" ^ -11.0R) PrintResult("""12"" ^ ""12""", "12" ^ "12") PrintResult("""12"" ^ TypeCode.Double", "12" ^ TypeCode.Double) PrintResult("TypeCode.Double ^ False", TypeCode.Double ^ False) PrintResult("TypeCode.Double ^ True", TypeCode.Double ^ True) PrintResult("TypeCode.Double ^ System.SByte.MinValue", TypeCode.Double ^ System.SByte.MinValue) PrintResult("TypeCode.Double ^ System.Byte.MaxValue", TypeCode.Double ^ System.Byte.MaxValue) PrintResult("TypeCode.Double ^ -3S", TypeCode.Double ^ -3S) PrintResult("TypeCode.Double ^ 24US", TypeCode.Double ^ 24US) PrintResult("TypeCode.Double ^ -5I", TypeCode.Double ^ -5I) PrintResult("TypeCode.Double ^ 26UI", TypeCode.Double ^ 26UI) PrintResult("TypeCode.Double ^ -7L", TypeCode.Double ^ -7L) PrintResult("TypeCode.Double ^ 28UL", TypeCode.Double ^ 28UL) PrintResult("TypeCode.Double ^ -9D", TypeCode.Double ^ -9D) PrintResult("TypeCode.Double ^ 10.0F", TypeCode.Double ^ 10.0F) PrintResult("TypeCode.Double ^ -11.0R", TypeCode.Double ^ -11.0R) PrintResult("TypeCode.Double ^ ""12""", TypeCode.Double ^ "12") PrintResult("TypeCode.Double ^ TypeCode.Double", TypeCode.Double ^ TypeCode.Double) PrintResult("False << False", False << False) PrintResult("False << True", False << True) PrintResult("False << System.SByte.MinValue", False << System.SByte.MinValue) PrintResult("False << System.Byte.MaxValue", False << System.Byte.MaxValue) PrintResult("False << -3S", False << -3S) PrintResult("False << 24US", False << 24US) PrintResult("False << -5I", False << -5I) PrintResult("False << 26UI", False << 26UI) PrintResult("False << -7L", False << -7L) PrintResult("False << 28UL", False << 28UL) PrintResult("False << -9D", False << -9D) PrintResult("False << 10.0F", False << 10.0F) PrintResult("False << -11.0R", False << -11.0R) PrintResult("False << ""12""", False << "12") PrintResult("False << TypeCode.Double", False << TypeCode.Double) PrintResult("True << False", True << False) PrintResult("True << True", True << True) PrintResult("True << System.SByte.MinValue", True << System.SByte.MinValue) PrintResult("True << System.Byte.MaxValue", True << System.Byte.MaxValue) PrintResult("True << -3S", True << -3S) PrintResult("True << 24US", True << 24US) PrintResult("True << -5I", True << -5I) PrintResult("True << 26UI", True << 26UI) PrintResult("True << -7L", True << -7L) PrintResult("True << 28UL", True << 28UL) PrintResult("True << -9D", True << -9D) PrintResult("True << 10.0F", True << 10.0F) PrintResult("True << -11.0R", True << -11.0R) PrintResult("True << ""12""", True << "12") PrintResult("True << TypeCode.Double", True << TypeCode.Double) PrintResult("System.SByte.MinValue << False", System.SByte.MinValue << False) PrintResult("System.SByte.MinValue << True", System.SByte.MinValue << True) PrintResult("System.SByte.MinValue << System.SByte.MinValue", System.SByte.MinValue << System.SByte.MinValue) PrintResult("System.SByte.MinValue << System.Byte.MaxValue", System.SByte.MinValue << System.Byte.MaxValue) PrintResult("System.SByte.MinValue << -3S", System.SByte.MinValue << -3S) PrintResult("System.SByte.MinValue << 24US", System.SByte.MinValue << 24US) PrintResult("System.SByte.MinValue << -5I", System.SByte.MinValue << -5I) PrintResult("System.SByte.MinValue << 26UI", System.SByte.MinValue << 26UI) PrintResult("System.SByte.MinValue << -7L", System.SByte.MinValue << -7L) PrintResult("System.SByte.MinValue << 28UL", System.SByte.MinValue << 28UL) PrintResult("System.SByte.MinValue << -9D", System.SByte.MinValue << -9D) PrintResult("System.SByte.MinValue << 10.0F", System.SByte.MinValue << 10.0F) PrintResult("System.SByte.MinValue << -11.0R", System.SByte.MinValue << -11.0R) PrintResult("System.SByte.MinValue << ""12""", System.SByte.MinValue << "12") PrintResult("System.SByte.MinValue << TypeCode.Double", System.SByte.MinValue << TypeCode.Double) PrintResult("System.Byte.MaxValue << False", System.Byte.MaxValue << False) PrintResult("System.Byte.MaxValue << True", System.Byte.MaxValue << True) PrintResult("System.Byte.MaxValue << System.SByte.MinValue", System.Byte.MaxValue << System.SByte.MinValue) PrintResult("System.Byte.MaxValue << System.Byte.MaxValue", System.Byte.MaxValue << System.Byte.MaxValue) PrintResult("System.Byte.MaxValue << -3S", System.Byte.MaxValue << -3S) PrintResult("System.Byte.MaxValue << 24US", System.Byte.MaxValue << 24US) PrintResult("System.Byte.MaxValue << -5I", System.Byte.MaxValue << -5I) PrintResult("System.Byte.MaxValue << 26UI", System.Byte.MaxValue << 26UI) PrintResult("System.Byte.MaxValue << -7L", System.Byte.MaxValue << -7L) PrintResult("System.Byte.MaxValue << 28UL", System.Byte.MaxValue << 28UL) PrintResult("System.Byte.MaxValue << -9D", System.Byte.MaxValue << -9D) PrintResult("System.Byte.MaxValue << 10.0F", System.Byte.MaxValue << 10.0F) PrintResult("System.Byte.MaxValue << -11.0R", System.Byte.MaxValue << -11.0R) PrintResult("System.Byte.MaxValue << ""12""", System.Byte.MaxValue << "12") PrintResult("System.Byte.MaxValue << TypeCode.Double", System.Byte.MaxValue << TypeCode.Double) PrintResult("-3S << False", -3S << False) PrintResult("-3S << True", -3S << True) PrintResult("-3S << System.SByte.MinValue", -3S << System.SByte.MinValue) PrintResult("-3S << System.Byte.MaxValue", -3S << System.Byte.MaxValue) PrintResult("-3S << -3S", -3S << -3S) PrintResult("-3S << 24US", -3S << 24US) PrintResult("-3S << -5I", -3S << -5I) PrintResult("-3S << 26UI", -3S << 26UI) PrintResult("-3S << -7L", -3S << -7L) PrintResult("-3S << 28UL", -3S << 28UL) PrintResult("-3S << -9D", -3S << -9D) PrintResult("-3S << 10.0F", -3S << 10.0F) PrintResult("-3S << -11.0R", -3S << -11.0R) PrintResult("-3S << ""12""", -3S << "12") PrintResult("-3S << TypeCode.Double", -3S << TypeCode.Double) PrintResult("24US << False", 24US << False) PrintResult("24US << True", 24US << True) PrintResult("24US << System.SByte.MinValue", 24US << System.SByte.MinValue) PrintResult("24US << System.Byte.MaxValue", 24US << System.Byte.MaxValue) PrintResult("24US << -3S", 24US << -3S) PrintResult("24US << 24US", 24US << 24US) PrintResult("24US << -5I", 24US << -5I) PrintResult("24US << 26UI", 24US << 26UI) PrintResult("24US << -7L", 24US << -7L) PrintResult("24US << 28UL", 24US << 28UL) PrintResult("24US << -9D", 24US << -9D) PrintResult("24US << 10.0F", 24US << 10.0F) PrintResult("24US << -11.0R", 24US << -11.0R) PrintResult("24US << ""12""", 24US << "12") PrintResult("24US << TypeCode.Double", 24US << TypeCode.Double) PrintResult("-5I << False", -5I << False) PrintResult("-5I << True", -5I << True) PrintResult("-5I << System.SByte.MinValue", -5I << System.SByte.MinValue) PrintResult("-5I << System.Byte.MaxValue", -5I << System.Byte.MaxValue) PrintResult("-5I << -3S", -5I << -3S) PrintResult("-5I << 24US", -5I << 24US) PrintResult("-5I << -5I", -5I << -5I) PrintResult("-5I << 26UI", -5I << 26UI) PrintResult("-5I << -7L", -5I << -7L) PrintResult("-5I << 28UL", -5I << 28UL) PrintResult("-5I << -9D", -5I << -9D) PrintResult("-5I << 10.0F", -5I << 10.0F) PrintResult("-5I << -11.0R", -5I << -11.0R) PrintResult("-5I << ""12""", -5I << "12") PrintResult("-5I << TypeCode.Double", -5I << TypeCode.Double) PrintResult("26UI << False", 26UI << False) PrintResult("26UI << True", 26UI << True) PrintResult("26UI << System.SByte.MinValue", 26UI << System.SByte.MinValue) PrintResult("26UI << System.Byte.MaxValue", 26UI << System.Byte.MaxValue) PrintResult("26UI << -3S", 26UI << -3S) PrintResult("26UI << 24US", 26UI << 24US) PrintResult("26UI << -5I", 26UI << -5I) PrintResult("26UI << 26UI", 26UI << 26UI) PrintResult("26UI << -7L", 26UI << -7L) PrintResult("26UI << 28UL", 26UI << 28UL) PrintResult("26UI << -9D", 26UI << -9D) PrintResult("26UI << 10.0F", 26UI << 10.0F) PrintResult("26UI << -11.0R", 26UI << -11.0R) PrintResult("26UI << ""12""", 26UI << "12") PrintResult("26UI << TypeCode.Double", 26UI << TypeCode.Double) PrintResult("-7L << False", -7L << False) PrintResult("-7L << True", -7L << True) PrintResult("-7L << System.SByte.MinValue", -7L << System.SByte.MinValue) PrintResult("-7L << System.Byte.MaxValue", -7L << System.Byte.MaxValue) PrintResult("-7L << -3S", -7L << -3S) PrintResult("-7L << 24US", -7L << 24US) PrintResult("-7L << -5I", -7L << -5I) PrintResult("-7L << 26UI", -7L << 26UI) PrintResult("-7L << -7L", -7L << -7L) PrintResult("-7L << 28UL", -7L << 28UL) PrintResult("-7L << -9D", -7L << -9D) PrintResult("-7L << 10.0F", -7L << 10.0F) PrintResult("-7L << -11.0R", -7L << -11.0R) PrintResult("-7L << ""12""", -7L << "12") PrintResult("-7L << TypeCode.Double", -7L << TypeCode.Double) PrintResult("28UL << False", 28UL << False) PrintResult("28UL << True", 28UL << True) PrintResult("28UL << System.SByte.MinValue", 28UL << System.SByte.MinValue) PrintResult("28UL << System.Byte.MaxValue", 28UL << System.Byte.MaxValue) PrintResult("28UL << -3S", 28UL << -3S) PrintResult("28UL << 24US", 28UL << 24US) PrintResult("28UL << -5I", 28UL << -5I) PrintResult("28UL << 26UI", 28UL << 26UI) PrintResult("28UL << -7L", 28UL << -7L) PrintResult("28UL << 28UL", 28UL << 28UL) PrintResult("28UL << -9D", 28UL << -9D) PrintResult("28UL << 10.0F", 28UL << 10.0F) PrintResult("28UL << -11.0R", 28UL << -11.0R) PrintResult("28UL << ""12""", 28UL << "12") PrintResult("28UL << TypeCode.Double", 28UL << TypeCode.Double) PrintResult("-9D << False", -9D << False) PrintResult("-9D << True", -9D << True) PrintResult("-9D << System.SByte.MinValue", -9D << System.SByte.MinValue) PrintResult("-9D << System.Byte.MaxValue", -9D << System.Byte.MaxValue) PrintResult("-9D << -3S", -9D << -3S) PrintResult("-9D << 24US", -9D << 24US) PrintResult("-9D << -5I", -9D << -5I) PrintResult("-9D << 26UI", -9D << 26UI) PrintResult("-9D << -7L", -9D << -7L) PrintResult("-9D << 28UL", -9D << 28UL) PrintResult("-9D << -9D", -9D << -9D) PrintResult("-9D << 10.0F", -9D << 10.0F) PrintResult("-9D << -11.0R", -9D << -11.0R) PrintResult("-9D << ""12""", -9D << "12") PrintResult("-9D << TypeCode.Double", -9D << TypeCode.Double) PrintResult("10.0F << False", 10.0F << False) PrintResult("10.0F << True", 10.0F << True) PrintResult("10.0F << System.SByte.MinValue", 10.0F << System.SByte.MinValue) PrintResult("10.0F << System.Byte.MaxValue", 10.0F << System.Byte.MaxValue) PrintResult("10.0F << -3S", 10.0F << -3S) PrintResult("10.0F << 24US", 10.0F << 24US) PrintResult("10.0F << -5I", 10.0F << -5I) PrintResult("10.0F << 26UI", 10.0F << 26UI) PrintResult("10.0F << -7L", 10.0F << -7L) PrintResult("10.0F << 28UL", 10.0F << 28UL) PrintResult("10.0F << -9D", 10.0F << -9D) PrintResult("10.0F << 10.0F", 10.0F << 10.0F) PrintResult("10.0F << -11.0R", 10.0F << -11.0R) PrintResult("10.0F << ""12""", 10.0F << "12") PrintResult("10.0F << TypeCode.Double", 10.0F << TypeCode.Double) PrintResult("-11.0R << False", -11.0R << False) PrintResult("-11.0R << True", -11.0R << True) PrintResult("-11.0R << System.SByte.MinValue", -11.0R << System.SByte.MinValue) PrintResult("-11.0R << System.Byte.MaxValue", -11.0R << System.Byte.MaxValue) PrintResult("-11.0R << -3S", -11.0R << -3S) PrintResult("-11.0R << 24US", -11.0R << 24US) PrintResult("-11.0R << -5I", -11.0R << -5I) PrintResult("-11.0R << 26UI", -11.0R << 26UI) PrintResult("-11.0R << -7L", -11.0R << -7L) PrintResult("-11.0R << 28UL", -11.0R << 28UL) PrintResult("-11.0R << -9D", -11.0R << -9D) PrintResult("-11.0R << 10.0F", -11.0R << 10.0F) PrintResult("-11.0R << -11.0R", -11.0R << -11.0R) PrintResult("-11.0R << ""12""", -11.0R << "12") PrintResult("-11.0R << TypeCode.Double", -11.0R << TypeCode.Double) PrintResult("""12"" << False", "12" << False) PrintResult("""12"" << True", "12" << True) PrintResult("""12"" << System.SByte.MinValue", "12" << System.SByte.MinValue) PrintResult("""12"" << System.Byte.MaxValue", "12" << System.Byte.MaxValue) PrintResult("""12"" << -3S", "12" << -3S) PrintResult("""12"" << 24US", "12" << 24US) PrintResult("""12"" << -5I", "12" << -5I) PrintResult("""12"" << 26UI", "12" << 26UI) PrintResult("""12"" << -7L", "12" << -7L) PrintResult("""12"" << 28UL", "12" << 28UL) PrintResult("""12"" << -9D", "12" << -9D) PrintResult("""12"" << 10.0F", "12" << 10.0F) PrintResult("""12"" << -11.0R", "12" << -11.0R) PrintResult("""12"" << ""12""", "12" << "12") PrintResult("""12"" << TypeCode.Double", "12" << TypeCode.Double) PrintResult("TypeCode.Double << False", TypeCode.Double << False) PrintResult("TypeCode.Double << True", TypeCode.Double << True) PrintResult("TypeCode.Double << System.SByte.MinValue", TypeCode.Double << System.SByte.MinValue) PrintResult("TypeCode.Double << System.Byte.MaxValue", TypeCode.Double << System.Byte.MaxValue) PrintResult("TypeCode.Double << -3S", TypeCode.Double << -3S) PrintResult("TypeCode.Double << 24US", TypeCode.Double << 24US) PrintResult("TypeCode.Double << -5I", TypeCode.Double << -5I) PrintResult("TypeCode.Double << 26UI", TypeCode.Double << 26UI) PrintResult("TypeCode.Double << -7L", TypeCode.Double << -7L) PrintResult("TypeCode.Double << 28UL", TypeCode.Double << 28UL) PrintResult("TypeCode.Double << -9D", TypeCode.Double << -9D) PrintResult("TypeCode.Double << 10.0F", TypeCode.Double << 10.0F) PrintResult("TypeCode.Double << -11.0R", TypeCode.Double << -11.0R) PrintResult("TypeCode.Double << ""12""", TypeCode.Double << "12") PrintResult("TypeCode.Double << TypeCode.Double", TypeCode.Double << TypeCode.Double) PrintResult("False >> False", False >> False) PrintResult("False >> True", False >> True) PrintResult("False >> System.SByte.MinValue", False >> System.SByte.MinValue) PrintResult("False >> System.Byte.MaxValue", False >> System.Byte.MaxValue) PrintResult("False >> -3S", False >> -3S) PrintResult("False >> 24US", False >> 24US) PrintResult("False >> -5I", False >> -5I) PrintResult("False >> 26UI", False >> 26UI) PrintResult("False >> -7L", False >> -7L) PrintResult("False >> 28UL", False >> 28UL) PrintResult("False >> -9D", False >> -9D) PrintResult("False >> 10.0F", False >> 10.0F) PrintResult("False >> -11.0R", False >> -11.0R) PrintResult("False >> ""12""", False >> "12") PrintResult("False >> TypeCode.Double", False >> TypeCode.Double) PrintResult("True >> False", True >> False) PrintResult("True >> True", True >> True) PrintResult("True >> System.SByte.MinValue", True >> System.SByte.MinValue) PrintResult("True >> System.Byte.MaxValue", True >> System.Byte.MaxValue) PrintResult("True >> -3S", True >> -3S) PrintResult("True >> 24US", True >> 24US) PrintResult("True >> -5I", True >> -5I) PrintResult("True >> 26UI", True >> 26UI) PrintResult("True >> -7L", True >> -7L) PrintResult("True >> 28UL", True >> 28UL) PrintResult("True >> -9D", True >> -9D) PrintResult("True >> 10.0F", True >> 10.0F) PrintResult("True >> -11.0R", True >> -11.0R) PrintResult("True >> ""12""", True >> "12") PrintResult("True >> TypeCode.Double", True >> TypeCode.Double) PrintResult("System.SByte.MinValue >> False", System.SByte.MinValue >> False) PrintResult("System.SByte.MinValue >> True", System.SByte.MinValue >> True) PrintResult("System.SByte.MinValue >> System.SByte.MinValue", System.SByte.MinValue >> System.SByte.MinValue) PrintResult("System.SByte.MinValue >> System.Byte.MaxValue", System.SByte.MinValue >> System.Byte.MaxValue) PrintResult("System.SByte.MinValue >> -3S", System.SByte.MinValue >> -3S) PrintResult("System.SByte.MinValue >> 24US", System.SByte.MinValue >> 24US) PrintResult("System.SByte.MinValue >> -5I", System.SByte.MinValue >> -5I) PrintResult("System.SByte.MinValue >> 26UI", System.SByte.MinValue >> 26UI) PrintResult("System.SByte.MinValue >> -7L", System.SByte.MinValue >> -7L) PrintResult("System.SByte.MinValue >> 28UL", System.SByte.MinValue >> 28UL) PrintResult("System.SByte.MinValue >> -9D", System.SByte.MinValue >> -9D) PrintResult("System.SByte.MinValue >> 10.0F", System.SByte.MinValue >> 10.0F) PrintResult("System.SByte.MinValue >> -11.0R", System.SByte.MinValue >> -11.0R) PrintResult("System.SByte.MinValue >> ""12""", System.SByte.MinValue >> "12") PrintResult("System.SByte.MinValue >> TypeCode.Double", System.SByte.MinValue >> TypeCode.Double) PrintResult("System.Byte.MaxValue >> False", System.Byte.MaxValue >> False) PrintResult("System.Byte.MaxValue >> True", System.Byte.MaxValue >> True) PrintResult("System.Byte.MaxValue >> System.SByte.MinValue", System.Byte.MaxValue >> System.SByte.MinValue) PrintResult("System.Byte.MaxValue >> System.Byte.MaxValue", System.Byte.MaxValue >> System.Byte.MaxValue) PrintResult("System.Byte.MaxValue >> -3S", System.Byte.MaxValue >> -3S) PrintResult("System.Byte.MaxValue >> 24US", System.Byte.MaxValue >> 24US) PrintResult("System.Byte.MaxValue >> -5I", System.Byte.MaxValue >> -5I) PrintResult("System.Byte.MaxValue >> 26UI", System.Byte.MaxValue >> 26UI) PrintResult("System.Byte.MaxValue >> -7L", System.Byte.MaxValue >> -7L) PrintResult("System.Byte.MaxValue >> 28UL", System.Byte.MaxValue >> 28UL) PrintResult("System.Byte.MaxValue >> -9D", System.Byte.MaxValue >> -9D) PrintResult("System.Byte.MaxValue >> 10.0F", System.Byte.MaxValue >> 10.0F) PrintResult("System.Byte.MaxValue >> -11.0R", System.Byte.MaxValue >> -11.0R) PrintResult("System.Byte.MaxValue >> ""12""", System.Byte.MaxValue >> "12") PrintResult("System.Byte.MaxValue >> TypeCode.Double", System.Byte.MaxValue >> TypeCode.Double) PrintResult("-3S >> False", -3S >> False) PrintResult("-3S >> True", -3S >> True) PrintResult("-3S >> System.SByte.MinValue", -3S >> System.SByte.MinValue) PrintResult("-3S >> System.Byte.MaxValue", -3S >> System.Byte.MaxValue) PrintResult("-3S >> -3S", -3S >> -3S) PrintResult("-3S >> 24US", -3S >> 24US) PrintResult("-3S >> -5I", -3S >> -5I) PrintResult("-3S >> 26UI", -3S >> 26UI) PrintResult("-3S >> -7L", -3S >> -7L) PrintResult("-3S >> 28UL", -3S >> 28UL) PrintResult("-3S >> -9D", -3S >> -9D) PrintResult("-3S >> 10.0F", -3S >> 10.0F) PrintResult("-3S >> -11.0R", -3S >> -11.0R) PrintResult("-3S >> ""12""", -3S >> "12") PrintResult("-3S >> TypeCode.Double", -3S >> TypeCode.Double) PrintResult("24US >> False", 24US >> False) PrintResult("24US >> True", 24US >> True) PrintResult("24US >> System.SByte.MinValue", 24US >> System.SByte.MinValue) PrintResult("24US >> System.Byte.MaxValue", 24US >> System.Byte.MaxValue) PrintResult("24US >> -3S", 24US >> -3S) PrintResult("24US >> 24US", 24US >> 24US) PrintResult("24US >> -5I", 24US >> -5I) PrintResult("24US >> 26UI", 24US >> 26UI) PrintResult("24US >> -7L", 24US >> -7L) PrintResult("24US >> 28UL", 24US >> 28UL) PrintResult("24US >> -9D", 24US >> -9D) PrintResult("24US >> 10.0F", 24US >> 10.0F) PrintResult("24US >> -11.0R", 24US >> -11.0R) PrintResult("24US >> ""12""", 24US >> "12") PrintResult("24US >> TypeCode.Double", 24US >> TypeCode.Double) PrintResult("-5I >> False", -5I >> False) PrintResult("-5I >> True", -5I >> True) PrintResult("-5I >> System.SByte.MinValue", -5I >> System.SByte.MinValue) PrintResult("-5I >> System.Byte.MaxValue", -5I >> System.Byte.MaxValue) PrintResult("-5I >> -3S", -5I >> -3S) PrintResult("-5I >> 24US", -5I >> 24US) PrintResult("-5I >> -5I", -5I >> -5I) PrintResult("-5I >> 26UI", -5I >> 26UI) PrintResult("-5I >> -7L", -5I >> -7L) PrintResult("-5I >> 28UL", -5I >> 28UL) PrintResult("-5I >> -9D", -5I >> -9D) PrintResult("-5I >> 10.0F", -5I >> 10.0F) PrintResult("-5I >> -11.0R", -5I >> -11.0R) PrintResult("-5I >> ""12""", -5I >> "12") PrintResult("-5I >> TypeCode.Double", -5I >> TypeCode.Double) PrintResult("26UI >> False", 26UI >> False) PrintResult("26UI >> True", 26UI >> True) PrintResult("26UI >> System.SByte.MinValue", 26UI >> System.SByte.MinValue) PrintResult("26UI >> System.Byte.MaxValue", 26UI >> System.Byte.MaxValue) PrintResult("26UI >> -3S", 26UI >> -3S) PrintResult("26UI >> 24US", 26UI >> 24US) PrintResult("26UI >> -5I", 26UI >> -5I) PrintResult("26UI >> 26UI", 26UI >> 26UI) PrintResult("26UI >> -7L", 26UI >> -7L) PrintResult("26UI >> 28UL", 26UI >> 28UL) PrintResult("26UI >> -9D", 26UI >> -9D) PrintResult("26UI >> 10.0F", 26UI >> 10.0F) PrintResult("26UI >> -11.0R", 26UI >> -11.0R) PrintResult("26UI >> ""12""", 26UI >> "12") PrintResult("26UI >> TypeCode.Double", 26UI >> TypeCode.Double) PrintResult("-7L >> False", -7L >> False) PrintResult("-7L >> True", -7L >> True) PrintResult("-7L >> System.SByte.MinValue", -7L >> System.SByte.MinValue) PrintResult("-7L >> System.Byte.MaxValue", -7L >> System.Byte.MaxValue) PrintResult("-7L >> -3S", -7L >> -3S) PrintResult("-7L >> 24US", -7L >> 24US) PrintResult("-7L >> -5I", -7L >> -5I) PrintResult("-7L >> 26UI", -7L >> 26UI) PrintResult("-7L >> -7L", -7L >> -7L) PrintResult("-7L >> 28UL", -7L >> 28UL) PrintResult("-7L >> -9D", -7L >> -9D) PrintResult("-7L >> 10.0F", -7L >> 10.0F) PrintResult("-7L >> -11.0R", -7L >> -11.0R) PrintResult("-7L >> ""12""", -7L >> "12") PrintResult("-7L >> TypeCode.Double", -7L >> TypeCode.Double) PrintResult("28UL >> False", 28UL >> False) PrintResult("28UL >> True", 28UL >> True) PrintResult("28UL >> System.SByte.MinValue", 28UL >> System.SByte.MinValue) PrintResult("28UL >> System.Byte.MaxValue", 28UL >> System.Byte.MaxValue) PrintResult("28UL >> -3S", 28UL >> -3S) PrintResult("28UL >> 24US", 28UL >> 24US) PrintResult("28UL >> -5I", 28UL >> -5I) PrintResult("28UL >> 26UI", 28UL >> 26UI) PrintResult("28UL >> -7L", 28UL >> -7L) PrintResult("28UL >> 28UL", 28UL >> 28UL) PrintResult("28UL >> -9D", 28UL >> -9D) PrintResult("28UL >> 10.0F", 28UL >> 10.0F) PrintResult("28UL >> -11.0R", 28UL >> -11.0R) PrintResult("28UL >> ""12""", 28UL >> "12") PrintResult("28UL >> TypeCode.Double", 28UL >> TypeCode.Double) PrintResult("-9D >> False", -9D >> False) PrintResult("-9D >> True", -9D >> True) PrintResult("-9D >> System.SByte.MinValue", -9D >> System.SByte.MinValue) PrintResult("-9D >> System.Byte.MaxValue", -9D >> System.Byte.MaxValue) PrintResult("-9D >> -3S", -9D >> -3S) PrintResult("-9D >> 24US", -9D >> 24US) PrintResult("-9D >> -5I", -9D >> -5I) PrintResult("-9D >> 26UI", -9D >> 26UI) PrintResult("-9D >> -7L", -9D >> -7L) PrintResult("-9D >> 28UL", -9D >> 28UL) PrintResult("-9D >> -9D", -9D >> -9D) PrintResult("-9D >> 10.0F", -9D >> 10.0F) PrintResult("-9D >> -11.0R", -9D >> -11.0R) PrintResult("-9D >> ""12""", -9D >> "12") PrintResult("-9D >> TypeCode.Double", -9D >> TypeCode.Double) PrintResult("10.0F >> False", 10.0F >> False) PrintResult("10.0F >> True", 10.0F >> True) PrintResult("10.0F >> System.SByte.MinValue", 10.0F >> System.SByte.MinValue) PrintResult("10.0F >> System.Byte.MaxValue", 10.0F >> System.Byte.MaxValue) PrintResult("10.0F >> -3S", 10.0F >> -3S) PrintResult("10.0F >> 24US", 10.0F >> 24US) PrintResult("10.0F >> -5I", 10.0F >> -5I) PrintResult("10.0F >> 26UI", 10.0F >> 26UI) PrintResult("10.0F >> -7L", 10.0F >> -7L) PrintResult("10.0F >> 28UL", 10.0F >> 28UL) PrintResult("10.0F >> -9D", 10.0F >> -9D) PrintResult("10.0F >> 10.0F", 10.0F >> 10.0F) PrintResult("10.0F >> -11.0R", 10.0F >> -11.0R) PrintResult("10.0F >> ""12""", 10.0F >> "12") PrintResult("10.0F >> TypeCode.Double", 10.0F >> TypeCode.Double) PrintResult("-11.0R >> False", -11.0R >> False) PrintResult("-11.0R >> True", -11.0R >> True) PrintResult("-11.0R >> System.SByte.MinValue", -11.0R >> System.SByte.MinValue) PrintResult("-11.0R >> System.Byte.MaxValue", -11.0R >> System.Byte.MaxValue) PrintResult("-11.0R >> -3S", -11.0R >> -3S) PrintResult("-11.0R >> 24US", -11.0R >> 24US) PrintResult("-11.0R >> -5I", -11.0R >> -5I) PrintResult("-11.0R >> 26UI", -11.0R >> 26UI) PrintResult("-11.0R >> -7L", -11.0R >> -7L) PrintResult("-11.0R >> 28UL", -11.0R >> 28UL) PrintResult("-11.0R >> -9D", -11.0R >> -9D) PrintResult("-11.0R >> 10.0F", -11.0R >> 10.0F) PrintResult("-11.0R >> -11.0R", -11.0R >> -11.0R) PrintResult("-11.0R >> ""12""", -11.0R >> "12") PrintResult("-11.0R >> TypeCode.Double", -11.0R >> TypeCode.Double) PrintResult("""12"" >> False", "12" >> False) PrintResult("""12"" >> True", "12" >> True) PrintResult("""12"" >> System.SByte.MinValue", "12" >> System.SByte.MinValue) PrintResult("""12"" >> System.Byte.MaxValue", "12" >> System.Byte.MaxValue) PrintResult("""12"" >> -3S", "12" >> -3S) PrintResult("""12"" >> 24US", "12" >> 24US) PrintResult("""12"" >> -5I", "12" >> -5I) PrintResult("""12"" >> 26UI", "12" >> 26UI) PrintResult("""12"" >> -7L", "12" >> -7L) PrintResult("""12"" >> 28UL", "12" >> 28UL) PrintResult("""12"" >> -9D", "12" >> -9D) PrintResult("""12"" >> 10.0F", "12" >> 10.0F) PrintResult("""12"" >> -11.0R", "12" >> -11.0R) PrintResult("""12"" >> ""12""", "12" >> "12") PrintResult("""12"" >> TypeCode.Double", "12" >> TypeCode.Double) PrintResult("TypeCode.Double >> False", TypeCode.Double >> False) PrintResult("TypeCode.Double >> True", TypeCode.Double >> True) PrintResult("TypeCode.Double >> System.SByte.MinValue", TypeCode.Double >> System.SByte.MinValue) PrintResult("TypeCode.Double >> System.Byte.MaxValue", TypeCode.Double >> System.Byte.MaxValue) PrintResult("TypeCode.Double >> -3S", TypeCode.Double >> -3S) PrintResult("TypeCode.Double >> 24US", TypeCode.Double >> 24US) PrintResult("TypeCode.Double >> -5I", TypeCode.Double >> -5I) PrintResult("TypeCode.Double >> 26UI", TypeCode.Double >> 26UI) PrintResult("TypeCode.Double >> -7L", TypeCode.Double >> -7L) PrintResult("TypeCode.Double >> 28UL", TypeCode.Double >> 28UL) PrintResult("TypeCode.Double >> -9D", TypeCode.Double >> -9D) PrintResult("TypeCode.Double >> 10.0F", TypeCode.Double >> 10.0F) PrintResult("TypeCode.Double >> -11.0R", TypeCode.Double >> -11.0R) PrintResult("TypeCode.Double >> ""12""", TypeCode.Double >> "12") PrintResult("TypeCode.Double >> TypeCode.Double", TypeCode.Double >> TypeCode.Double) PrintResult("False OrElse False", False OrElse False) PrintResult("False OrElse True", False OrElse True) PrintResult("False OrElse System.SByte.MinValue", False OrElse System.SByte.MinValue) PrintResult("False OrElse System.Byte.MaxValue", False OrElse System.Byte.MaxValue) PrintResult("False OrElse -3S", False OrElse -3S) PrintResult("False OrElse 24US", False OrElse 24US) PrintResult("False OrElse -5I", False OrElse -5I) PrintResult("False OrElse 26UI", False OrElse 26UI) PrintResult("False OrElse -7L", False OrElse -7L) PrintResult("False OrElse 28UL", False OrElse 28UL) PrintResult("False OrElse -9D", False OrElse -9D) PrintResult("False OrElse 10.0F", False OrElse 10.0F) PrintResult("False OrElse -11.0R", False OrElse -11.0R) PrintResult("False OrElse ""12""", False OrElse "12") PrintResult("False OrElse TypeCode.Double", False OrElse TypeCode.Double) PrintResult("True OrElse False", True OrElse False) PrintResult("True OrElse True", True OrElse True) PrintResult("True OrElse System.SByte.MinValue", True OrElse System.SByte.MinValue) PrintResult("True OrElse System.Byte.MaxValue", True OrElse System.Byte.MaxValue) PrintResult("True OrElse -3S", True OrElse -3S) PrintResult("True OrElse 24US", True OrElse 24US) PrintResult("True OrElse -5I", True OrElse -5I) PrintResult("True OrElse 26UI", True OrElse 26UI) PrintResult("True OrElse -7L", True OrElse -7L) PrintResult("True OrElse 28UL", True OrElse 28UL) PrintResult("True OrElse -9D", True OrElse -9D) PrintResult("True OrElse 10.0F", True OrElse 10.0F) PrintResult("True OrElse -11.0R", True OrElse -11.0R) PrintResult("True OrElse ""12""", True OrElse "12") PrintResult("True OrElse TypeCode.Double", True OrElse TypeCode.Double) PrintResult("System.SByte.MinValue OrElse False", System.SByte.MinValue OrElse False) PrintResult("System.SByte.MinValue OrElse True", System.SByte.MinValue OrElse True) PrintResult("System.SByte.MinValue OrElse System.SByte.MinValue", System.SByte.MinValue OrElse System.SByte.MinValue) PrintResult("System.SByte.MinValue OrElse System.Byte.MaxValue", System.SByte.MinValue OrElse System.Byte.MaxValue) PrintResult("System.SByte.MinValue OrElse -3S", System.SByte.MinValue OrElse -3S) PrintResult("System.SByte.MinValue OrElse 24US", System.SByte.MinValue OrElse 24US) PrintResult("System.SByte.MinValue OrElse -5I", System.SByte.MinValue OrElse -5I) PrintResult("System.SByte.MinValue OrElse 26UI", System.SByte.MinValue OrElse 26UI) PrintResult("System.SByte.MinValue OrElse -7L", System.SByte.MinValue OrElse -7L) PrintResult("System.SByte.MinValue OrElse 28UL", System.SByte.MinValue OrElse 28UL) PrintResult("System.SByte.MinValue OrElse -9D", System.SByte.MinValue OrElse -9D) PrintResult("System.SByte.MinValue OrElse 10.0F", System.SByte.MinValue OrElse 10.0F) PrintResult("System.SByte.MinValue OrElse -11.0R", System.SByte.MinValue OrElse -11.0R) PrintResult("System.SByte.MinValue OrElse ""12""", System.SByte.MinValue OrElse "12") PrintResult("System.SByte.MinValue OrElse TypeCode.Double", System.SByte.MinValue OrElse TypeCode.Double) PrintResult("System.Byte.MaxValue OrElse False", System.Byte.MaxValue OrElse False) PrintResult("System.Byte.MaxValue OrElse True", System.Byte.MaxValue OrElse True) PrintResult("System.Byte.MaxValue OrElse System.SByte.MinValue", System.Byte.MaxValue OrElse System.SByte.MinValue) PrintResult("System.Byte.MaxValue OrElse System.Byte.MaxValue", System.Byte.MaxValue OrElse System.Byte.MaxValue) PrintResult("System.Byte.MaxValue OrElse -3S", System.Byte.MaxValue OrElse -3S) PrintResult("System.Byte.MaxValue OrElse 24US", System.Byte.MaxValue OrElse 24US) PrintResult("System.Byte.MaxValue OrElse -5I", System.Byte.MaxValue OrElse -5I) PrintResult("System.Byte.MaxValue OrElse 26UI", System.Byte.MaxValue OrElse 26UI) PrintResult("System.Byte.MaxValue OrElse -7L", System.Byte.MaxValue OrElse -7L) PrintResult("System.Byte.MaxValue OrElse 28UL", System.Byte.MaxValue OrElse 28UL) PrintResult("System.Byte.MaxValue OrElse -9D", System.Byte.MaxValue OrElse -9D) PrintResult("System.Byte.MaxValue OrElse 10.0F", System.Byte.MaxValue OrElse 10.0F) PrintResult("System.Byte.MaxValue OrElse -11.0R", System.Byte.MaxValue OrElse -11.0R) PrintResult("System.Byte.MaxValue OrElse ""12""", System.Byte.MaxValue OrElse "12") PrintResult("System.Byte.MaxValue OrElse TypeCode.Double", System.Byte.MaxValue OrElse TypeCode.Double) PrintResult("-3S OrElse False", -3S OrElse False) PrintResult("-3S OrElse True", -3S OrElse True) PrintResult("-3S OrElse System.SByte.MinValue", -3S OrElse System.SByte.MinValue) PrintResult("-3S OrElse System.Byte.MaxValue", -3S OrElse System.Byte.MaxValue) PrintResult("-3S OrElse -3S", -3S OrElse -3S) PrintResult("-3S OrElse 24US", -3S OrElse 24US) PrintResult("-3S OrElse -5I", -3S OrElse -5I) PrintResult("-3S OrElse 26UI", -3S OrElse 26UI) PrintResult("-3S OrElse -7L", -3S OrElse -7L) PrintResult("-3S OrElse 28UL", -3S OrElse 28UL) PrintResult("-3S OrElse -9D", -3S OrElse -9D) PrintResult("-3S OrElse 10.0F", -3S OrElse 10.0F) PrintResult("-3S OrElse -11.0R", -3S OrElse -11.0R) PrintResult("-3S OrElse ""12""", -3S OrElse "12") PrintResult("-3S OrElse TypeCode.Double", -3S OrElse TypeCode.Double) PrintResult("24US OrElse False", 24US OrElse False) PrintResult("24US OrElse True", 24US OrElse True) PrintResult("24US OrElse System.SByte.MinValue", 24US OrElse System.SByte.MinValue) PrintResult("24US OrElse System.Byte.MaxValue", 24US OrElse System.Byte.MaxValue) PrintResult("24US OrElse -3S", 24US OrElse -3S) PrintResult("24US OrElse 24US", 24US OrElse 24US) PrintResult("24US OrElse -5I", 24US OrElse -5I) PrintResult("24US OrElse 26UI", 24US OrElse 26UI) PrintResult("24US OrElse -7L", 24US OrElse -7L) PrintResult("24US OrElse 28UL", 24US OrElse 28UL) PrintResult("24US OrElse -9D", 24US OrElse -9D) PrintResult("24US OrElse 10.0F", 24US OrElse 10.0F) PrintResult("24US OrElse -11.0R", 24US OrElse -11.0R) PrintResult("24US OrElse ""12""", 24US OrElse "12") PrintResult("24US OrElse TypeCode.Double", 24US OrElse TypeCode.Double) PrintResult("-5I OrElse False", -5I OrElse False) PrintResult("-5I OrElse True", -5I OrElse True) PrintResult("-5I OrElse System.SByte.MinValue", -5I OrElse System.SByte.MinValue) PrintResult("-5I OrElse System.Byte.MaxValue", -5I OrElse System.Byte.MaxValue) PrintResult("-5I OrElse -3S", -5I OrElse -3S) PrintResult("-5I OrElse 24US", -5I OrElse 24US) PrintResult("-5I OrElse -5I", -5I OrElse -5I) PrintResult("-5I OrElse 26UI", -5I OrElse 26UI) PrintResult("-5I OrElse -7L", -5I OrElse -7L) PrintResult("-5I OrElse 28UL", -5I OrElse 28UL) PrintResult("-5I OrElse -9D", -5I OrElse -9D) PrintResult("-5I OrElse 10.0F", -5I OrElse 10.0F) PrintResult("-5I OrElse -11.0R", -5I OrElse -11.0R) PrintResult("-5I OrElse ""12""", -5I OrElse "12") PrintResult("-5I OrElse TypeCode.Double", -5I OrElse TypeCode.Double) PrintResult("26UI OrElse False", 26UI OrElse False) PrintResult("26UI OrElse True", 26UI OrElse True) PrintResult("26UI OrElse System.SByte.MinValue", 26UI OrElse System.SByte.MinValue) PrintResult("26UI OrElse System.Byte.MaxValue", 26UI OrElse System.Byte.MaxValue) PrintResult("26UI OrElse -3S", 26UI OrElse -3S) PrintResult("26UI OrElse 24US", 26UI OrElse 24US) PrintResult("26UI OrElse -5I", 26UI OrElse -5I) PrintResult("26UI OrElse 26UI", 26UI OrElse 26UI) PrintResult("26UI OrElse -7L", 26UI OrElse -7L) PrintResult("26UI OrElse 28UL", 26UI OrElse 28UL) PrintResult("26UI OrElse -9D", 26UI OrElse -9D) PrintResult("26UI OrElse 10.0F", 26UI OrElse 10.0F) PrintResult("26UI OrElse -11.0R", 26UI OrElse -11.0R) PrintResult("26UI OrElse ""12""", 26UI OrElse "12") PrintResult("26UI OrElse TypeCode.Double", 26UI OrElse TypeCode.Double) PrintResult("-7L OrElse False", -7L OrElse False) PrintResult("-7L OrElse True", -7L OrElse True) PrintResult("-7L OrElse System.SByte.MinValue", -7L OrElse System.SByte.MinValue) PrintResult("-7L OrElse System.Byte.MaxValue", -7L OrElse System.Byte.MaxValue) PrintResult("-7L OrElse -3S", -7L OrElse -3S) PrintResult("-7L OrElse 24US", -7L OrElse 24US) PrintResult("-7L OrElse -5I", -7L OrElse -5I) PrintResult("-7L OrElse 26UI", -7L OrElse 26UI) PrintResult("-7L OrElse -7L", -7L OrElse -7L) PrintResult("-7L OrElse 28UL", -7L OrElse 28UL) PrintResult("-7L OrElse -9D", -7L OrElse -9D) PrintResult("-7L OrElse 10.0F", -7L OrElse 10.0F) PrintResult("-7L OrElse -11.0R", -7L OrElse -11.0R) PrintResult("-7L OrElse ""12""", -7L OrElse "12") PrintResult("-7L OrElse TypeCode.Double", -7L OrElse TypeCode.Double) PrintResult("28UL OrElse False", 28UL OrElse False) PrintResult("28UL OrElse True", 28UL OrElse True) PrintResult("28UL OrElse System.SByte.MinValue", 28UL OrElse System.SByte.MinValue) PrintResult("28UL OrElse System.Byte.MaxValue", 28UL OrElse System.Byte.MaxValue) PrintResult("28UL OrElse -3S", 28UL OrElse -3S) PrintResult("28UL OrElse 24US", 28UL OrElse 24US) PrintResult("28UL OrElse -5I", 28UL OrElse -5I) PrintResult("28UL OrElse 26UI", 28UL OrElse 26UI) PrintResult("28UL OrElse -7L", 28UL OrElse -7L) PrintResult("28UL OrElse 28UL", 28UL OrElse 28UL) PrintResult("28UL OrElse -9D", 28UL OrElse -9D) PrintResult("28UL OrElse 10.0F", 28UL OrElse 10.0F) PrintResult("28UL OrElse -11.0R", 28UL OrElse -11.0R) PrintResult("28UL OrElse ""12""", 28UL OrElse "12") PrintResult("28UL OrElse TypeCode.Double", 28UL OrElse TypeCode.Double) PrintResult("-9D OrElse False", -9D OrElse False) PrintResult("-9D OrElse True", -9D OrElse True) PrintResult("-9D OrElse System.SByte.MinValue", -9D OrElse System.SByte.MinValue) PrintResult("-9D OrElse System.Byte.MaxValue", -9D OrElse System.Byte.MaxValue) PrintResult("-9D OrElse -3S", -9D OrElse -3S) PrintResult("-9D OrElse 24US", -9D OrElse 24US) PrintResult("-9D OrElse -5I", -9D OrElse -5I) PrintResult("-9D OrElse 26UI", -9D OrElse 26UI) PrintResult("-9D OrElse -7L", -9D OrElse -7L) PrintResult("-9D OrElse 28UL", -9D OrElse 28UL) PrintResult("-9D OrElse -9D", -9D OrElse -9D) PrintResult("-9D OrElse 10.0F", -9D OrElse 10.0F) PrintResult("-9D OrElse -11.0R", -9D OrElse -11.0R) PrintResult("-9D OrElse ""12""", -9D OrElse "12") PrintResult("-9D OrElse TypeCode.Double", -9D OrElse TypeCode.Double) PrintResult("10.0F OrElse False", 10.0F OrElse False) PrintResult("10.0F OrElse True", 10.0F OrElse True) PrintResult("10.0F OrElse System.SByte.MinValue", 10.0F OrElse System.SByte.MinValue) PrintResult("10.0F OrElse System.Byte.MaxValue", 10.0F OrElse System.Byte.MaxValue) PrintResult("10.0F OrElse -3S", 10.0F OrElse -3S) PrintResult("10.0F OrElse 24US", 10.0F OrElse 24US) PrintResult("10.0F OrElse -5I", 10.0F OrElse -5I) PrintResult("10.0F OrElse 26UI", 10.0F OrElse 26UI) PrintResult("10.0F OrElse -7L", 10.0F OrElse -7L) PrintResult("10.0F OrElse 28UL", 10.0F OrElse 28UL) PrintResult("10.0F OrElse -9D", 10.0F OrElse -9D) PrintResult("10.0F OrElse 10.0F", 10.0F OrElse 10.0F) PrintResult("10.0F OrElse -11.0R", 10.0F OrElse -11.0R) PrintResult("10.0F OrElse ""12""", 10.0F OrElse "12") PrintResult("10.0F OrElse TypeCode.Double", 10.0F OrElse TypeCode.Double) PrintResult("-11.0R OrElse False", -11.0R OrElse False) PrintResult("-11.0R OrElse True", -11.0R OrElse True) PrintResult("-11.0R OrElse System.SByte.MinValue", -11.0R OrElse System.SByte.MinValue) PrintResult("-11.0R OrElse System.Byte.MaxValue", -11.0R OrElse System.Byte.MaxValue) PrintResult("-11.0R OrElse -3S", -11.0R OrElse -3S) PrintResult("-11.0R OrElse 24US", -11.0R OrElse 24US) PrintResult("-11.0R OrElse -5I", -11.0R OrElse -5I) PrintResult("-11.0R OrElse 26UI", -11.0R OrElse 26UI) PrintResult("-11.0R OrElse -7L", -11.0R OrElse -7L) PrintResult("-11.0R OrElse 28UL", -11.0R OrElse 28UL) PrintResult("-11.0R OrElse -9D", -11.0R OrElse -9D) PrintResult("-11.0R OrElse 10.0F", -11.0R OrElse 10.0F) PrintResult("-11.0R OrElse -11.0R", -11.0R OrElse -11.0R) PrintResult("-11.0R OrElse ""12""", -11.0R OrElse "12") PrintResult("-11.0R OrElse TypeCode.Double", -11.0R OrElse TypeCode.Double) PrintResult("""12"" OrElse False", "12" OrElse False) PrintResult("""12"" OrElse True", "12" OrElse True) PrintResult("""12"" OrElse System.SByte.MinValue", "12" OrElse System.SByte.MinValue) PrintResult("""12"" OrElse System.Byte.MaxValue", "12" OrElse System.Byte.MaxValue) PrintResult("""12"" OrElse -3S", "12" OrElse -3S) PrintResult("""12"" OrElse 24US", "12" OrElse 24US) PrintResult("""12"" OrElse -5I", "12" OrElse -5I) PrintResult("""12"" OrElse 26UI", "12" OrElse 26UI) PrintResult("""12"" OrElse -7L", "12" OrElse -7L) PrintResult("""12"" OrElse 28UL", "12" OrElse 28UL) PrintResult("""12"" OrElse -9D", "12" OrElse -9D) PrintResult("""12"" OrElse 10.0F", "12" OrElse 10.0F) PrintResult("""12"" OrElse -11.0R", "12" OrElse -11.0R) PrintResult("""12"" OrElse ""12""", "12" OrElse "12") PrintResult("""12"" OrElse TypeCode.Double", "12" OrElse TypeCode.Double) PrintResult("TypeCode.Double OrElse False", TypeCode.Double OrElse False) PrintResult("TypeCode.Double OrElse True", TypeCode.Double OrElse True) PrintResult("TypeCode.Double OrElse System.SByte.MinValue", TypeCode.Double OrElse System.SByte.MinValue) PrintResult("TypeCode.Double OrElse System.Byte.MaxValue", TypeCode.Double OrElse System.Byte.MaxValue) PrintResult("TypeCode.Double OrElse -3S", TypeCode.Double OrElse -3S) PrintResult("TypeCode.Double OrElse 24US", TypeCode.Double OrElse 24US) PrintResult("TypeCode.Double OrElse -5I", TypeCode.Double OrElse -5I) PrintResult("TypeCode.Double OrElse 26UI", TypeCode.Double OrElse 26UI) PrintResult("TypeCode.Double OrElse -7L", TypeCode.Double OrElse -7L) PrintResult("TypeCode.Double OrElse 28UL", TypeCode.Double OrElse 28UL) PrintResult("TypeCode.Double OrElse -9D", TypeCode.Double OrElse -9D) PrintResult("TypeCode.Double OrElse 10.0F", TypeCode.Double OrElse 10.0F) PrintResult("TypeCode.Double OrElse -11.0R", TypeCode.Double OrElse -11.0R) PrintResult("TypeCode.Double OrElse ""12""", TypeCode.Double OrElse "12") PrintResult("TypeCode.Double OrElse TypeCode.Double", TypeCode.Double OrElse TypeCode.Double) PrintResult("False AndAlso False", False AndAlso False) PrintResult("False AndAlso True", False AndAlso True) PrintResult("False AndAlso System.SByte.MinValue", False AndAlso System.SByte.MinValue) PrintResult("False AndAlso System.Byte.MaxValue", False AndAlso System.Byte.MaxValue) PrintResult("False AndAlso -3S", False AndAlso -3S) PrintResult("False AndAlso 24US", False AndAlso 24US) PrintResult("False AndAlso -5I", False AndAlso -5I) PrintResult("False AndAlso 26UI", False AndAlso 26UI) PrintResult("False AndAlso -7L", False AndAlso -7L) PrintResult("False AndAlso 28UL", False AndAlso 28UL) PrintResult("False AndAlso -9D", False AndAlso -9D) PrintResult("False AndAlso 10.0F", False AndAlso 10.0F) PrintResult("False AndAlso -11.0R", False AndAlso -11.0R) PrintResult("False AndAlso ""12""", False AndAlso "12") PrintResult("False AndAlso TypeCode.Double", False AndAlso TypeCode.Double) PrintResult("True AndAlso False", True AndAlso False) PrintResult("True AndAlso True", True AndAlso True) PrintResult("True AndAlso System.SByte.MinValue", True AndAlso System.SByte.MinValue) PrintResult("True AndAlso System.Byte.MaxValue", True AndAlso System.Byte.MaxValue) PrintResult("True AndAlso -3S", True AndAlso -3S) PrintResult("True AndAlso 24US", True AndAlso 24US) PrintResult("True AndAlso -5I", True AndAlso -5I) PrintResult("True AndAlso 26UI", True AndAlso 26UI) PrintResult("True AndAlso -7L", True AndAlso -7L) PrintResult("True AndAlso 28UL", True AndAlso 28UL) PrintResult("True AndAlso -9D", True AndAlso -9D) PrintResult("True AndAlso 10.0F", True AndAlso 10.0F) PrintResult("True AndAlso -11.0R", True AndAlso -11.0R) PrintResult("True AndAlso ""12""", True AndAlso "12") PrintResult("True AndAlso TypeCode.Double", True AndAlso TypeCode.Double) PrintResult("System.SByte.MinValue AndAlso False", System.SByte.MinValue AndAlso False) PrintResult("System.SByte.MinValue AndAlso True", System.SByte.MinValue AndAlso True) PrintResult("System.SByte.MinValue AndAlso System.SByte.MinValue", System.SByte.MinValue AndAlso System.SByte.MinValue) PrintResult("System.SByte.MinValue AndAlso System.Byte.MaxValue", System.SByte.MinValue AndAlso System.Byte.MaxValue) PrintResult("System.SByte.MinValue AndAlso -3S", System.SByte.MinValue AndAlso -3S) PrintResult("System.SByte.MinValue AndAlso 24US", System.SByte.MinValue AndAlso 24US) PrintResult("System.SByte.MinValue AndAlso -5I", System.SByte.MinValue AndAlso -5I) PrintResult("System.SByte.MinValue AndAlso 26UI", System.SByte.MinValue AndAlso 26UI) PrintResult("System.SByte.MinValue AndAlso -7L", System.SByte.MinValue AndAlso -7L) PrintResult("System.SByte.MinValue AndAlso 28UL", System.SByte.MinValue AndAlso 28UL) PrintResult("System.SByte.MinValue AndAlso -9D", System.SByte.MinValue AndAlso -9D) PrintResult("System.SByte.MinValue AndAlso 10.0F", System.SByte.MinValue AndAlso 10.0F) PrintResult("System.SByte.MinValue AndAlso -11.0R", System.SByte.MinValue AndAlso -11.0R) PrintResult("System.SByte.MinValue AndAlso ""12""", System.SByte.MinValue AndAlso "12") PrintResult("System.SByte.MinValue AndAlso TypeCode.Double", System.SByte.MinValue AndAlso TypeCode.Double) PrintResult("System.Byte.MaxValue AndAlso False", System.Byte.MaxValue AndAlso False) PrintResult("System.Byte.MaxValue AndAlso True", System.Byte.MaxValue AndAlso True) PrintResult("System.Byte.MaxValue AndAlso System.SByte.MinValue", System.Byte.MaxValue AndAlso System.SByte.MinValue) PrintResult("System.Byte.MaxValue AndAlso System.Byte.MaxValue", System.Byte.MaxValue AndAlso System.Byte.MaxValue) PrintResult("System.Byte.MaxValue AndAlso -3S", System.Byte.MaxValue AndAlso -3S) PrintResult("System.Byte.MaxValue AndAlso 24US", System.Byte.MaxValue AndAlso 24US) PrintResult("System.Byte.MaxValue AndAlso -5I", System.Byte.MaxValue AndAlso -5I) PrintResult("System.Byte.MaxValue AndAlso 26UI", System.Byte.MaxValue AndAlso 26UI) PrintResult("System.Byte.MaxValue AndAlso -7L", System.Byte.MaxValue AndAlso -7L) PrintResult("System.Byte.MaxValue AndAlso 28UL", System.Byte.MaxValue AndAlso 28UL) PrintResult("System.Byte.MaxValue AndAlso -9D", System.Byte.MaxValue AndAlso -9D) PrintResult("System.Byte.MaxValue AndAlso 10.0F", System.Byte.MaxValue AndAlso 10.0F) PrintResult("System.Byte.MaxValue AndAlso -11.0R", System.Byte.MaxValue AndAlso -11.0R) PrintResult("System.Byte.MaxValue AndAlso ""12""", System.Byte.MaxValue AndAlso "12") PrintResult("System.Byte.MaxValue AndAlso TypeCode.Double", System.Byte.MaxValue AndAlso TypeCode.Double) PrintResult("-3S AndAlso False", -3S AndAlso False) PrintResult("-3S AndAlso True", -3S AndAlso True) PrintResult("-3S AndAlso System.SByte.MinValue", -3S AndAlso System.SByte.MinValue) PrintResult("-3S AndAlso System.Byte.MaxValue", -3S AndAlso System.Byte.MaxValue) PrintResult("-3S AndAlso -3S", -3S AndAlso -3S) PrintResult("-3S AndAlso 24US", -3S AndAlso 24US) PrintResult("-3S AndAlso -5I", -3S AndAlso -5I) PrintResult("-3S AndAlso 26UI", -3S AndAlso 26UI) PrintResult("-3S AndAlso -7L", -3S AndAlso -7L) PrintResult("-3S AndAlso 28UL", -3S AndAlso 28UL) PrintResult("-3S AndAlso -9D", -3S AndAlso -9D) PrintResult("-3S AndAlso 10.0F", -3S AndAlso 10.0F) PrintResult("-3S AndAlso -11.0R", -3S AndAlso -11.0R) PrintResult("-3S AndAlso ""12""", -3S AndAlso "12") PrintResult("-3S AndAlso TypeCode.Double", -3S AndAlso TypeCode.Double) PrintResult("24US AndAlso False", 24US AndAlso False) PrintResult("24US AndAlso True", 24US AndAlso True) PrintResult("24US AndAlso System.SByte.MinValue", 24US AndAlso System.SByte.MinValue) PrintResult("24US AndAlso System.Byte.MaxValue", 24US AndAlso System.Byte.MaxValue) PrintResult("24US AndAlso -3S", 24US AndAlso -3S) PrintResult("24US AndAlso 24US", 24US AndAlso 24US) PrintResult("24US AndAlso -5I", 24US AndAlso -5I) PrintResult("24US AndAlso 26UI", 24US AndAlso 26UI) PrintResult("24US AndAlso -7L", 24US AndAlso -7L) PrintResult("24US AndAlso 28UL", 24US AndAlso 28UL) PrintResult("24US AndAlso -9D", 24US AndAlso -9D) PrintResult("24US AndAlso 10.0F", 24US AndAlso 10.0F) PrintResult("24US AndAlso -11.0R", 24US AndAlso -11.0R) PrintResult("24US AndAlso ""12""", 24US AndAlso "12") PrintResult("24US AndAlso TypeCode.Double", 24US AndAlso TypeCode.Double) PrintResult("-5I AndAlso False", -5I AndAlso False) PrintResult("-5I AndAlso True", -5I AndAlso True) PrintResult("-5I AndAlso System.SByte.MinValue", -5I AndAlso System.SByte.MinValue) PrintResult("-5I AndAlso System.Byte.MaxValue", -5I AndAlso System.Byte.MaxValue) PrintResult("-5I AndAlso -3S", -5I AndAlso -3S) PrintResult("-5I AndAlso 24US", -5I AndAlso 24US) PrintResult("-5I AndAlso -5I", -5I AndAlso -5I) PrintResult("-5I AndAlso 26UI", -5I AndAlso 26UI) PrintResult("-5I AndAlso -7L", -5I AndAlso -7L) PrintResult("-5I AndAlso 28UL", -5I AndAlso 28UL) PrintResult("-5I AndAlso -9D", -5I AndAlso -9D) PrintResult("-5I AndAlso 10.0F", -5I AndAlso 10.0F) PrintResult("-5I AndAlso -11.0R", -5I AndAlso -11.0R) PrintResult("-5I AndAlso ""12""", -5I AndAlso "12") PrintResult("-5I AndAlso TypeCode.Double", -5I AndAlso TypeCode.Double) PrintResult("26UI AndAlso False", 26UI AndAlso False) PrintResult("26UI AndAlso True", 26UI AndAlso True) PrintResult("26UI AndAlso System.SByte.MinValue", 26UI AndAlso System.SByte.MinValue) PrintResult("26UI AndAlso System.Byte.MaxValue", 26UI AndAlso System.Byte.MaxValue) PrintResult("26UI AndAlso -3S", 26UI AndAlso -3S) PrintResult("26UI AndAlso 24US", 26UI AndAlso 24US) PrintResult("26UI AndAlso -5I", 26UI AndAlso -5I) PrintResult("26UI AndAlso 26UI", 26UI AndAlso 26UI) PrintResult("26UI AndAlso -7L", 26UI AndAlso -7L) PrintResult("26UI AndAlso 28UL", 26UI AndAlso 28UL) PrintResult("26UI AndAlso -9D", 26UI AndAlso -9D) PrintResult("26UI AndAlso 10.0F", 26UI AndAlso 10.0F) PrintResult("26UI AndAlso -11.0R", 26UI AndAlso -11.0R) PrintResult("26UI AndAlso ""12""", 26UI AndAlso "12") PrintResult("26UI AndAlso TypeCode.Double", 26UI AndAlso TypeCode.Double) PrintResult("-7L AndAlso False", -7L AndAlso False) PrintResult("-7L AndAlso True", -7L AndAlso True) PrintResult("-7L AndAlso System.SByte.MinValue", -7L AndAlso System.SByte.MinValue) PrintResult("-7L AndAlso System.Byte.MaxValue", -7L AndAlso System.Byte.MaxValue) PrintResult("-7L AndAlso -3S", -7L AndAlso -3S) PrintResult("-7L AndAlso 24US", -7L AndAlso 24US) PrintResult("-7L AndAlso -5I", -7L AndAlso -5I) PrintResult("-7L AndAlso 26UI", -7L AndAlso 26UI) PrintResult("-7L AndAlso -7L", -7L AndAlso -7L) PrintResult("-7L AndAlso 28UL", -7L AndAlso 28UL) PrintResult("-7L AndAlso -9D", -7L AndAlso -9D) PrintResult("-7L AndAlso 10.0F", -7L AndAlso 10.0F) PrintResult("-7L AndAlso -11.0R", -7L AndAlso -11.0R) PrintResult("-7L AndAlso ""12""", -7L AndAlso "12") PrintResult("-7L AndAlso TypeCode.Double", -7L AndAlso TypeCode.Double) PrintResult("28UL AndAlso False", 28UL AndAlso False) PrintResult("28UL AndAlso True", 28UL AndAlso True) PrintResult("28UL AndAlso System.SByte.MinValue", 28UL AndAlso System.SByte.MinValue) PrintResult("28UL AndAlso System.Byte.MaxValue", 28UL AndAlso System.Byte.MaxValue) PrintResult("28UL AndAlso -3S", 28UL AndAlso -3S) PrintResult("28UL AndAlso 24US", 28UL AndAlso 24US) PrintResult("28UL AndAlso -5I", 28UL AndAlso -5I) PrintResult("28UL AndAlso 26UI", 28UL AndAlso 26UI) PrintResult("28UL AndAlso -7L", 28UL AndAlso -7L) PrintResult("28UL AndAlso 28UL", 28UL AndAlso 28UL) PrintResult("28UL AndAlso -9D", 28UL AndAlso -9D) PrintResult("28UL AndAlso 10.0F", 28UL AndAlso 10.0F) PrintResult("28UL AndAlso -11.0R", 28UL AndAlso -11.0R) PrintResult("28UL AndAlso ""12""", 28UL AndAlso "12") PrintResult("28UL AndAlso TypeCode.Double", 28UL AndAlso TypeCode.Double) PrintResult("-9D AndAlso False", -9D AndAlso False) PrintResult("-9D AndAlso True", -9D AndAlso True) PrintResult("-9D AndAlso System.SByte.MinValue", -9D AndAlso System.SByte.MinValue) PrintResult("-9D AndAlso System.Byte.MaxValue", -9D AndAlso System.Byte.MaxValue) PrintResult("-9D AndAlso -3S", -9D AndAlso -3S) PrintResult("-9D AndAlso 24US", -9D AndAlso 24US) PrintResult("-9D AndAlso -5I", -9D AndAlso -5I) PrintResult("-9D AndAlso 26UI", -9D AndAlso 26UI) PrintResult("-9D AndAlso -7L", -9D AndAlso -7L) PrintResult("-9D AndAlso 28UL", -9D AndAlso 28UL) PrintResult("-9D AndAlso -9D", -9D AndAlso -9D) PrintResult("-9D AndAlso 10.0F", -9D AndAlso 10.0F) PrintResult("-9D AndAlso -11.0R", -9D AndAlso -11.0R) PrintResult("-9D AndAlso ""12""", -9D AndAlso "12") PrintResult("-9D AndAlso TypeCode.Double", -9D AndAlso TypeCode.Double) PrintResult("10.0F AndAlso False", 10.0F AndAlso False) PrintResult("10.0F AndAlso True", 10.0F AndAlso True) PrintResult("10.0F AndAlso System.SByte.MinValue", 10.0F AndAlso System.SByte.MinValue) PrintResult("10.0F AndAlso System.Byte.MaxValue", 10.0F AndAlso System.Byte.MaxValue) PrintResult("10.0F AndAlso -3S", 10.0F AndAlso -3S) PrintResult("10.0F AndAlso 24US", 10.0F AndAlso 24US) PrintResult("10.0F AndAlso -5I", 10.0F AndAlso -5I) PrintResult("10.0F AndAlso 26UI", 10.0F AndAlso 26UI) PrintResult("10.0F AndAlso -7L", 10.0F AndAlso -7L) PrintResult("10.0F AndAlso 28UL", 10.0F AndAlso 28UL) PrintResult("10.0F AndAlso -9D", 10.0F AndAlso -9D) PrintResult("10.0F AndAlso 10.0F", 10.0F AndAlso 10.0F) PrintResult("10.0F AndAlso -11.0R", 10.0F AndAlso -11.0R) PrintResult("10.0F AndAlso ""12""", 10.0F AndAlso "12") PrintResult("10.0F AndAlso TypeCode.Double", 10.0F AndAlso TypeCode.Double) PrintResult("-11.0R AndAlso False", -11.0R AndAlso False) PrintResult("-11.0R AndAlso True", -11.0R AndAlso True) PrintResult("-11.0R AndAlso System.SByte.MinValue", -11.0R AndAlso System.SByte.MinValue) PrintResult("-11.0R AndAlso System.Byte.MaxValue", -11.0R AndAlso System.Byte.MaxValue) PrintResult("-11.0R AndAlso -3S", -11.0R AndAlso -3S) PrintResult("-11.0R AndAlso 24US", -11.0R AndAlso 24US) PrintResult("-11.0R AndAlso -5I", -11.0R AndAlso -5I) PrintResult("-11.0R AndAlso 26UI", -11.0R AndAlso 26UI) PrintResult("-11.0R AndAlso -7L", -11.0R AndAlso -7L) PrintResult("-11.0R AndAlso 28UL", -11.0R AndAlso 28UL) PrintResult("-11.0R AndAlso -9D", -11.0R AndAlso -9D) PrintResult("-11.0R AndAlso 10.0F", -11.0R AndAlso 10.0F) PrintResult("-11.0R AndAlso -11.0R", -11.0R AndAlso -11.0R) PrintResult("-11.0R AndAlso ""12""", -11.0R AndAlso "12") PrintResult("-11.0R AndAlso TypeCode.Double", -11.0R AndAlso TypeCode.Double) PrintResult("""12"" AndAlso False", "12" AndAlso False) PrintResult("""12"" AndAlso True", "12" AndAlso True) PrintResult("""12"" AndAlso System.SByte.MinValue", "12" AndAlso System.SByte.MinValue) PrintResult("""12"" AndAlso System.Byte.MaxValue", "12" AndAlso System.Byte.MaxValue) PrintResult("""12"" AndAlso -3S", "12" AndAlso -3S) PrintResult("""12"" AndAlso 24US", "12" AndAlso 24US) PrintResult("""12"" AndAlso -5I", "12" AndAlso -5I) PrintResult("""12"" AndAlso 26UI", "12" AndAlso 26UI) PrintResult("""12"" AndAlso -7L", "12" AndAlso -7L) PrintResult("""12"" AndAlso 28UL", "12" AndAlso 28UL) PrintResult("""12"" AndAlso -9D", "12" AndAlso -9D) PrintResult("""12"" AndAlso 10.0F", "12" AndAlso 10.0F) PrintResult("""12"" AndAlso -11.0R", "12" AndAlso -11.0R) PrintResult("""12"" AndAlso ""12""", "12" AndAlso "12") PrintResult("""12"" AndAlso TypeCode.Double", "12" AndAlso TypeCode.Double) PrintResult("TypeCode.Double AndAlso False", TypeCode.Double AndAlso False) PrintResult("TypeCode.Double AndAlso True", TypeCode.Double AndAlso True) PrintResult("TypeCode.Double AndAlso System.SByte.MinValue", TypeCode.Double AndAlso System.SByte.MinValue) PrintResult("TypeCode.Double AndAlso System.Byte.MaxValue", TypeCode.Double AndAlso System.Byte.MaxValue) PrintResult("TypeCode.Double AndAlso -3S", TypeCode.Double AndAlso -3S) PrintResult("TypeCode.Double AndAlso 24US", TypeCode.Double AndAlso 24US) PrintResult("TypeCode.Double AndAlso -5I", TypeCode.Double AndAlso -5I) PrintResult("TypeCode.Double AndAlso 26UI", TypeCode.Double AndAlso 26UI) PrintResult("TypeCode.Double AndAlso -7L", TypeCode.Double AndAlso -7L) PrintResult("TypeCode.Double AndAlso 28UL", TypeCode.Double AndAlso 28UL) PrintResult("TypeCode.Double AndAlso -9D", TypeCode.Double AndAlso -9D) PrintResult("TypeCode.Double AndAlso 10.0F", TypeCode.Double AndAlso 10.0F) PrintResult("TypeCode.Double AndAlso -11.0R", TypeCode.Double AndAlso -11.0R) PrintResult("TypeCode.Double AndAlso ""12""", TypeCode.Double AndAlso "12") PrintResult("TypeCode.Double AndAlso TypeCode.Double", TypeCode.Double AndAlso TypeCode.Double) PrintResult("False & False", False & False) PrintResult("False & True", False & True) PrintResult("False & System.SByte.MinValue", False & System.SByte.MinValue) PrintResult("False & System.Byte.MaxValue", False & System.Byte.MaxValue) PrintResult("False & -3S", False & -3S) PrintResult("False & 24US", False & 24US) PrintResult("False & -5I", False & -5I) PrintResult("False & 26UI", False & 26UI) PrintResult("False & -7L", False & -7L) PrintResult("False & 28UL", False & 28UL) PrintResult("False & -9D", False & -9D) PrintResult("False & 10.0F", False & 10.0F) PrintResult("False & -11.0R", False & -11.0R) PrintResult("False & ""12""", False & "12") PrintResult("False & TypeCode.Double", False & TypeCode.Double) PrintResult("True & False", True & False) PrintResult("True & True", True & True) PrintResult("True & System.SByte.MinValue", True & System.SByte.MinValue) PrintResult("True & System.Byte.MaxValue", True & System.Byte.MaxValue) PrintResult("True & -3S", True & -3S) PrintResult("True & 24US", True & 24US) PrintResult("True & -5I", True & -5I) PrintResult("True & 26UI", True & 26UI) PrintResult("True & -7L", True & -7L) PrintResult("True & 28UL", True & 28UL) PrintResult("True & -9D", True & -9D) PrintResult("True & 10.0F", True & 10.0F) PrintResult("True & -11.0R", True & -11.0R) PrintResult("True & ""12""", True & "12") PrintResult("True & TypeCode.Double", True & TypeCode.Double) PrintResult("System.SByte.MinValue & False", System.SByte.MinValue & False) PrintResult("System.SByte.MinValue & True", System.SByte.MinValue & True) PrintResult("System.SByte.MinValue & System.SByte.MinValue", System.SByte.MinValue & System.SByte.MinValue) PrintResult("System.SByte.MinValue & System.Byte.MaxValue", System.SByte.MinValue & System.Byte.MaxValue) PrintResult("System.SByte.MinValue & -3S", System.SByte.MinValue & -3S) PrintResult("System.SByte.MinValue & 24US", System.SByte.MinValue & 24US) PrintResult("System.SByte.MinValue & -5I", System.SByte.MinValue & -5I) PrintResult("System.SByte.MinValue & 26UI", System.SByte.MinValue & 26UI) PrintResult("System.SByte.MinValue & -7L", System.SByte.MinValue & -7L) PrintResult("System.SByte.MinValue & 28UL", System.SByte.MinValue & 28UL) PrintResult("System.SByte.MinValue & -9D", System.SByte.MinValue & -9D) PrintResult("System.SByte.MinValue & 10.0F", System.SByte.MinValue & 10.0F) PrintResult("System.SByte.MinValue & -11.0R", System.SByte.MinValue & -11.0R) PrintResult("System.SByte.MinValue & ""12""", System.SByte.MinValue & "12") PrintResult("System.SByte.MinValue & TypeCode.Double", System.SByte.MinValue & TypeCode.Double) PrintResult("System.Byte.MaxValue & False", System.Byte.MaxValue & False) PrintResult("System.Byte.MaxValue & True", System.Byte.MaxValue & True) PrintResult("System.Byte.MaxValue & System.SByte.MinValue", System.Byte.MaxValue & System.SByte.MinValue) PrintResult("System.Byte.MaxValue & System.Byte.MaxValue", System.Byte.MaxValue & System.Byte.MaxValue) PrintResult("System.Byte.MaxValue & -3S", System.Byte.MaxValue & -3S) PrintResult("System.Byte.MaxValue & 24US", System.Byte.MaxValue & 24US) PrintResult("System.Byte.MaxValue & -5I", System.Byte.MaxValue & -5I) PrintResult("System.Byte.MaxValue & 26UI", System.Byte.MaxValue & 26UI) PrintResult("System.Byte.MaxValue & -7L", System.Byte.MaxValue & -7L) PrintResult("System.Byte.MaxValue & 28UL", System.Byte.MaxValue & 28UL) PrintResult("System.Byte.MaxValue & -9D", System.Byte.MaxValue & -9D) PrintResult("System.Byte.MaxValue & 10.0F", System.Byte.MaxValue & 10.0F) PrintResult("System.Byte.MaxValue & -11.0R", System.Byte.MaxValue & -11.0R) PrintResult("System.Byte.MaxValue & ""12""", System.Byte.MaxValue & "12") PrintResult("System.Byte.MaxValue & TypeCode.Double", System.Byte.MaxValue & TypeCode.Double) PrintResult("-3S & False", -3S & False) PrintResult("-3S & True", -3S & True) PrintResult("-3S & System.SByte.MinValue", -3S & System.SByte.MinValue) PrintResult("-3S & System.Byte.MaxValue", -3S & System.Byte.MaxValue) PrintResult("-3S & -3S", -3S & -3S) PrintResult("-3S & 24US", -3S & 24US) PrintResult("-3S & -5I", -3S & -5I) PrintResult("-3S & 26UI", -3S & 26UI) PrintResult("-3S & -7L", -3S & -7L) PrintResult("-3S & 28UL", -3S & 28UL) PrintResult("-3S & -9D", -3S & -9D) PrintResult("-3S & 10.0F", -3S & 10.0F) PrintResult("-3S & -11.0R", -3S & -11.0R) PrintResult("-3S & ""12""", -3S & "12") PrintResult("-3S & TypeCode.Double", -3S & TypeCode.Double) PrintResult("24US & False", 24US & False) PrintResult("24US & True", 24US & True) PrintResult("24US & System.SByte.MinValue", 24US & System.SByte.MinValue) PrintResult("24US & System.Byte.MaxValue", 24US & System.Byte.MaxValue) PrintResult("24US & -3S", 24US & -3S) PrintResult("24US & 24US", 24US & 24US) PrintResult("24US & -5I", 24US & -5I) PrintResult("24US & 26UI", 24US & 26UI) PrintResult("24US & -7L", 24US & -7L) PrintResult("24US & 28UL", 24US & 28UL) PrintResult("24US & -9D", 24US & -9D) PrintResult("24US & 10.0F", 24US & 10.0F) PrintResult("24US & -11.0R", 24US & -11.0R) PrintResult("24US & ""12""", 24US & "12") PrintResult("24US & TypeCode.Double", 24US & TypeCode.Double) PrintResult("-5I & False", -5I & False) PrintResult("-5I & True", -5I & True) PrintResult("-5I & System.SByte.MinValue", -5I & System.SByte.MinValue) PrintResult("-5I & System.Byte.MaxValue", -5I & System.Byte.MaxValue) PrintResult("-5I & -3S", -5I & -3S) PrintResult("-5I & 24US", -5I & 24US) PrintResult("-5I & -5I", -5I & -5I) PrintResult("-5I & 26UI", -5I & 26UI) PrintResult("-5I & -7L", -5I & -7L) PrintResult("-5I & 28UL", -5I & 28UL) PrintResult("-5I & -9D", -5I & -9D) PrintResult("-5I & 10.0F", -5I & 10.0F) PrintResult("-5I & -11.0R", -5I & -11.0R) PrintResult("-5I & ""12""", -5I & "12") PrintResult("-5I & TypeCode.Double", -5I & TypeCode.Double) PrintResult("26UI & False", 26UI & False) PrintResult("26UI & True", 26UI & True) PrintResult("26UI & System.SByte.MinValue", 26UI & System.SByte.MinValue) PrintResult("26UI & System.Byte.MaxValue", 26UI & System.Byte.MaxValue) PrintResult("26UI & -3S", 26UI & -3S) PrintResult("26UI & 24US", 26UI & 24US) PrintResult("26UI & -5I", 26UI & -5I) PrintResult("26UI & 26UI", 26UI & 26UI) PrintResult("26UI & -7L", 26UI & -7L) PrintResult("26UI & 28UL", 26UI & 28UL) PrintResult("26UI & -9D", 26UI & -9D) PrintResult("26UI & 10.0F", 26UI & 10.0F) PrintResult("26UI & -11.0R", 26UI & -11.0R) PrintResult("26UI & ""12""", 26UI & "12") PrintResult("26UI & TypeCode.Double", 26UI & TypeCode.Double) PrintResult("-7L & False", -7L & False) PrintResult("-7L & True", -7L & True) PrintResult("-7L & System.SByte.MinValue", -7L & System.SByte.MinValue) PrintResult("-7L & System.Byte.MaxValue", -7L & System.Byte.MaxValue) PrintResult("-7L & -3S", -7L & -3S) PrintResult("-7L & 24US", -7L & 24US) PrintResult("-7L & -5I", -7L & -5I) PrintResult("-7L & 26UI", -7L & 26UI) PrintResult("-7L & -7L", -7L & -7L) PrintResult("-7L & 28UL", -7L & 28UL) PrintResult("-7L & -9D", -7L & -9D) PrintResult("-7L & 10.0F", -7L & 10.0F) PrintResult("-7L & -11.0R", -7L & -11.0R) PrintResult("-7L & ""12""", -7L & "12") PrintResult("-7L & TypeCode.Double", -7L & TypeCode.Double) PrintResult("28UL & False", 28UL & False) PrintResult("28UL & True", 28UL & True) PrintResult("28UL & System.SByte.MinValue", 28UL & System.SByte.MinValue) PrintResult("28UL & System.Byte.MaxValue", 28UL & System.Byte.MaxValue) PrintResult("28UL & -3S", 28UL & -3S) PrintResult("28UL & 24US", 28UL & 24US) PrintResult("28UL & -5I", 28UL & -5I) PrintResult("28UL & 26UI", 28UL & 26UI) PrintResult("28UL & -7L", 28UL & -7L) PrintResult("28UL & 28UL", 28UL & 28UL) PrintResult("28UL & -9D", 28UL & -9D) PrintResult("28UL & 10.0F", 28UL & 10.0F) PrintResult("28UL & -11.0R", 28UL & -11.0R) PrintResult("28UL & ""12""", 28UL & "12") PrintResult("28UL & TypeCode.Double", 28UL & TypeCode.Double) PrintResult("-9D & False", -9D & False) PrintResult("-9D & True", -9D & True) PrintResult("-9D & System.SByte.MinValue", -9D & System.SByte.MinValue) PrintResult("-9D & System.Byte.MaxValue", -9D & System.Byte.MaxValue) PrintResult("-9D & -3S", -9D & -3S) PrintResult("-9D & 24US", -9D & 24US) PrintResult("-9D & -5I", -9D & -5I) PrintResult("-9D & 26UI", -9D & 26UI) PrintResult("-9D & -7L", -9D & -7L) PrintResult("-9D & 28UL", -9D & 28UL) PrintResult("-9D & -9D", -9D & -9D) PrintResult("-9D & 10.0F", -9D & 10.0F) PrintResult("-9D & -11.0R", -9D & -11.0R) PrintResult("-9D & ""12""", -9D & "12") PrintResult("-9D & TypeCode.Double", -9D & TypeCode.Double) PrintResult("10.0F & False", 10.0F & False) PrintResult("10.0F & True", 10.0F & True) PrintResult("10.0F & System.SByte.MinValue", 10.0F & System.SByte.MinValue) PrintResult("10.0F & System.Byte.MaxValue", 10.0F & System.Byte.MaxValue) PrintResult("10.0F & -3S", 10.0F & -3S) PrintResult("10.0F & 24US", 10.0F & 24US) PrintResult("10.0F & -5I", 10.0F & -5I) PrintResult("10.0F & 26UI", 10.0F & 26UI) PrintResult("10.0F & -7L", 10.0F & -7L) PrintResult("10.0F & 28UL", 10.0F & 28UL) PrintResult("10.0F & -9D", 10.0F & -9D) PrintResult("10.0F & 10.0F", 10.0F & 10.0F) PrintResult("10.0F & -11.0R", 10.0F & -11.0R) PrintResult("10.0F & ""12""", 10.0F & "12") PrintResult("10.0F & TypeCode.Double", 10.0F & TypeCode.Double) PrintResult("-11.0R & False", -11.0R & False) PrintResult("-11.0R & True", -11.0R & True) PrintResult("-11.0R & System.SByte.MinValue", -11.0R & System.SByte.MinValue) PrintResult("-11.0R & System.Byte.MaxValue", -11.0R & System.Byte.MaxValue) PrintResult("-11.0R & -3S", -11.0R & -3S) PrintResult("-11.0R & 24US", -11.0R & 24US) PrintResult("-11.0R & -5I", -11.0R & -5I) PrintResult("-11.0R & 26UI", -11.0R & 26UI) PrintResult("-11.0R & -7L", -11.0R & -7L) PrintResult("-11.0R & 28UL", -11.0R & 28UL) PrintResult("-11.0R & -9D", -11.0R & -9D) PrintResult("-11.0R & 10.0F", -11.0R & 10.0F) PrintResult("-11.0R & -11.0R", -11.0R & -11.0R) PrintResult("-11.0R & ""12""", -11.0R & "12") PrintResult("-11.0R & TypeCode.Double", -11.0R & TypeCode.Double) PrintResult("""12"" & False", "12" & False) PrintResult("""12"" & True", "12" & True) PrintResult("""12"" & System.SByte.MinValue", "12" & System.SByte.MinValue) PrintResult("""12"" & System.Byte.MaxValue", "12" & System.Byte.MaxValue) PrintResult("""12"" & -3S", "12" & -3S) PrintResult("""12"" & 24US", "12" & 24US) PrintResult("""12"" & -5I", "12" & -5I) PrintResult("""12"" & 26UI", "12" & 26UI) PrintResult("""12"" & -7L", "12" & -7L) PrintResult("""12"" & 28UL", "12" & 28UL) PrintResult("""12"" & -9D", "12" & -9D) PrintResult("""12"" & 10.0F", "12" & 10.0F) PrintResult("""12"" & -11.0R", "12" & -11.0R) PrintResult("""12"" & ""12""", "12" & "12") PrintResult("""12"" & TypeCode.Double", "12" & TypeCode.Double) PrintResult("TypeCode.Double & False", TypeCode.Double & False) PrintResult("TypeCode.Double & True", TypeCode.Double & True) PrintResult("TypeCode.Double & System.SByte.MinValue", TypeCode.Double & System.SByte.MinValue) PrintResult("TypeCode.Double & System.Byte.MaxValue", TypeCode.Double & System.Byte.MaxValue) PrintResult("TypeCode.Double & -3S", TypeCode.Double & -3S) PrintResult("TypeCode.Double & 24US", TypeCode.Double & 24US) PrintResult("TypeCode.Double & -5I", TypeCode.Double & -5I) PrintResult("TypeCode.Double & 26UI", TypeCode.Double & 26UI) PrintResult("TypeCode.Double & -7L", TypeCode.Double & -7L) PrintResult("TypeCode.Double & 28UL", TypeCode.Double & 28UL) PrintResult("TypeCode.Double & -9D", TypeCode.Double & -9D) PrintResult("TypeCode.Double & 10.0F", TypeCode.Double & 10.0F) PrintResult("TypeCode.Double & -11.0R", TypeCode.Double & -11.0R) PrintResult("TypeCode.Double & ""12""", TypeCode.Double & "12") PrintResult("TypeCode.Double & TypeCode.Double", TypeCode.Double & TypeCode.Double) PrintResult("False Like False", False Like False) PrintResult("False Like True", False Like True) PrintResult("False Like System.SByte.MinValue", False Like System.SByte.MinValue) PrintResult("False Like System.Byte.MaxValue", False Like System.Byte.MaxValue) PrintResult("False Like -3S", False Like -3S) PrintResult("False Like 24US", False Like 24US) PrintResult("False Like -5I", False Like -5I) PrintResult("False Like 26UI", False Like 26UI) PrintResult("False Like -7L", False Like -7L) PrintResult("False Like 28UL", False Like 28UL) PrintResult("False Like -9D", False Like -9D) PrintResult("False Like 10.0F", False Like 10.0F) PrintResult("False Like -11.0R", False Like -11.0R) PrintResult("False Like ""12""", False Like "12") PrintResult("False Like TypeCode.Double", False Like TypeCode.Double) PrintResult("True Like False", True Like False) PrintResult("True Like True", True Like True) PrintResult("True Like System.SByte.MinValue", True Like System.SByte.MinValue) PrintResult("True Like System.Byte.MaxValue", True Like System.Byte.MaxValue) PrintResult("True Like -3S", True Like -3S) PrintResult("True Like 24US", True Like 24US) PrintResult("True Like -5I", True Like -5I) PrintResult("True Like 26UI", True Like 26UI) PrintResult("True Like -7L", True Like -7L) PrintResult("True Like 28UL", True Like 28UL) PrintResult("True Like -9D", True Like -9D) PrintResult("True Like 10.0F", True Like 10.0F) PrintResult("True Like -11.0R", True Like -11.0R) PrintResult("True Like ""12""", True Like "12") PrintResult("True Like TypeCode.Double", True Like TypeCode.Double) PrintResult("System.SByte.MinValue Like False", System.SByte.MinValue Like False) PrintResult("System.SByte.MinValue Like True", System.SByte.MinValue Like True) PrintResult("System.SByte.MinValue Like System.SByte.MinValue", System.SByte.MinValue Like System.SByte.MinValue) PrintResult("System.SByte.MinValue Like System.Byte.MaxValue", System.SByte.MinValue Like System.Byte.MaxValue) PrintResult("System.SByte.MinValue Like -3S", System.SByte.MinValue Like -3S) PrintResult("System.SByte.MinValue Like 24US", System.SByte.MinValue Like 24US) PrintResult("System.SByte.MinValue Like -5I", System.SByte.MinValue Like -5I) PrintResult("System.SByte.MinValue Like 26UI", System.SByte.MinValue Like 26UI) PrintResult("System.SByte.MinValue Like -7L", System.SByte.MinValue Like -7L) PrintResult("System.SByte.MinValue Like 28UL", System.SByte.MinValue Like 28UL) PrintResult("System.SByte.MinValue Like -9D", System.SByte.MinValue Like -9D) PrintResult("System.SByte.MinValue Like 10.0F", System.SByte.MinValue Like 10.0F) PrintResult("System.SByte.MinValue Like -11.0R", System.SByte.MinValue Like -11.0R) PrintResult("System.SByte.MinValue Like ""12""", System.SByte.MinValue Like "12") PrintResult("System.SByte.MinValue Like TypeCode.Double", System.SByte.MinValue Like TypeCode.Double) PrintResult("System.Byte.MaxValue Like False", System.Byte.MaxValue Like False) PrintResult("System.Byte.MaxValue Like True", System.Byte.MaxValue Like True) PrintResult("System.Byte.MaxValue Like System.SByte.MinValue", System.Byte.MaxValue Like System.SByte.MinValue) PrintResult("System.Byte.MaxValue Like System.Byte.MaxValue", System.Byte.MaxValue Like System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Like -3S", System.Byte.MaxValue Like -3S) PrintResult("System.Byte.MaxValue Like 24US", System.Byte.MaxValue Like 24US) PrintResult("System.Byte.MaxValue Like -5I", System.Byte.MaxValue Like -5I) PrintResult("System.Byte.MaxValue Like 26UI", System.Byte.MaxValue Like 26UI) PrintResult("System.Byte.MaxValue Like -7L", System.Byte.MaxValue Like -7L) PrintResult("System.Byte.MaxValue Like 28UL", System.Byte.MaxValue Like 28UL) PrintResult("System.Byte.MaxValue Like -9D", System.Byte.MaxValue Like -9D) PrintResult("System.Byte.MaxValue Like 10.0F", System.Byte.MaxValue Like 10.0F) PrintResult("System.Byte.MaxValue Like -11.0R", System.Byte.MaxValue Like -11.0R) PrintResult("System.Byte.MaxValue Like ""12""", System.Byte.MaxValue Like "12") PrintResult("System.Byte.MaxValue Like TypeCode.Double", System.Byte.MaxValue Like TypeCode.Double) PrintResult("-3S Like False", -3S Like False) PrintResult("-3S Like True", -3S Like True) PrintResult("-3S Like System.SByte.MinValue", -3S Like System.SByte.MinValue) PrintResult("-3S Like System.Byte.MaxValue", -3S Like System.Byte.MaxValue) PrintResult("-3S Like -3S", -3S Like -3S) PrintResult("-3S Like 24US", -3S Like 24US) PrintResult("-3S Like -5I", -3S Like -5I) PrintResult("-3S Like 26UI", -3S Like 26UI) PrintResult("-3S Like -7L", -3S Like -7L) PrintResult("-3S Like 28UL", -3S Like 28UL) PrintResult("-3S Like -9D", -3S Like -9D) PrintResult("-3S Like 10.0F", -3S Like 10.0F) PrintResult("-3S Like -11.0R", -3S Like -11.0R) PrintResult("-3S Like ""12""", -3S Like "12") PrintResult("-3S Like TypeCode.Double", -3S Like TypeCode.Double) PrintResult("24US Like False", 24US Like False) PrintResult("24US Like True", 24US Like True) PrintResult("24US Like System.SByte.MinValue", 24US Like System.SByte.MinValue) PrintResult("24US Like System.Byte.MaxValue", 24US Like System.Byte.MaxValue) PrintResult("24US Like -3S", 24US Like -3S) PrintResult("24US Like 24US", 24US Like 24US) PrintResult("24US Like -5I", 24US Like -5I) PrintResult("24US Like 26UI", 24US Like 26UI) PrintResult("24US Like -7L", 24US Like -7L) PrintResult("24US Like 28UL", 24US Like 28UL) PrintResult("24US Like -9D", 24US Like -9D) PrintResult("24US Like 10.0F", 24US Like 10.0F) PrintResult("24US Like -11.0R", 24US Like -11.0R) PrintResult("24US Like ""12""", 24US Like "12") PrintResult("24US Like TypeCode.Double", 24US Like TypeCode.Double) PrintResult("-5I Like False", -5I Like False) PrintResult("-5I Like True", -5I Like True) PrintResult("-5I Like System.SByte.MinValue", -5I Like System.SByte.MinValue) PrintResult("-5I Like System.Byte.MaxValue", -5I Like System.Byte.MaxValue) PrintResult("-5I Like -3S", -5I Like -3S) PrintResult("-5I Like 24US", -5I Like 24US) PrintResult("-5I Like -5I", -5I Like -5I) PrintResult("-5I Like 26UI", -5I Like 26UI) PrintResult("-5I Like -7L", -5I Like -7L) PrintResult("-5I Like 28UL", -5I Like 28UL) PrintResult("-5I Like -9D", -5I Like -9D) PrintResult("-5I Like 10.0F", -5I Like 10.0F) PrintResult("-5I Like -11.0R", -5I Like -11.0R) PrintResult("-5I Like ""12""", -5I Like "12") PrintResult("-5I Like TypeCode.Double", -5I Like TypeCode.Double) PrintResult("26UI Like False", 26UI Like False) PrintResult("26UI Like True", 26UI Like True) PrintResult("26UI Like System.SByte.MinValue", 26UI Like System.SByte.MinValue) PrintResult("26UI Like System.Byte.MaxValue", 26UI Like System.Byte.MaxValue) PrintResult("26UI Like -3S", 26UI Like -3S) PrintResult("26UI Like 24US", 26UI Like 24US) PrintResult("26UI Like -5I", 26UI Like -5I) PrintResult("26UI Like 26UI", 26UI Like 26UI) PrintResult("26UI Like -7L", 26UI Like -7L) PrintResult("26UI Like 28UL", 26UI Like 28UL) PrintResult("26UI Like -9D", 26UI Like -9D) PrintResult("26UI Like 10.0F", 26UI Like 10.0F) PrintResult("26UI Like -11.0R", 26UI Like -11.0R) PrintResult("26UI Like ""12""", 26UI Like "12") PrintResult("26UI Like TypeCode.Double", 26UI Like TypeCode.Double) PrintResult("-7L Like False", -7L Like False) PrintResult("-7L Like True", -7L Like True) PrintResult("-7L Like System.SByte.MinValue", -7L Like System.SByte.MinValue) PrintResult("-7L Like System.Byte.MaxValue", -7L Like System.Byte.MaxValue) PrintResult("-7L Like -3S", -7L Like -3S) PrintResult("-7L Like 24US", -7L Like 24US) PrintResult("-7L Like -5I", -7L Like -5I) PrintResult("-7L Like 26UI", -7L Like 26UI) PrintResult("-7L Like -7L", -7L Like -7L) PrintResult("-7L Like 28UL", -7L Like 28UL) PrintResult("-7L Like -9D", -7L Like -9D) PrintResult("-7L Like 10.0F", -7L Like 10.0F) PrintResult("-7L Like -11.0R", -7L Like -11.0R) PrintResult("-7L Like ""12""", -7L Like "12") PrintResult("-7L Like TypeCode.Double", -7L Like TypeCode.Double) PrintResult("28UL Like False", 28UL Like False) PrintResult("28UL Like True", 28UL Like True) PrintResult("28UL Like System.SByte.MinValue", 28UL Like System.SByte.MinValue) PrintResult("28UL Like System.Byte.MaxValue", 28UL Like System.Byte.MaxValue) PrintResult("28UL Like -3S", 28UL Like -3S) PrintResult("28UL Like 24US", 28UL Like 24US) PrintResult("28UL Like -5I", 28UL Like -5I) PrintResult("28UL Like 26UI", 28UL Like 26UI) PrintResult("28UL Like -7L", 28UL Like -7L) PrintResult("28UL Like 28UL", 28UL Like 28UL) PrintResult("28UL Like -9D", 28UL Like -9D) PrintResult("28UL Like 10.0F", 28UL Like 10.0F) PrintResult("28UL Like -11.0R", 28UL Like -11.0R) PrintResult("28UL Like ""12""", 28UL Like "12") PrintResult("28UL Like TypeCode.Double", 28UL Like TypeCode.Double) PrintResult("-9D Like False", -9D Like False) PrintResult("-9D Like True", -9D Like True) PrintResult("-9D Like System.SByte.MinValue", -9D Like System.SByte.MinValue) PrintResult("-9D Like System.Byte.MaxValue", -9D Like System.Byte.MaxValue) PrintResult("-9D Like -3S", -9D Like -3S) PrintResult("-9D Like 24US", -9D Like 24US) PrintResult("-9D Like -5I", -9D Like -5I) PrintResult("-9D Like 26UI", -9D Like 26UI) PrintResult("-9D Like -7L", -9D Like -7L) PrintResult("-9D Like 28UL", -9D Like 28UL) PrintResult("-9D Like -9D", -9D Like -9D) PrintResult("-9D Like 10.0F", -9D Like 10.0F) PrintResult("-9D Like -11.0R", -9D Like -11.0R) PrintResult("-9D Like ""12""", -9D Like "12") PrintResult("-9D Like TypeCode.Double", -9D Like TypeCode.Double) PrintResult("10.0F Like False", 10.0F Like False) PrintResult("10.0F Like True", 10.0F Like True) PrintResult("10.0F Like System.SByte.MinValue", 10.0F Like System.SByte.MinValue) PrintResult("10.0F Like System.Byte.MaxValue", 10.0F Like System.Byte.MaxValue) PrintResult("10.0F Like -3S", 10.0F Like -3S) PrintResult("10.0F Like 24US", 10.0F Like 24US) PrintResult("10.0F Like -5I", 10.0F Like -5I) PrintResult("10.0F Like 26UI", 10.0F Like 26UI) PrintResult("10.0F Like -7L", 10.0F Like -7L) PrintResult("10.0F Like 28UL", 10.0F Like 28UL) PrintResult("10.0F Like -9D", 10.0F Like -9D) PrintResult("10.0F Like 10.0F", 10.0F Like 10.0F) PrintResult("10.0F Like -11.0R", 10.0F Like -11.0R) PrintResult("10.0F Like ""12""", 10.0F Like "12") PrintResult("10.0F Like TypeCode.Double", 10.0F Like TypeCode.Double) PrintResult("-11.0R Like False", -11.0R Like False) PrintResult("-11.0R Like True", -11.0R Like True) PrintResult("-11.0R Like System.SByte.MinValue", -11.0R Like System.SByte.MinValue) PrintResult("-11.0R Like System.Byte.MaxValue", -11.0R Like System.Byte.MaxValue) PrintResult("-11.0R Like -3S", -11.0R Like -3S) PrintResult("-11.0R Like 24US", -11.0R Like 24US) PrintResult("-11.0R Like -5I", -11.0R Like -5I) PrintResult("-11.0R Like 26UI", -11.0R Like 26UI) PrintResult("-11.0R Like -7L", -11.0R Like -7L) PrintResult("-11.0R Like 28UL", -11.0R Like 28UL) PrintResult("-11.0R Like -9D", -11.0R Like -9D) PrintResult("-11.0R Like 10.0F", -11.0R Like 10.0F) PrintResult("-11.0R Like -11.0R", -11.0R Like -11.0R) PrintResult("-11.0R Like ""12""", -11.0R Like "12") PrintResult("-11.0R Like TypeCode.Double", -11.0R Like TypeCode.Double) PrintResult("""12"" Like False", "12" Like False) PrintResult("""12"" Like True", "12" Like True) PrintResult("""12"" Like System.SByte.MinValue", "12" Like System.SByte.MinValue) PrintResult("""12"" Like System.Byte.MaxValue", "12" Like System.Byte.MaxValue) PrintResult("""12"" Like -3S", "12" Like -3S) PrintResult("""12"" Like 24US", "12" Like 24US) PrintResult("""12"" Like -5I", "12" Like -5I) PrintResult("""12"" Like 26UI", "12" Like 26UI) PrintResult("""12"" Like -7L", "12" Like -7L) PrintResult("""12"" Like 28UL", "12" Like 28UL) PrintResult("""12"" Like -9D", "12" Like -9D) PrintResult("""12"" Like 10.0F", "12" Like 10.0F) PrintResult("""12"" Like -11.0R", "12" Like -11.0R) PrintResult("""12"" Like ""12""", "12" Like "12") PrintResult("""12"" Like TypeCode.Double", "12" Like TypeCode.Double) PrintResult("TypeCode.Double Like False", TypeCode.Double Like False) PrintResult("TypeCode.Double Like True", TypeCode.Double Like True) PrintResult("TypeCode.Double Like System.SByte.MinValue", TypeCode.Double Like System.SByte.MinValue) PrintResult("TypeCode.Double Like System.Byte.MaxValue", TypeCode.Double Like System.Byte.MaxValue) PrintResult("TypeCode.Double Like -3S", TypeCode.Double Like -3S) PrintResult("TypeCode.Double Like 24US", TypeCode.Double Like 24US) PrintResult("TypeCode.Double Like -5I", TypeCode.Double Like -5I) PrintResult("TypeCode.Double Like 26UI", TypeCode.Double Like 26UI) PrintResult("TypeCode.Double Like -7L", TypeCode.Double Like -7L) PrintResult("TypeCode.Double Like 28UL", TypeCode.Double Like 28UL) PrintResult("TypeCode.Double Like -9D", TypeCode.Double Like -9D) PrintResult("TypeCode.Double Like 10.0F", TypeCode.Double Like 10.0F) PrintResult("TypeCode.Double Like -11.0R", TypeCode.Double Like -11.0R) PrintResult("TypeCode.Double Like ""12""", TypeCode.Double Like "12") PrintResult("TypeCode.Double Like TypeCode.Double", TypeCode.Double Like TypeCode.Double) PrintResult("False = False", False = False) PrintResult("False = True", False = True) PrintResult("False = System.SByte.MinValue", False = System.SByte.MinValue) PrintResult("False = System.Byte.MaxValue", False = System.Byte.MaxValue) PrintResult("False = -3S", False = -3S) PrintResult("False = 24US", False = 24US) PrintResult("False = -5I", False = -5I) PrintResult("False = 26UI", False = 26UI) PrintResult("False = -7L", False = -7L) PrintResult("False = 28UL", False = 28UL) PrintResult("False = -9D", False = -9D) PrintResult("False = 10.0F", False = 10.0F) PrintResult("False = -11.0R", False = -11.0R) PrintResult("False = ""12""", False = "12") PrintResult("False = TypeCode.Double", False = TypeCode.Double) PrintResult("True = False", True = False) PrintResult("True = True", True = True) PrintResult("True = System.SByte.MinValue", True = System.SByte.MinValue) PrintResult("True = System.Byte.MaxValue", True = System.Byte.MaxValue) PrintResult("True = -3S", True = -3S) PrintResult("True = 24US", True = 24US) PrintResult("True = -5I", True = -5I) PrintResult("True = 26UI", True = 26UI) PrintResult("True = -7L", True = -7L) PrintResult("True = 28UL", True = 28UL) PrintResult("True = -9D", True = -9D) PrintResult("True = 10.0F", True = 10.0F) PrintResult("True = -11.0R", True = -11.0R) PrintResult("True = ""12""", True = "12") PrintResult("True = TypeCode.Double", True = TypeCode.Double) PrintResult("System.SByte.MinValue = False", System.SByte.MinValue = False) PrintResult("System.SByte.MinValue = True", System.SByte.MinValue = True) PrintResult("System.SByte.MinValue = System.SByte.MinValue", System.SByte.MinValue = System.SByte.MinValue) PrintResult("System.SByte.MinValue = System.Byte.MaxValue", System.SByte.MinValue = System.Byte.MaxValue) PrintResult("System.SByte.MinValue = -3S", System.SByte.MinValue = -3S) PrintResult("System.SByte.MinValue = 24US", System.SByte.MinValue = 24US) PrintResult("System.SByte.MinValue = -5I", System.SByte.MinValue = -5I) PrintResult("System.SByte.MinValue = 26UI", System.SByte.MinValue = 26UI) PrintResult("System.SByte.MinValue = -7L", System.SByte.MinValue = -7L) PrintResult("System.SByte.MinValue = 28UL", System.SByte.MinValue = 28UL) PrintResult("System.SByte.MinValue = -9D", System.SByte.MinValue = -9D) PrintResult("System.SByte.MinValue = 10.0F", System.SByte.MinValue = 10.0F) PrintResult("System.SByte.MinValue = -11.0R", System.SByte.MinValue = -11.0R) PrintResult("System.SByte.MinValue = ""12""", System.SByte.MinValue = "12") PrintResult("System.SByte.MinValue = TypeCode.Double", System.SByte.MinValue = TypeCode.Double) PrintResult("System.Byte.MaxValue = False", System.Byte.MaxValue = False) PrintResult("System.Byte.MaxValue = True", System.Byte.MaxValue = True) PrintResult("System.Byte.MaxValue = System.SByte.MinValue", System.Byte.MaxValue = System.SByte.MinValue) PrintResult("System.Byte.MaxValue = System.Byte.MaxValue", System.Byte.MaxValue = System.Byte.MaxValue) PrintResult("System.Byte.MaxValue = -3S", System.Byte.MaxValue = -3S) PrintResult("System.Byte.MaxValue = 24US", System.Byte.MaxValue = 24US) PrintResult("System.Byte.MaxValue = -5I", System.Byte.MaxValue = -5I) PrintResult("System.Byte.MaxValue = 26UI", System.Byte.MaxValue = 26UI) PrintResult("System.Byte.MaxValue = -7L", System.Byte.MaxValue = -7L) PrintResult("System.Byte.MaxValue = 28UL", System.Byte.MaxValue = 28UL) PrintResult("System.Byte.MaxValue = -9D", System.Byte.MaxValue = -9D) PrintResult("System.Byte.MaxValue = 10.0F", System.Byte.MaxValue = 10.0F) PrintResult("System.Byte.MaxValue = -11.0R", System.Byte.MaxValue = -11.0R) PrintResult("System.Byte.MaxValue = ""12""", System.Byte.MaxValue = "12") PrintResult("System.Byte.MaxValue = TypeCode.Double", System.Byte.MaxValue = TypeCode.Double) PrintResult("-3S = False", -3S = False) PrintResult("-3S = True", -3S = True) PrintResult("-3S = System.SByte.MinValue", -3S = System.SByte.MinValue) PrintResult("-3S = System.Byte.MaxValue", -3S = System.Byte.MaxValue) PrintResult("-3S = -3S", -3S = -3S) PrintResult("-3S = 24US", -3S = 24US) PrintResult("-3S = -5I", -3S = -5I) PrintResult("-3S = 26UI", -3S = 26UI) PrintResult("-3S = -7L", -3S = -7L) PrintResult("-3S = 28UL", -3S = 28UL) PrintResult("-3S = -9D", -3S = -9D) PrintResult("-3S = 10.0F", -3S = 10.0F) PrintResult("-3S = -11.0R", -3S = -11.0R) PrintResult("-3S = ""12""", -3S = "12") PrintResult("-3S = TypeCode.Double", -3S = TypeCode.Double) PrintResult("24US = False", 24US = False) PrintResult("24US = True", 24US = True) PrintResult("24US = System.SByte.MinValue", 24US = System.SByte.MinValue) PrintResult("24US = System.Byte.MaxValue", 24US = System.Byte.MaxValue) PrintResult("24US = -3S", 24US = -3S) PrintResult("24US = 24US", 24US = 24US) PrintResult("24US = -5I", 24US = -5I) PrintResult("24US = 26UI", 24US = 26UI) PrintResult("24US = -7L", 24US = -7L) PrintResult("24US = 28UL", 24US = 28UL) PrintResult("24US = -9D", 24US = -9D) PrintResult("24US = 10.0F", 24US = 10.0F) PrintResult("24US = -11.0R", 24US = -11.0R) PrintResult("24US = ""12""", 24US = "12") PrintResult("24US = TypeCode.Double", 24US = TypeCode.Double) PrintResult("-5I = False", -5I = False) PrintResult("-5I = True", -5I = True) PrintResult("-5I = System.SByte.MinValue", -5I = System.SByte.MinValue) PrintResult("-5I = System.Byte.MaxValue", -5I = System.Byte.MaxValue) PrintResult("-5I = -3S", -5I = -3S) PrintResult("-5I = 24US", -5I = 24US) PrintResult("-5I = -5I", -5I = -5I) PrintResult("-5I = 26UI", -5I = 26UI) PrintResult("-5I = -7L", -5I = -7L) PrintResult("-5I = 28UL", -5I = 28UL) PrintResult("-5I = -9D", -5I = -9D) PrintResult("-5I = 10.0F", -5I = 10.0F) PrintResult("-5I = -11.0R", -5I = -11.0R) PrintResult("-5I = ""12""", -5I = "12") PrintResult("-5I = TypeCode.Double", -5I = TypeCode.Double) PrintResult("26UI = False", 26UI = False) PrintResult("26UI = True", 26UI = True) PrintResult("26UI = System.SByte.MinValue", 26UI = System.SByte.MinValue) PrintResult("26UI = System.Byte.MaxValue", 26UI = System.Byte.MaxValue) PrintResult("26UI = -3S", 26UI = -3S) PrintResult("26UI = 24US", 26UI = 24US) PrintResult("26UI = -5I", 26UI = -5I) PrintResult("26UI = 26UI", 26UI = 26UI) PrintResult("26UI = -7L", 26UI = -7L) PrintResult("26UI = 28UL", 26UI = 28UL) PrintResult("26UI = -9D", 26UI = -9D) PrintResult("26UI = 10.0F", 26UI = 10.0F) PrintResult("26UI = -11.0R", 26UI = -11.0R) PrintResult("26UI = ""12""", 26UI = "12") PrintResult("26UI = TypeCode.Double", 26UI = TypeCode.Double) PrintResult("-7L = False", -7L = False) PrintResult("-7L = True", -7L = True) PrintResult("-7L = System.SByte.MinValue", -7L = System.SByte.MinValue) PrintResult("-7L = System.Byte.MaxValue", -7L = System.Byte.MaxValue) PrintResult("-7L = -3S", -7L = -3S) PrintResult("-7L = 24US", -7L = 24US) PrintResult("-7L = -5I", -7L = -5I) PrintResult("-7L = 26UI", -7L = 26UI) PrintResult("-7L = -7L", -7L = -7L) PrintResult("-7L = 28UL", -7L = 28UL) PrintResult("-7L = -9D", -7L = -9D) PrintResult("-7L = 10.0F", -7L = 10.0F) PrintResult("-7L = -11.0R", -7L = -11.0R) PrintResult("-7L = ""12""", -7L = "12") PrintResult("-7L = TypeCode.Double", -7L = TypeCode.Double) PrintResult("28UL = False", 28UL = False) PrintResult("28UL = True", 28UL = True) PrintResult("28UL = System.SByte.MinValue", 28UL = System.SByte.MinValue) PrintResult("28UL = System.Byte.MaxValue", 28UL = System.Byte.MaxValue) PrintResult("28UL = -3S", 28UL = -3S) PrintResult("28UL = 24US", 28UL = 24US) PrintResult("28UL = -5I", 28UL = -5I) PrintResult("28UL = 26UI", 28UL = 26UI) PrintResult("28UL = -7L", 28UL = -7L) PrintResult("28UL = 28UL", 28UL = 28UL) PrintResult("28UL = -9D", 28UL = -9D) PrintResult("28UL = 10.0F", 28UL = 10.0F) PrintResult("28UL = -11.0R", 28UL = -11.0R) PrintResult("28UL = ""12""", 28UL = "12") PrintResult("28UL = TypeCode.Double", 28UL = TypeCode.Double) PrintResult("-9D = False", -9D = False) PrintResult("-9D = True", -9D = True) PrintResult("-9D = System.SByte.MinValue", -9D = System.SByte.MinValue) PrintResult("-9D = System.Byte.MaxValue", -9D = System.Byte.MaxValue) PrintResult("-9D = -3S", -9D = -3S) PrintResult("-9D = 24US", -9D = 24US) PrintResult("-9D = -5I", -9D = -5I) PrintResult("-9D = 26UI", -9D = 26UI) PrintResult("-9D = -7L", -9D = -7L) PrintResult("-9D = 28UL", -9D = 28UL) PrintResult("-9D = -9D", -9D = -9D) PrintResult("-9D = 10.0F", -9D = 10.0F) PrintResult("-9D = -11.0R", -9D = -11.0R) PrintResult("-9D = ""12""", -9D = "12") PrintResult("-9D = TypeCode.Double", -9D = TypeCode.Double) PrintResult("10.0F = False", 10.0F = False) PrintResult("10.0F = True", 10.0F = True) PrintResult("10.0F = System.SByte.MinValue", 10.0F = System.SByte.MinValue) PrintResult("10.0F = System.Byte.MaxValue", 10.0F = System.Byte.MaxValue) PrintResult("10.0F = -3S", 10.0F = -3S) PrintResult("10.0F = 24US", 10.0F = 24US) PrintResult("10.0F = -5I", 10.0F = -5I) PrintResult("10.0F = 26UI", 10.0F = 26UI) PrintResult("10.0F = -7L", 10.0F = -7L) PrintResult("10.0F = 28UL", 10.0F = 28UL) PrintResult("10.0F = -9D", 10.0F = -9D) PrintResult("10.0F = 10.0F", 10.0F = 10.0F) PrintResult("10.0F = -11.0R", 10.0F = -11.0R) PrintResult("10.0F = ""12""", 10.0F = "12") PrintResult("10.0F = TypeCode.Double", 10.0F = TypeCode.Double) PrintResult("-11.0R = False", -11.0R = False) PrintResult("-11.0R = True", -11.0R = True) PrintResult("-11.0R = System.SByte.MinValue", -11.0R = System.SByte.MinValue) PrintResult("-11.0R = System.Byte.MaxValue", -11.0R = System.Byte.MaxValue) PrintResult("-11.0R = -3S", -11.0R = -3S) PrintResult("-11.0R = 24US", -11.0R = 24US) PrintResult("-11.0R = -5I", -11.0R = -5I) PrintResult("-11.0R = 26UI", -11.0R = 26UI) PrintResult("-11.0R = -7L", -11.0R = -7L) PrintResult("-11.0R = 28UL", -11.0R = 28UL) PrintResult("-11.0R = -9D", -11.0R = -9D) PrintResult("-11.0R = 10.0F", -11.0R = 10.0F) PrintResult("-11.0R = -11.0R", -11.0R = -11.0R) PrintResult("-11.0R = ""12""", -11.0R = "12") PrintResult("-11.0R = TypeCode.Double", -11.0R = TypeCode.Double) PrintResult("""12"" = False", "12" = False) PrintResult("""12"" = True", "12" = True) PrintResult("""12"" = System.SByte.MinValue", "12" = System.SByte.MinValue) PrintResult("""12"" = System.Byte.MaxValue", "12" = System.Byte.MaxValue) PrintResult("""12"" = -3S", "12" = -3S) PrintResult("""12"" = 24US", "12" = 24US) PrintResult("""12"" = -5I", "12" = -5I) PrintResult("""12"" = 26UI", "12" = 26UI) PrintResult("""12"" = -7L", "12" = -7L) PrintResult("""12"" = 28UL", "12" = 28UL) PrintResult("""12"" = -9D", "12" = -9D) PrintResult("""12"" = 10.0F", "12" = 10.0F) PrintResult("""12"" = -11.0R", "12" = -11.0R) PrintResult("""12"" = ""12""", "12" = "12") PrintResult("""12"" = TypeCode.Double", "12" = TypeCode.Double) PrintResult("TypeCode.Double = False", TypeCode.Double = False) PrintResult("TypeCode.Double = True", TypeCode.Double = True) PrintResult("TypeCode.Double = System.SByte.MinValue", TypeCode.Double = System.SByte.MinValue) PrintResult("TypeCode.Double = System.Byte.MaxValue", TypeCode.Double = System.Byte.MaxValue) PrintResult("TypeCode.Double = -3S", TypeCode.Double = -3S) PrintResult("TypeCode.Double = 24US", TypeCode.Double = 24US) PrintResult("TypeCode.Double = -5I", TypeCode.Double = -5I) PrintResult("TypeCode.Double = 26UI", TypeCode.Double = 26UI) PrintResult("TypeCode.Double = -7L", TypeCode.Double = -7L) PrintResult("TypeCode.Double = 28UL", TypeCode.Double = 28UL) PrintResult("TypeCode.Double = -9D", TypeCode.Double = -9D) PrintResult("TypeCode.Double = 10.0F", TypeCode.Double = 10.0F) PrintResult("TypeCode.Double = -11.0R", TypeCode.Double = -11.0R) PrintResult("TypeCode.Double = ""12""", TypeCode.Double = "12") PrintResult("TypeCode.Double = TypeCode.Double", TypeCode.Double = TypeCode.Double) PrintResult("False <> False", False <> False) PrintResult("False <> True", False <> True) PrintResult("False <> System.SByte.MinValue", False <> System.SByte.MinValue) PrintResult("False <> System.Byte.MaxValue", False <> System.Byte.MaxValue) PrintResult("False <> -3S", False <> -3S) PrintResult("False <> 24US", False <> 24US) PrintResult("False <> -5I", False <> -5I) PrintResult("False <> 26UI", False <> 26UI) PrintResult("False <> -7L", False <> -7L) PrintResult("False <> 28UL", False <> 28UL) PrintResult("False <> -9D", False <> -9D) PrintResult("False <> 10.0F", False <> 10.0F) PrintResult("False <> -11.0R", False <> -11.0R) PrintResult("False <> ""12""", False <> "12") PrintResult("False <> TypeCode.Double", False <> TypeCode.Double) PrintResult("True <> False", True <> False) PrintResult("True <> True", True <> True) PrintResult("True <> System.SByte.MinValue", True <> System.SByte.MinValue) PrintResult("True <> System.Byte.MaxValue", True <> System.Byte.MaxValue) PrintResult("True <> -3S", True <> -3S) PrintResult("True <> 24US", True <> 24US) PrintResult("True <> -5I", True <> -5I) PrintResult("True <> 26UI", True <> 26UI) PrintResult("True <> -7L", True <> -7L) PrintResult("True <> 28UL", True <> 28UL) PrintResult("True <> -9D", True <> -9D) PrintResult("True <> 10.0F", True <> 10.0F) PrintResult("True <> -11.0R", True <> -11.0R) PrintResult("True <> ""12""", True <> "12") PrintResult("True <> TypeCode.Double", True <> TypeCode.Double) PrintResult("System.SByte.MinValue <> False", System.SByte.MinValue <> False) PrintResult("System.SByte.MinValue <> True", System.SByte.MinValue <> True) PrintResult("System.SByte.MinValue <> System.SByte.MinValue", System.SByte.MinValue <> System.SByte.MinValue) PrintResult("System.SByte.MinValue <> System.Byte.MaxValue", System.SByte.MinValue <> System.Byte.MaxValue) PrintResult("System.SByte.MinValue <> -3S", System.SByte.MinValue <> -3S) PrintResult("System.SByte.MinValue <> 24US", System.SByte.MinValue <> 24US) PrintResult("System.SByte.MinValue <> -5I", System.SByte.MinValue <> -5I) PrintResult("System.SByte.MinValue <> 26UI", System.SByte.MinValue <> 26UI) PrintResult("System.SByte.MinValue <> -7L", System.SByte.MinValue <> -7L) PrintResult("System.SByte.MinValue <> 28UL", System.SByte.MinValue <> 28UL) PrintResult("System.SByte.MinValue <> -9D", System.SByte.MinValue <> -9D) PrintResult("System.SByte.MinValue <> 10.0F", System.SByte.MinValue <> 10.0F) PrintResult("System.SByte.MinValue <> -11.0R", System.SByte.MinValue <> -11.0R) PrintResult("System.SByte.MinValue <> ""12""", System.SByte.MinValue <> "12") PrintResult("System.SByte.MinValue <> TypeCode.Double", System.SByte.MinValue <> TypeCode.Double) PrintResult("System.Byte.MaxValue <> False", System.Byte.MaxValue <> False) PrintResult("System.Byte.MaxValue <> True", System.Byte.MaxValue <> True) PrintResult("System.Byte.MaxValue <> System.SByte.MinValue", System.Byte.MaxValue <> System.SByte.MinValue) PrintResult("System.Byte.MaxValue <> System.Byte.MaxValue", System.Byte.MaxValue <> System.Byte.MaxValue) PrintResult("System.Byte.MaxValue <> -3S", System.Byte.MaxValue <> -3S) PrintResult("System.Byte.MaxValue <> 24US", System.Byte.MaxValue <> 24US) PrintResult("System.Byte.MaxValue <> -5I", System.Byte.MaxValue <> -5I) PrintResult("System.Byte.MaxValue <> 26UI", System.Byte.MaxValue <> 26UI) PrintResult("System.Byte.MaxValue <> -7L", System.Byte.MaxValue <> -7L) PrintResult("System.Byte.MaxValue <> 28UL", System.Byte.MaxValue <> 28UL) PrintResult("System.Byte.MaxValue <> -9D", System.Byte.MaxValue <> -9D) PrintResult("System.Byte.MaxValue <> 10.0F", System.Byte.MaxValue <> 10.0F) PrintResult("System.Byte.MaxValue <> -11.0R", System.Byte.MaxValue <> -11.0R) PrintResult("System.Byte.MaxValue <> ""12""", System.Byte.MaxValue <> "12") PrintResult("System.Byte.MaxValue <> TypeCode.Double", System.Byte.MaxValue <> TypeCode.Double) PrintResult("-3S <> False", -3S <> False) PrintResult("-3S <> True", -3S <> True) PrintResult("-3S <> System.SByte.MinValue", -3S <> System.SByte.MinValue) PrintResult("-3S <> System.Byte.MaxValue", -3S <> System.Byte.MaxValue) PrintResult("-3S <> -3S", -3S <> -3S) PrintResult("-3S <> 24US", -3S <> 24US) PrintResult("-3S <> -5I", -3S <> -5I) PrintResult("-3S <> 26UI", -3S <> 26UI) PrintResult("-3S <> -7L", -3S <> -7L) PrintResult("-3S <> 28UL", -3S <> 28UL) PrintResult("-3S <> -9D", -3S <> -9D) PrintResult("-3S <> 10.0F", -3S <> 10.0F) PrintResult("-3S <> -11.0R", -3S <> -11.0R) PrintResult("-3S <> ""12""", -3S <> "12") PrintResult("-3S <> TypeCode.Double", -3S <> TypeCode.Double) PrintResult("24US <> False", 24US <> False) PrintResult("24US <> True", 24US <> True) PrintResult("24US <> System.SByte.MinValue", 24US <> System.SByte.MinValue) PrintResult("24US <> System.Byte.MaxValue", 24US <> System.Byte.MaxValue) PrintResult("24US <> -3S", 24US <> -3S) PrintResult("24US <> 24US", 24US <> 24US) PrintResult("24US <> -5I", 24US <> -5I) PrintResult("24US <> 26UI", 24US <> 26UI) PrintResult("24US <> -7L", 24US <> -7L) PrintResult("24US <> 28UL", 24US <> 28UL) PrintResult("24US <> -9D", 24US <> -9D) PrintResult("24US <> 10.0F", 24US <> 10.0F) PrintResult("24US <> -11.0R", 24US <> -11.0R) PrintResult("24US <> ""12""", 24US <> "12") PrintResult("24US <> TypeCode.Double", 24US <> TypeCode.Double) PrintResult("-5I <> False", -5I <> False) PrintResult("-5I <> True", -5I <> True) PrintResult("-5I <> System.SByte.MinValue", -5I <> System.SByte.MinValue) PrintResult("-5I <> System.Byte.MaxValue", -5I <> System.Byte.MaxValue) PrintResult("-5I <> -3S", -5I <> -3S) PrintResult("-5I <> 24US", -5I <> 24US) PrintResult("-5I <> -5I", -5I <> -5I) PrintResult("-5I <> 26UI", -5I <> 26UI) PrintResult("-5I <> -7L", -5I <> -7L) PrintResult("-5I <> 28UL", -5I <> 28UL) PrintResult("-5I <> -9D", -5I <> -9D) PrintResult("-5I <> 10.0F", -5I <> 10.0F) PrintResult("-5I <> -11.0R", -5I <> -11.0R) PrintResult("-5I <> ""12""", -5I <> "12") PrintResult("-5I <> TypeCode.Double", -5I <> TypeCode.Double) PrintResult("26UI <> False", 26UI <> False) PrintResult("26UI <> True", 26UI <> True) PrintResult("26UI <> System.SByte.MinValue", 26UI <> System.SByte.MinValue) PrintResult("26UI <> System.Byte.MaxValue", 26UI <> System.Byte.MaxValue) PrintResult("26UI <> -3S", 26UI <> -3S) PrintResult("26UI <> 24US", 26UI <> 24US) PrintResult("26UI <> -5I", 26UI <> -5I) PrintResult("26UI <> 26UI", 26UI <> 26UI) PrintResult("26UI <> -7L", 26UI <> -7L) PrintResult("26UI <> 28UL", 26UI <> 28UL) PrintResult("26UI <> -9D", 26UI <> -9D) PrintResult("26UI <> 10.0F", 26UI <> 10.0F) PrintResult("26UI <> -11.0R", 26UI <> -11.0R) PrintResult("26UI <> ""12""", 26UI <> "12") PrintResult("26UI <> TypeCode.Double", 26UI <> TypeCode.Double) PrintResult("-7L <> False", -7L <> False) PrintResult("-7L <> True", -7L <> True) PrintResult("-7L <> System.SByte.MinValue", -7L <> System.SByte.MinValue) PrintResult("-7L <> System.Byte.MaxValue", -7L <> System.Byte.MaxValue) PrintResult("-7L <> -3S", -7L <> -3S) PrintResult("-7L <> 24US", -7L <> 24US) PrintResult("-7L <> -5I", -7L <> -5I) PrintResult("-7L <> 26UI", -7L <> 26UI) PrintResult("-7L <> -7L", -7L <> -7L) PrintResult("-7L <> 28UL", -7L <> 28UL) PrintResult("-7L <> -9D", -7L <> -9D) PrintResult("-7L <> 10.0F", -7L <> 10.0F) PrintResult("-7L <> -11.0R", -7L <> -11.0R) PrintResult("-7L <> ""12""", -7L <> "12") PrintResult("-7L <> TypeCode.Double", -7L <> TypeCode.Double) PrintResult("28UL <> False", 28UL <> False) PrintResult("28UL <> True", 28UL <> True) PrintResult("28UL <> System.SByte.MinValue", 28UL <> System.SByte.MinValue) PrintResult("28UL <> System.Byte.MaxValue", 28UL <> System.Byte.MaxValue) PrintResult("28UL <> -3S", 28UL <> -3S) PrintResult("28UL <> 24US", 28UL <> 24US) PrintResult("28UL <> -5I", 28UL <> -5I) PrintResult("28UL <> 26UI", 28UL <> 26UI) PrintResult("28UL <> -7L", 28UL <> -7L) PrintResult("28UL <> 28UL", 28UL <> 28UL) PrintResult("28UL <> -9D", 28UL <> -9D) PrintResult("28UL <> 10.0F", 28UL <> 10.0F) PrintResult("28UL <> -11.0R", 28UL <> -11.0R) PrintResult("28UL <> ""12""", 28UL <> "12") PrintResult("28UL <> TypeCode.Double", 28UL <> TypeCode.Double) PrintResult("-9D <> False", -9D <> False) PrintResult("-9D <> True", -9D <> True) PrintResult("-9D <> System.SByte.MinValue", -9D <> System.SByte.MinValue) PrintResult("-9D <> System.Byte.MaxValue", -9D <> System.Byte.MaxValue) PrintResult("-9D <> -3S", -9D <> -3S) PrintResult("-9D <> 24US", -9D <> 24US) PrintResult("-9D <> -5I", -9D <> -5I) PrintResult("-9D <> 26UI", -9D <> 26UI) PrintResult("-9D <> -7L", -9D <> -7L) PrintResult("-9D <> 28UL", -9D <> 28UL) PrintResult("-9D <> -9D", -9D <> -9D) PrintResult("-9D <> 10.0F", -9D <> 10.0F) PrintResult("-9D <> -11.0R", -9D <> -11.0R) PrintResult("-9D <> ""12""", -9D <> "12") PrintResult("-9D <> TypeCode.Double", -9D <> TypeCode.Double) PrintResult("10.0F <> False", 10.0F <> False) PrintResult("10.0F <> True", 10.0F <> True) PrintResult("10.0F <> System.SByte.MinValue", 10.0F <> System.SByte.MinValue) PrintResult("10.0F <> System.Byte.MaxValue", 10.0F <> System.Byte.MaxValue) PrintResult("10.0F <> -3S", 10.0F <> -3S) PrintResult("10.0F <> 24US", 10.0F <> 24US) PrintResult("10.0F <> -5I", 10.0F <> -5I) PrintResult("10.0F <> 26UI", 10.0F <> 26UI) PrintResult("10.0F <> -7L", 10.0F <> -7L) PrintResult("10.0F <> 28UL", 10.0F <> 28UL) PrintResult("10.0F <> -9D", 10.0F <> -9D) PrintResult("10.0F <> 10.0F", 10.0F <> 10.0F) PrintResult("10.0F <> -11.0R", 10.0F <> -11.0R) PrintResult("10.0F <> ""12""", 10.0F <> "12") PrintResult("10.0F <> TypeCode.Double", 10.0F <> TypeCode.Double) PrintResult("-11.0R <> False", -11.0R <> False) PrintResult("-11.0R <> True", -11.0R <> True) PrintResult("-11.0R <> System.SByte.MinValue", -11.0R <> System.SByte.MinValue) PrintResult("-11.0R <> System.Byte.MaxValue", -11.0R <> System.Byte.MaxValue) PrintResult("-11.0R <> -3S", -11.0R <> -3S) PrintResult("-11.0R <> 24US", -11.0R <> 24US) PrintResult("-11.0R <> -5I", -11.0R <> -5I) PrintResult("-11.0R <> 26UI", -11.0R <> 26UI) PrintResult("-11.0R <> -7L", -11.0R <> -7L) PrintResult("-11.0R <> 28UL", -11.0R <> 28UL) PrintResult("-11.0R <> -9D", -11.0R <> -9D) PrintResult("-11.0R <> 10.0F", -11.0R <> 10.0F) PrintResult("-11.0R <> -11.0R", -11.0R <> -11.0R) PrintResult("-11.0R <> ""12""", -11.0R <> "12") PrintResult("-11.0R <> TypeCode.Double", -11.0R <> TypeCode.Double) PrintResult("""12"" <> False", "12" <> False) PrintResult("""12"" <> True", "12" <> True) PrintResult("""12"" <> System.SByte.MinValue", "12" <> System.SByte.MinValue) PrintResult("""12"" <> System.Byte.MaxValue", "12" <> System.Byte.MaxValue) PrintResult("""12"" <> -3S", "12" <> -3S) PrintResult("""12"" <> 24US", "12" <> 24US) PrintResult("""12"" <> -5I", "12" <> -5I) PrintResult("""12"" <> 26UI", "12" <> 26UI) PrintResult("""12"" <> -7L", "12" <> -7L) PrintResult("""12"" <> 28UL", "12" <> 28UL) PrintResult("""12"" <> -9D", "12" <> -9D) PrintResult("""12"" <> 10.0F", "12" <> 10.0F) PrintResult("""12"" <> -11.0R", "12" <> -11.0R) PrintResult("""12"" <> ""12""", "12" <> "12") PrintResult("""12"" <> TypeCode.Double", "12" <> TypeCode.Double) PrintResult("TypeCode.Double <> False", TypeCode.Double <> False) PrintResult("TypeCode.Double <> True", TypeCode.Double <> True) PrintResult("TypeCode.Double <> System.SByte.MinValue", TypeCode.Double <> System.SByte.MinValue) PrintResult("TypeCode.Double <> System.Byte.MaxValue", TypeCode.Double <> System.Byte.MaxValue) PrintResult("TypeCode.Double <> -3S", TypeCode.Double <> -3S) PrintResult("TypeCode.Double <> 24US", TypeCode.Double <> 24US) PrintResult("TypeCode.Double <> -5I", TypeCode.Double <> -5I) PrintResult("TypeCode.Double <> 26UI", TypeCode.Double <> 26UI) PrintResult("TypeCode.Double <> -7L", TypeCode.Double <> -7L) PrintResult("TypeCode.Double <> 28UL", TypeCode.Double <> 28UL) PrintResult("TypeCode.Double <> -9D", TypeCode.Double <> -9D) PrintResult("TypeCode.Double <> 10.0F", TypeCode.Double <> 10.0F) PrintResult("TypeCode.Double <> -11.0R", TypeCode.Double <> -11.0R) PrintResult("TypeCode.Double <> ""12""", TypeCode.Double <> "12") PrintResult("TypeCode.Double <> TypeCode.Double", TypeCode.Double <> TypeCode.Double) PrintResult("False <= False", False <= False) PrintResult("False <= True", False <= True) PrintResult("False <= System.SByte.MinValue", False <= System.SByte.MinValue) PrintResult("False <= System.Byte.MaxValue", False <= System.Byte.MaxValue) PrintResult("False <= -3S", False <= -3S) PrintResult("False <= 24US", False <= 24US) PrintResult("False <= -5I", False <= -5I) PrintResult("False <= 26UI", False <= 26UI) PrintResult("False <= -7L", False <= -7L) PrintResult("False <= 28UL", False <= 28UL) PrintResult("False <= -9D", False <= -9D) PrintResult("False <= 10.0F", False <= 10.0F) PrintResult("False <= -11.0R", False <= -11.0R) PrintResult("False <= ""12""", False <= "12") PrintResult("False <= TypeCode.Double", False <= TypeCode.Double) PrintResult("True <= False", True <= False) PrintResult("True <= True", True <= True) PrintResult("True <= System.SByte.MinValue", True <= System.SByte.MinValue) PrintResult("True <= System.Byte.MaxValue", True <= System.Byte.MaxValue) PrintResult("True <= -3S", True <= -3S) PrintResult("True <= 24US", True <= 24US) PrintResult("True <= -5I", True <= -5I) PrintResult("True <= 26UI", True <= 26UI) PrintResult("True <= -7L", True <= -7L) PrintResult("True <= 28UL", True <= 28UL) PrintResult("True <= -9D", True <= -9D) PrintResult("True <= 10.0F", True <= 10.0F) PrintResult("True <= -11.0R", True <= -11.0R) PrintResult("True <= ""12""", True <= "12") PrintResult("True <= TypeCode.Double", True <= TypeCode.Double) PrintResult("System.SByte.MinValue <= False", System.SByte.MinValue <= False) PrintResult("System.SByte.MinValue <= True", System.SByte.MinValue <= True) PrintResult("System.SByte.MinValue <= System.SByte.MinValue", System.SByte.MinValue <= System.SByte.MinValue) PrintResult("System.SByte.MinValue <= System.Byte.MaxValue", System.SByte.MinValue <= System.Byte.MaxValue) PrintResult("System.SByte.MinValue <= -3S", System.SByte.MinValue <= -3S) PrintResult("System.SByte.MinValue <= 24US", System.SByte.MinValue <= 24US) PrintResult("System.SByte.MinValue <= -5I", System.SByte.MinValue <= -5I) PrintResult("System.SByte.MinValue <= 26UI", System.SByte.MinValue <= 26UI) PrintResult("System.SByte.MinValue <= -7L", System.SByte.MinValue <= -7L) PrintResult("System.SByte.MinValue <= 28UL", System.SByte.MinValue <= 28UL) PrintResult("System.SByte.MinValue <= -9D", System.SByte.MinValue <= -9D) PrintResult("System.SByte.MinValue <= 10.0F", System.SByte.MinValue <= 10.0F) PrintResult("System.SByte.MinValue <= -11.0R", System.SByte.MinValue <= -11.0R) PrintResult("System.SByte.MinValue <= ""12""", System.SByte.MinValue <= "12") PrintResult("System.SByte.MinValue <= TypeCode.Double", System.SByte.MinValue <= TypeCode.Double) PrintResult("System.Byte.MaxValue <= False", System.Byte.MaxValue <= False) PrintResult("System.Byte.MaxValue <= True", System.Byte.MaxValue <= True) PrintResult("System.Byte.MaxValue <= System.SByte.MinValue", System.Byte.MaxValue <= System.SByte.MinValue) PrintResult("System.Byte.MaxValue <= System.Byte.MaxValue", System.Byte.MaxValue <= System.Byte.MaxValue) PrintResult("System.Byte.MaxValue <= -3S", System.Byte.MaxValue <= -3S) PrintResult("System.Byte.MaxValue <= 24US", System.Byte.MaxValue <= 24US) PrintResult("System.Byte.MaxValue <= -5I", System.Byte.MaxValue <= -5I) PrintResult("System.Byte.MaxValue <= 26UI", System.Byte.MaxValue <= 26UI) PrintResult("System.Byte.MaxValue <= -7L", System.Byte.MaxValue <= -7L) PrintResult("System.Byte.MaxValue <= 28UL", System.Byte.MaxValue <= 28UL) PrintResult("System.Byte.MaxValue <= -9D", System.Byte.MaxValue <= -9D) PrintResult("System.Byte.MaxValue <= 10.0F", System.Byte.MaxValue <= 10.0F) PrintResult("System.Byte.MaxValue <= -11.0R", System.Byte.MaxValue <= -11.0R) PrintResult("System.Byte.MaxValue <= ""12""", System.Byte.MaxValue <= "12") PrintResult("System.Byte.MaxValue <= TypeCode.Double", System.Byte.MaxValue <= TypeCode.Double) PrintResult("-3S <= False", -3S <= False) PrintResult("-3S <= True", -3S <= True) PrintResult("-3S <= System.SByte.MinValue", -3S <= System.SByte.MinValue) PrintResult("-3S <= System.Byte.MaxValue", -3S <= System.Byte.MaxValue) PrintResult("-3S <= -3S", -3S <= -3S) PrintResult("-3S <= 24US", -3S <= 24US) PrintResult("-3S <= -5I", -3S <= -5I) PrintResult("-3S <= 26UI", -3S <= 26UI) PrintResult("-3S <= -7L", -3S <= -7L) PrintResult("-3S <= 28UL", -3S <= 28UL) PrintResult("-3S <= -9D", -3S <= -9D) PrintResult("-3S <= 10.0F", -3S <= 10.0F) PrintResult("-3S <= -11.0R", -3S <= -11.0R) PrintResult("-3S <= ""12""", -3S <= "12") PrintResult("-3S <= TypeCode.Double", -3S <= TypeCode.Double) PrintResult("24US <= False", 24US <= False) PrintResult("24US <= True", 24US <= True) PrintResult("24US <= System.SByte.MinValue", 24US <= System.SByte.MinValue) PrintResult("24US <= System.Byte.MaxValue", 24US <= System.Byte.MaxValue) PrintResult("24US <= -3S", 24US <= -3S) PrintResult("24US <= 24US", 24US <= 24US) PrintResult("24US <= -5I", 24US <= -5I) PrintResult("24US <= 26UI", 24US <= 26UI) PrintResult("24US <= -7L", 24US <= -7L) PrintResult("24US <= 28UL", 24US <= 28UL) PrintResult("24US <= -9D", 24US <= -9D) PrintResult("24US <= 10.0F", 24US <= 10.0F) PrintResult("24US <= -11.0R", 24US <= -11.0R) PrintResult("24US <= ""12""", 24US <= "12") PrintResult("24US <= TypeCode.Double", 24US <= TypeCode.Double) PrintResult("-5I <= False", -5I <= False) PrintResult("-5I <= True", -5I <= True) PrintResult("-5I <= System.SByte.MinValue", -5I <= System.SByte.MinValue) PrintResult("-5I <= System.Byte.MaxValue", -5I <= System.Byte.MaxValue) PrintResult("-5I <= -3S", -5I <= -3S) PrintResult("-5I <= 24US", -5I <= 24US) PrintResult("-5I <= -5I", -5I <= -5I) PrintResult("-5I <= 26UI", -5I <= 26UI) PrintResult("-5I <= -7L", -5I <= -7L) PrintResult("-5I <= 28UL", -5I <= 28UL) PrintResult("-5I <= -9D", -5I <= -9D) PrintResult("-5I <= 10.0F", -5I <= 10.0F) PrintResult("-5I <= -11.0R", -5I <= -11.0R) PrintResult("-5I <= ""12""", -5I <= "12") PrintResult("-5I <= TypeCode.Double", -5I <= TypeCode.Double) PrintResult("26UI <= False", 26UI <= False) PrintResult("26UI <= True", 26UI <= True) PrintResult("26UI <= System.SByte.MinValue", 26UI <= System.SByte.MinValue) PrintResult("26UI <= System.Byte.MaxValue", 26UI <= System.Byte.MaxValue) PrintResult("26UI <= -3S", 26UI <= -3S) PrintResult("26UI <= 24US", 26UI <= 24US) PrintResult("26UI <= -5I", 26UI <= -5I) PrintResult("26UI <= 26UI", 26UI <= 26UI) PrintResult("26UI <= -7L", 26UI <= -7L) PrintResult("26UI <= 28UL", 26UI <= 28UL) PrintResult("26UI <= -9D", 26UI <= -9D) PrintResult("26UI <= 10.0F", 26UI <= 10.0F) PrintResult("26UI <= -11.0R", 26UI <= -11.0R) PrintResult("26UI <= ""12""", 26UI <= "12") PrintResult("26UI <= TypeCode.Double", 26UI <= TypeCode.Double) PrintResult("-7L <= False", -7L <= False) PrintResult("-7L <= True", -7L <= True) PrintResult("-7L <= System.SByte.MinValue", -7L <= System.SByte.MinValue) PrintResult("-7L <= System.Byte.MaxValue", -7L <= System.Byte.MaxValue) PrintResult("-7L <= -3S", -7L <= -3S) PrintResult("-7L <= 24US", -7L <= 24US) PrintResult("-7L <= -5I", -7L <= -5I) PrintResult("-7L <= 26UI", -7L <= 26UI) PrintResult("-7L <= -7L", -7L <= -7L) PrintResult("-7L <= 28UL", -7L <= 28UL) PrintResult("-7L <= -9D", -7L <= -9D) PrintResult("-7L <= 10.0F", -7L <= 10.0F) PrintResult("-7L <= -11.0R", -7L <= -11.0R) PrintResult("-7L <= ""12""", -7L <= "12") PrintResult("-7L <= TypeCode.Double", -7L <= TypeCode.Double) PrintResult("28UL <= False", 28UL <= False) PrintResult("28UL <= True", 28UL <= True) PrintResult("28UL <= System.SByte.MinValue", 28UL <= System.SByte.MinValue) PrintResult("28UL <= System.Byte.MaxValue", 28UL <= System.Byte.MaxValue) PrintResult("28UL <= -3S", 28UL <= -3S) PrintResult("28UL <= 24US", 28UL <= 24US) PrintResult("28UL <= -5I", 28UL <= -5I) PrintResult("28UL <= 26UI", 28UL <= 26UI) PrintResult("28UL <= -7L", 28UL <= -7L) PrintResult("28UL <= 28UL", 28UL <= 28UL) PrintResult("28UL <= -9D", 28UL <= -9D) PrintResult("28UL <= 10.0F", 28UL <= 10.0F) PrintResult("28UL <= -11.0R", 28UL <= -11.0R) PrintResult("28UL <= ""12""", 28UL <= "12") PrintResult("28UL <= TypeCode.Double", 28UL <= TypeCode.Double) PrintResult("-9D <= False", -9D <= False) PrintResult("-9D <= True", -9D <= True) PrintResult("-9D <= System.SByte.MinValue", -9D <= System.SByte.MinValue) PrintResult("-9D <= System.Byte.MaxValue", -9D <= System.Byte.MaxValue) PrintResult("-9D <= -3S", -9D <= -3S) PrintResult("-9D <= 24US", -9D <= 24US) PrintResult("-9D <= -5I", -9D <= -5I) PrintResult("-9D <= 26UI", -9D <= 26UI) PrintResult("-9D <= -7L", -9D <= -7L) PrintResult("-9D <= 28UL", -9D <= 28UL) PrintResult("-9D <= -9D", -9D <= -9D) PrintResult("-9D <= 10.0F", -9D <= 10.0F) PrintResult("-9D <= -11.0R", -9D <= -11.0R) PrintResult("-9D <= ""12""", -9D <= "12") PrintResult("-9D <= TypeCode.Double", -9D <= TypeCode.Double) PrintResult("10.0F <= False", 10.0F <= False) PrintResult("10.0F <= True", 10.0F <= True) PrintResult("10.0F <= System.SByte.MinValue", 10.0F <= System.SByte.MinValue) PrintResult("10.0F <= System.Byte.MaxValue", 10.0F <= System.Byte.MaxValue) PrintResult("10.0F <= -3S", 10.0F <= -3S) PrintResult("10.0F <= 24US", 10.0F <= 24US) PrintResult("10.0F <= -5I", 10.0F <= -5I) PrintResult("10.0F <= 26UI", 10.0F <= 26UI) PrintResult("10.0F <= -7L", 10.0F <= -7L) PrintResult("10.0F <= 28UL", 10.0F <= 28UL) PrintResult("10.0F <= -9D", 10.0F <= -9D) PrintResult("10.0F <= 10.0F", 10.0F <= 10.0F) PrintResult("10.0F <= -11.0R", 10.0F <= -11.0R) PrintResult("10.0F <= ""12""", 10.0F <= "12") PrintResult("10.0F <= TypeCode.Double", 10.0F <= TypeCode.Double) PrintResult("-11.0R <= False", -11.0R <= False) PrintResult("-11.0R <= True", -11.0R <= True) PrintResult("-11.0R <= System.SByte.MinValue", -11.0R <= System.SByte.MinValue) PrintResult("-11.0R <= System.Byte.MaxValue", -11.0R <= System.Byte.MaxValue) PrintResult("-11.0R <= -3S", -11.0R <= -3S) PrintResult("-11.0R <= 24US", -11.0R <= 24US) PrintResult("-11.0R <= -5I", -11.0R <= -5I) PrintResult("-11.0R <= 26UI", -11.0R <= 26UI) PrintResult("-11.0R <= -7L", -11.0R <= -7L) PrintResult("-11.0R <= 28UL", -11.0R <= 28UL) PrintResult("-11.0R <= -9D", -11.0R <= -9D) PrintResult("-11.0R <= 10.0F", -11.0R <= 10.0F) PrintResult("-11.0R <= -11.0R", -11.0R <= -11.0R) PrintResult("-11.0R <= ""12""", -11.0R <= "12") PrintResult("-11.0R <= TypeCode.Double", -11.0R <= TypeCode.Double) PrintResult("""12"" <= False", "12" <= False) PrintResult("""12"" <= True", "12" <= True) PrintResult("""12"" <= System.SByte.MinValue", "12" <= System.SByte.MinValue) PrintResult("""12"" <= System.Byte.MaxValue", "12" <= System.Byte.MaxValue) PrintResult("""12"" <= -3S", "12" <= -3S) PrintResult("""12"" <= 24US", "12" <= 24US) PrintResult("""12"" <= -5I", "12" <= -5I) PrintResult("""12"" <= 26UI", "12" <= 26UI) PrintResult("""12"" <= -7L", "12" <= -7L) PrintResult("""12"" <= 28UL", "12" <= 28UL) PrintResult("""12"" <= -9D", "12" <= -9D) PrintResult("""12"" <= 10.0F", "12" <= 10.0F) PrintResult("""12"" <= -11.0R", "12" <= -11.0R) PrintResult("""12"" <= ""12""", "12" <= "12") PrintResult("""12"" <= TypeCode.Double", "12" <= TypeCode.Double) PrintResult("TypeCode.Double <= False", TypeCode.Double <= False) PrintResult("TypeCode.Double <= True", TypeCode.Double <= True) PrintResult("TypeCode.Double <= System.SByte.MinValue", TypeCode.Double <= System.SByte.MinValue) PrintResult("TypeCode.Double <= System.Byte.MaxValue", TypeCode.Double <= System.Byte.MaxValue) PrintResult("TypeCode.Double <= -3S", TypeCode.Double <= -3S) PrintResult("TypeCode.Double <= 24US", TypeCode.Double <= 24US) PrintResult("TypeCode.Double <= -5I", TypeCode.Double <= -5I) PrintResult("TypeCode.Double <= 26UI", TypeCode.Double <= 26UI) PrintResult("TypeCode.Double <= -7L", TypeCode.Double <= -7L) PrintResult("TypeCode.Double <= 28UL", TypeCode.Double <= 28UL) PrintResult("TypeCode.Double <= -9D", TypeCode.Double <= -9D) PrintResult("TypeCode.Double <= 10.0F", TypeCode.Double <= 10.0F) PrintResult("TypeCode.Double <= -11.0R", TypeCode.Double <= -11.0R) PrintResult("TypeCode.Double <= ""12""", TypeCode.Double <= "12") PrintResult("TypeCode.Double <= TypeCode.Double", TypeCode.Double <= TypeCode.Double) PrintResult("False >= False", False >= False) PrintResult("False >= True", False >= True) PrintResult("False >= System.SByte.MinValue", False >= System.SByte.MinValue) PrintResult("False >= System.Byte.MaxValue", False >= System.Byte.MaxValue) PrintResult("False >= -3S", False >= -3S) PrintResult("False >= 24US", False >= 24US) PrintResult("False >= -5I", False >= -5I) PrintResult("False >= 26UI", False >= 26UI) PrintResult("False >= -7L", False >= -7L) PrintResult("False >= 28UL", False >= 28UL) PrintResult("False >= -9D", False >= -9D) PrintResult("False >= 10.0F", False >= 10.0F) PrintResult("False >= -11.0R", False >= -11.0R) PrintResult("False >= ""12""", False >= "12") PrintResult("False >= TypeCode.Double", False >= TypeCode.Double) PrintResult("True >= False", True >= False) PrintResult("True >= True", True >= True) PrintResult("True >= System.SByte.MinValue", True >= System.SByte.MinValue) PrintResult("True >= System.Byte.MaxValue", True >= System.Byte.MaxValue) PrintResult("True >= -3S", True >= -3S) PrintResult("True >= 24US", True >= 24US) PrintResult("True >= -5I", True >= -5I) PrintResult("True >= 26UI", True >= 26UI) PrintResult("True >= -7L", True >= -7L) PrintResult("True >= 28UL", True >= 28UL) PrintResult("True >= -9D", True >= -9D) PrintResult("True >= 10.0F", True >= 10.0F) PrintResult("True >= -11.0R", True >= -11.0R) PrintResult("True >= ""12""", True >= "12") PrintResult("True >= TypeCode.Double", True >= TypeCode.Double) PrintResult("System.SByte.MinValue >= False", System.SByte.MinValue >= False) PrintResult("System.SByte.MinValue >= True", System.SByte.MinValue >= True) PrintResult("System.SByte.MinValue >= System.SByte.MinValue", System.SByte.MinValue >= System.SByte.MinValue) PrintResult("System.SByte.MinValue >= System.Byte.MaxValue", System.SByte.MinValue >= System.Byte.MaxValue) PrintResult("System.SByte.MinValue >= -3S", System.SByte.MinValue >= -3S) PrintResult("System.SByte.MinValue >= 24US", System.SByte.MinValue >= 24US) PrintResult("System.SByte.MinValue >= -5I", System.SByte.MinValue >= -5I) PrintResult("System.SByte.MinValue >= 26UI", System.SByte.MinValue >= 26UI) PrintResult("System.SByte.MinValue >= -7L", System.SByte.MinValue >= -7L) PrintResult("System.SByte.MinValue >= 28UL", System.SByte.MinValue >= 28UL) PrintResult("System.SByte.MinValue >= -9D", System.SByte.MinValue >= -9D) PrintResult("System.SByte.MinValue >= 10.0F", System.SByte.MinValue >= 10.0F) PrintResult("System.SByte.MinValue >= -11.0R", System.SByte.MinValue >= -11.0R) PrintResult("System.SByte.MinValue >= ""12""", System.SByte.MinValue >= "12") PrintResult("System.SByte.MinValue >= TypeCode.Double", System.SByte.MinValue >= TypeCode.Double) PrintResult("System.Byte.MaxValue >= False", System.Byte.MaxValue >= False) PrintResult("System.Byte.MaxValue >= True", System.Byte.MaxValue >= True) PrintResult("System.Byte.MaxValue >= System.SByte.MinValue", System.Byte.MaxValue >= System.SByte.MinValue) PrintResult("System.Byte.MaxValue >= System.Byte.MaxValue", System.Byte.MaxValue >= System.Byte.MaxValue) PrintResult("System.Byte.MaxValue >= -3S", System.Byte.MaxValue >= -3S) PrintResult("System.Byte.MaxValue >= 24US", System.Byte.MaxValue >= 24US) PrintResult("System.Byte.MaxValue >= -5I", System.Byte.MaxValue >= -5I) PrintResult("System.Byte.MaxValue >= 26UI", System.Byte.MaxValue >= 26UI) PrintResult("System.Byte.MaxValue >= -7L", System.Byte.MaxValue >= -7L) PrintResult("System.Byte.MaxValue >= 28UL", System.Byte.MaxValue >= 28UL) PrintResult("System.Byte.MaxValue >= -9D", System.Byte.MaxValue >= -9D) PrintResult("System.Byte.MaxValue >= 10.0F", System.Byte.MaxValue >= 10.0F) PrintResult("System.Byte.MaxValue >= -11.0R", System.Byte.MaxValue >= -11.0R) PrintResult("System.Byte.MaxValue >= ""12""", System.Byte.MaxValue >= "12") PrintResult("System.Byte.MaxValue >= TypeCode.Double", System.Byte.MaxValue >= TypeCode.Double) PrintResult("-3S >= False", -3S >= False) PrintResult("-3S >= True", -3S >= True) PrintResult("-3S >= System.SByte.MinValue", -3S >= System.SByte.MinValue) PrintResult("-3S >= System.Byte.MaxValue", -3S >= System.Byte.MaxValue) PrintResult("-3S >= -3S", -3S >= -3S) PrintResult("-3S >= 24US", -3S >= 24US) PrintResult("-3S >= -5I", -3S >= -5I) PrintResult("-3S >= 26UI", -3S >= 26UI) PrintResult("-3S >= -7L", -3S >= -7L) PrintResult("-3S >= 28UL", -3S >= 28UL) PrintResult("-3S >= -9D", -3S >= -9D) PrintResult("-3S >= 10.0F", -3S >= 10.0F) PrintResult("-3S >= -11.0R", -3S >= -11.0R) PrintResult("-3S >= ""12""", -3S >= "12") PrintResult("-3S >= TypeCode.Double", -3S >= TypeCode.Double) PrintResult("24US >= False", 24US >= False) PrintResult("24US >= True", 24US >= True) PrintResult("24US >= System.SByte.MinValue", 24US >= System.SByte.MinValue) PrintResult("24US >= System.Byte.MaxValue", 24US >= System.Byte.MaxValue) PrintResult("24US >= -3S", 24US >= -3S) PrintResult("24US >= 24US", 24US >= 24US) PrintResult("24US >= -5I", 24US >= -5I) PrintResult("24US >= 26UI", 24US >= 26UI) PrintResult("24US >= -7L", 24US >= -7L) PrintResult("24US >= 28UL", 24US >= 28UL) PrintResult("24US >= -9D", 24US >= -9D) PrintResult("24US >= 10.0F", 24US >= 10.0F) PrintResult("24US >= -11.0R", 24US >= -11.0R) PrintResult("24US >= ""12""", 24US >= "12") PrintResult("24US >= TypeCode.Double", 24US >= TypeCode.Double) PrintResult("-5I >= False", -5I >= False) PrintResult("-5I >= True", -5I >= True) PrintResult("-5I >= System.SByte.MinValue", -5I >= System.SByte.MinValue) PrintResult("-5I >= System.Byte.MaxValue", -5I >= System.Byte.MaxValue) PrintResult("-5I >= -3S", -5I >= -3S) PrintResult("-5I >= 24US", -5I >= 24US) PrintResult("-5I >= -5I", -5I >= -5I) PrintResult("-5I >= 26UI", -5I >= 26UI) PrintResult("-5I >= -7L", -5I >= -7L) PrintResult("-5I >= 28UL", -5I >= 28UL) PrintResult("-5I >= -9D", -5I >= -9D) PrintResult("-5I >= 10.0F", -5I >= 10.0F) PrintResult("-5I >= -11.0R", -5I >= -11.0R) PrintResult("-5I >= ""12""", -5I >= "12") PrintResult("-5I >= TypeCode.Double", -5I >= TypeCode.Double) PrintResult("26UI >= False", 26UI >= False) PrintResult("26UI >= True", 26UI >= True) PrintResult("26UI >= System.SByte.MinValue", 26UI >= System.SByte.MinValue) PrintResult("26UI >= System.Byte.MaxValue", 26UI >= System.Byte.MaxValue) PrintResult("26UI >= -3S", 26UI >= -3S) PrintResult("26UI >= 24US", 26UI >= 24US) PrintResult("26UI >= -5I", 26UI >= -5I) PrintResult("26UI >= 26UI", 26UI >= 26UI) PrintResult("26UI >= -7L", 26UI >= -7L) PrintResult("26UI >= 28UL", 26UI >= 28UL) PrintResult("26UI >= -9D", 26UI >= -9D) PrintResult("26UI >= 10.0F", 26UI >= 10.0F) PrintResult("26UI >= -11.0R", 26UI >= -11.0R) PrintResult("26UI >= ""12""", 26UI >= "12") PrintResult("26UI >= TypeCode.Double", 26UI >= TypeCode.Double) PrintResult("-7L >= False", -7L >= False) PrintResult("-7L >= True", -7L >= True) PrintResult("-7L >= System.SByte.MinValue", -7L >= System.SByte.MinValue) PrintResult("-7L >= System.Byte.MaxValue", -7L >= System.Byte.MaxValue) PrintResult("-7L >= -3S", -7L >= -3S) PrintResult("-7L >= 24US", -7L >= 24US) PrintResult("-7L >= -5I", -7L >= -5I) PrintResult("-7L >= 26UI", -7L >= 26UI) PrintResult("-7L >= -7L", -7L >= -7L) PrintResult("-7L >= 28UL", -7L >= 28UL) PrintResult("-7L >= -9D", -7L >= -9D) PrintResult("-7L >= 10.0F", -7L >= 10.0F) PrintResult("-7L >= -11.0R", -7L >= -11.0R) PrintResult("-7L >= ""12""", -7L >= "12") PrintResult("-7L >= TypeCode.Double", -7L >= TypeCode.Double) PrintResult("28UL >= False", 28UL >= False) PrintResult("28UL >= True", 28UL >= True) PrintResult("28UL >= System.SByte.MinValue", 28UL >= System.SByte.MinValue) PrintResult("28UL >= System.Byte.MaxValue", 28UL >= System.Byte.MaxValue) PrintResult("28UL >= -3S", 28UL >= -3S) PrintResult("28UL >= 24US", 28UL >= 24US) PrintResult("28UL >= -5I", 28UL >= -5I) PrintResult("28UL >= 26UI", 28UL >= 26UI) PrintResult("28UL >= -7L", 28UL >= -7L) PrintResult("28UL >= 28UL", 28UL >= 28UL) PrintResult("28UL >= -9D", 28UL >= -9D) PrintResult("28UL >= 10.0F", 28UL >= 10.0F) PrintResult("28UL >= -11.0R", 28UL >= -11.0R) PrintResult("28UL >= ""12""", 28UL >= "12") PrintResult("28UL >= TypeCode.Double", 28UL >= TypeCode.Double) PrintResult("-9D >= False", -9D >= False) PrintResult("-9D >= True", -9D >= True) PrintResult("-9D >= System.SByte.MinValue", -9D >= System.SByte.MinValue) PrintResult("-9D >= System.Byte.MaxValue", -9D >= System.Byte.MaxValue) PrintResult("-9D >= -3S", -9D >= -3S) PrintResult("-9D >= 24US", -9D >= 24US) PrintResult("-9D >= -5I", -9D >= -5I) PrintResult("-9D >= 26UI", -9D >= 26UI) PrintResult("-9D >= -7L", -9D >= -7L) PrintResult("-9D >= 28UL", -9D >= 28UL) PrintResult("-9D >= -9D", -9D >= -9D) PrintResult("-9D >= 10.0F", -9D >= 10.0F) PrintResult("-9D >= -11.0R", -9D >= -11.0R) PrintResult("-9D >= ""12""", -9D >= "12") PrintResult("-9D >= TypeCode.Double", -9D >= TypeCode.Double) PrintResult("10.0F >= False", 10.0F >= False) PrintResult("10.0F >= True", 10.0F >= True) PrintResult("10.0F >= System.SByte.MinValue", 10.0F >= System.SByte.MinValue) PrintResult("10.0F >= System.Byte.MaxValue", 10.0F >= System.Byte.MaxValue) PrintResult("10.0F >= -3S", 10.0F >= -3S) PrintResult("10.0F >= 24US", 10.0F >= 24US) PrintResult("10.0F >= -5I", 10.0F >= -5I) PrintResult("10.0F >= 26UI", 10.0F >= 26UI) PrintResult("10.0F >= -7L", 10.0F >= -7L) PrintResult("10.0F >= 28UL", 10.0F >= 28UL) PrintResult("10.0F >= -9D", 10.0F >= -9D) PrintResult("10.0F >= 10.0F", 10.0F >= 10.0F) PrintResult("10.0F >= -11.0R", 10.0F >= -11.0R) PrintResult("10.0F >= ""12""", 10.0F >= "12") PrintResult("10.0F >= TypeCode.Double", 10.0F >= TypeCode.Double) PrintResult("-11.0R >= False", -11.0R >= False) PrintResult("-11.0R >= True", -11.0R >= True) PrintResult("-11.0R >= System.SByte.MinValue", -11.0R >= System.SByte.MinValue) PrintResult("-11.0R >= System.Byte.MaxValue", -11.0R >= System.Byte.MaxValue) PrintResult("-11.0R >= -3S", -11.0R >= -3S) PrintResult("-11.0R >= 24US", -11.0R >= 24US) PrintResult("-11.0R >= -5I", -11.0R >= -5I) PrintResult("-11.0R >= 26UI", -11.0R >= 26UI) PrintResult("-11.0R >= -7L", -11.0R >= -7L) PrintResult("-11.0R >= 28UL", -11.0R >= 28UL) PrintResult("-11.0R >= -9D", -11.0R >= -9D) PrintResult("-11.0R >= 10.0F", -11.0R >= 10.0F) PrintResult("-11.0R >= -11.0R", -11.0R >= -11.0R) PrintResult("-11.0R >= ""12""", -11.0R >= "12") PrintResult("-11.0R >= TypeCode.Double", -11.0R >= TypeCode.Double) PrintResult("""12"" >= False", "12" >= False) PrintResult("""12"" >= True", "12" >= True) PrintResult("""12"" >= System.SByte.MinValue", "12" >= System.SByte.MinValue) PrintResult("""12"" >= System.Byte.MaxValue", "12" >= System.Byte.MaxValue) PrintResult("""12"" >= -3S", "12" >= -3S) PrintResult("""12"" >= 24US", "12" >= 24US) PrintResult("""12"" >= -5I", "12" >= -5I) PrintResult("""12"" >= 26UI", "12" >= 26UI) PrintResult("""12"" >= -7L", "12" >= -7L) PrintResult("""12"" >= 28UL", "12" >= 28UL) PrintResult("""12"" >= -9D", "12" >= -9D) PrintResult("""12"" >= 10.0F", "12" >= 10.0F) PrintResult("""12"" >= -11.0R", "12" >= -11.0R) PrintResult("""12"" >= ""12""", "12" >= "12") PrintResult("""12"" >= TypeCode.Double", "12" >= TypeCode.Double) PrintResult("TypeCode.Double >= False", TypeCode.Double >= False) PrintResult("TypeCode.Double >= True", TypeCode.Double >= True) PrintResult("TypeCode.Double >= System.SByte.MinValue", TypeCode.Double >= System.SByte.MinValue) PrintResult("TypeCode.Double >= System.Byte.MaxValue", TypeCode.Double >= System.Byte.MaxValue) PrintResult("TypeCode.Double >= -3S", TypeCode.Double >= -3S) PrintResult("TypeCode.Double >= 24US", TypeCode.Double >= 24US) PrintResult("TypeCode.Double >= -5I", TypeCode.Double >= -5I) PrintResult("TypeCode.Double >= 26UI", TypeCode.Double >= 26UI) PrintResult("TypeCode.Double >= -7L", TypeCode.Double >= -7L) PrintResult("TypeCode.Double >= 28UL", TypeCode.Double >= 28UL) PrintResult("TypeCode.Double >= -9D", TypeCode.Double >= -9D) PrintResult("TypeCode.Double >= 10.0F", TypeCode.Double >= 10.0F) PrintResult("TypeCode.Double >= -11.0R", TypeCode.Double >= -11.0R) PrintResult("TypeCode.Double >= ""12""", TypeCode.Double >= "12") PrintResult("TypeCode.Double >= TypeCode.Double", TypeCode.Double >= TypeCode.Double) PrintResult("False < False", False < False) PrintResult("False < True", False < True) PrintResult("False < System.SByte.MinValue", False < System.SByte.MinValue) PrintResult("False < System.Byte.MaxValue", False < System.Byte.MaxValue) PrintResult("False < -3S", False < -3S) PrintResult("False < 24US", False < 24US) PrintResult("False < -5I", False < -5I) PrintResult("False < 26UI", False < 26UI) PrintResult("False < -7L", False < -7L) PrintResult("False < 28UL", False < 28UL) PrintResult("False < -9D", False < -9D) PrintResult("False < 10.0F", False < 10.0F) PrintResult("False < -11.0R", False < -11.0R) PrintResult("False < ""12""", False < "12") PrintResult("False < TypeCode.Double", False < TypeCode.Double) PrintResult("True < False", True < False) PrintResult("True < True", True < True) PrintResult("True < System.SByte.MinValue", True < System.SByte.MinValue) PrintResult("True < System.Byte.MaxValue", True < System.Byte.MaxValue) PrintResult("True < -3S", True < -3S) PrintResult("True < 24US", True < 24US) PrintResult("True < -5I", True < -5I) PrintResult("True < 26UI", True < 26UI) PrintResult("True < -7L", True < -7L) PrintResult("True < 28UL", True < 28UL) PrintResult("True < -9D", True < -9D) PrintResult("True < 10.0F", True < 10.0F) PrintResult("True < -11.0R", True < -11.0R) PrintResult("True < ""12""", True < "12") PrintResult("True < TypeCode.Double", True < TypeCode.Double) PrintResult("System.SByte.MinValue < False", System.SByte.MinValue < False) PrintResult("System.SByte.MinValue < True", System.SByte.MinValue < True) PrintResult("System.SByte.MinValue < System.SByte.MinValue", System.SByte.MinValue < System.SByte.MinValue) PrintResult("System.SByte.MinValue < System.Byte.MaxValue", System.SByte.MinValue < System.Byte.MaxValue) PrintResult("System.SByte.MinValue < -3S", System.SByte.MinValue < -3S) PrintResult("System.SByte.MinValue < 24US", System.SByte.MinValue < 24US) PrintResult("System.SByte.MinValue < -5I", System.SByte.MinValue < -5I) PrintResult("System.SByte.MinValue < 26UI", System.SByte.MinValue < 26UI) PrintResult("System.SByte.MinValue < -7L", System.SByte.MinValue < -7L) PrintResult("System.SByte.MinValue < 28UL", System.SByte.MinValue < 28UL) PrintResult("System.SByte.MinValue < -9D", System.SByte.MinValue < -9D) PrintResult("System.SByte.MinValue < 10.0F", System.SByte.MinValue < 10.0F) PrintResult("System.SByte.MinValue < -11.0R", System.SByte.MinValue < -11.0R) PrintResult("System.SByte.MinValue < ""12""", System.SByte.MinValue < "12") PrintResult("System.SByte.MinValue < TypeCode.Double", System.SByte.MinValue < TypeCode.Double) PrintResult("System.Byte.MaxValue < False", System.Byte.MaxValue < False) PrintResult("System.Byte.MaxValue < True", System.Byte.MaxValue < True) PrintResult("System.Byte.MaxValue < System.SByte.MinValue", System.Byte.MaxValue < System.SByte.MinValue) PrintResult("System.Byte.MaxValue < System.Byte.MaxValue", System.Byte.MaxValue < System.Byte.MaxValue) PrintResult("System.Byte.MaxValue < -3S", System.Byte.MaxValue < -3S) PrintResult("System.Byte.MaxValue < 24US", System.Byte.MaxValue < 24US) PrintResult("System.Byte.MaxValue < -5I", System.Byte.MaxValue < -5I) PrintResult("System.Byte.MaxValue < 26UI", System.Byte.MaxValue < 26UI) PrintResult("System.Byte.MaxValue < -7L", System.Byte.MaxValue < -7L) PrintResult("System.Byte.MaxValue < 28UL", System.Byte.MaxValue < 28UL) PrintResult("System.Byte.MaxValue < -9D", System.Byte.MaxValue < -9D) PrintResult("System.Byte.MaxValue < 10.0F", System.Byte.MaxValue < 10.0F) PrintResult("System.Byte.MaxValue < -11.0R", System.Byte.MaxValue < -11.0R) PrintResult("System.Byte.MaxValue < ""12""", System.Byte.MaxValue < "12") PrintResult("System.Byte.MaxValue < TypeCode.Double", System.Byte.MaxValue < TypeCode.Double) PrintResult("-3S < False", -3S < False) PrintResult("-3S < True", -3S < True) PrintResult("-3S < System.SByte.MinValue", -3S < System.SByte.MinValue) PrintResult("-3S < System.Byte.MaxValue", -3S < System.Byte.MaxValue) PrintResult("-3S < -3S", -3S < -3S) PrintResult("-3S < 24US", -3S < 24US) PrintResult("-3S < -5I", -3S < -5I) PrintResult("-3S < 26UI", -3S < 26UI) PrintResult("-3S < -7L", -3S < -7L) PrintResult("-3S < 28UL", -3S < 28UL) PrintResult("-3S < -9D", -3S < -9D) PrintResult("-3S < 10.0F", -3S < 10.0F) PrintResult("-3S < -11.0R", -3S < -11.0R) PrintResult("-3S < ""12""", -3S < "12") PrintResult("-3S < TypeCode.Double", -3S < TypeCode.Double) PrintResult("24US < False", 24US < False) PrintResult("24US < True", 24US < True) PrintResult("24US < System.SByte.MinValue", 24US < System.SByte.MinValue) PrintResult("24US < System.Byte.MaxValue", 24US < System.Byte.MaxValue) PrintResult("24US < -3S", 24US < -3S) PrintResult("24US < 24US", 24US < 24US) PrintResult("24US < -5I", 24US < -5I) PrintResult("24US < 26UI", 24US < 26UI) PrintResult("24US < -7L", 24US < -7L) PrintResult("24US < 28UL", 24US < 28UL) PrintResult("24US < -9D", 24US < -9D) PrintResult("24US < 10.0F", 24US < 10.0F) PrintResult("24US < -11.0R", 24US < -11.0R) PrintResult("24US < ""12""", 24US < "12") PrintResult("24US < TypeCode.Double", 24US < TypeCode.Double) PrintResult("-5I < False", -5I < False) PrintResult("-5I < True", -5I < True) PrintResult("-5I < System.SByte.MinValue", -5I < System.SByte.MinValue) PrintResult("-5I < System.Byte.MaxValue", -5I < System.Byte.MaxValue) PrintResult("-5I < -3S", -5I < -3S) PrintResult("-5I < 24US", -5I < 24US) PrintResult("-5I < -5I", -5I < -5I) PrintResult("-5I < 26UI", -5I < 26UI) PrintResult("-5I < -7L", -5I < -7L) PrintResult("-5I < 28UL", -5I < 28UL) PrintResult("-5I < -9D", -5I < -9D) PrintResult("-5I < 10.0F", -5I < 10.0F) PrintResult("-5I < -11.0R", -5I < -11.0R) PrintResult("-5I < ""12""", -5I < "12") PrintResult("-5I < TypeCode.Double", -5I < TypeCode.Double) PrintResult("26UI < False", 26UI < False) PrintResult("26UI < True", 26UI < True) PrintResult("26UI < System.SByte.MinValue", 26UI < System.SByte.MinValue) PrintResult("26UI < System.Byte.MaxValue", 26UI < System.Byte.MaxValue) PrintResult("26UI < -3S", 26UI < -3S) PrintResult("26UI < 24US", 26UI < 24US) PrintResult("26UI < -5I", 26UI < -5I) PrintResult("26UI < 26UI", 26UI < 26UI) PrintResult("26UI < -7L", 26UI < -7L) PrintResult("26UI < 28UL", 26UI < 28UL) PrintResult("26UI < -9D", 26UI < -9D) PrintResult("26UI < 10.0F", 26UI < 10.0F) PrintResult("26UI < -11.0R", 26UI < -11.0R) PrintResult("26UI < ""12""", 26UI < "12") PrintResult("26UI < TypeCode.Double", 26UI < TypeCode.Double) PrintResult("-7L < False", -7L < False) PrintResult("-7L < True", -7L < True) PrintResult("-7L < System.SByte.MinValue", -7L < System.SByte.MinValue) PrintResult("-7L < System.Byte.MaxValue", -7L < System.Byte.MaxValue) PrintResult("-7L < -3S", -7L < -3S) PrintResult("-7L < 24US", -7L < 24US) PrintResult("-7L < -5I", -7L < -5I) PrintResult("-7L < 26UI", -7L < 26UI) PrintResult("-7L < -7L", -7L < -7L) PrintResult("-7L < 28UL", -7L < 28UL) PrintResult("-7L < -9D", -7L < -9D) PrintResult("-7L < 10.0F", -7L < 10.0F) PrintResult("-7L < -11.0R", -7L < -11.0R) PrintResult("-7L < ""12""", -7L < "12") PrintResult("-7L < TypeCode.Double", -7L < TypeCode.Double) PrintResult("28UL < False", 28UL < False) PrintResult("28UL < True", 28UL < True) PrintResult("28UL < System.SByte.MinValue", 28UL < System.SByte.MinValue) PrintResult("28UL < System.Byte.MaxValue", 28UL < System.Byte.MaxValue) PrintResult("28UL < -3S", 28UL < -3S) PrintResult("28UL < 24US", 28UL < 24US) PrintResult("28UL < -5I", 28UL < -5I) PrintResult("28UL < 26UI", 28UL < 26UI) PrintResult("28UL < -7L", 28UL < -7L) PrintResult("28UL < 28UL", 28UL < 28UL) PrintResult("28UL < -9D", 28UL < -9D) PrintResult("28UL < 10.0F", 28UL < 10.0F) PrintResult("28UL < -11.0R", 28UL < -11.0R) PrintResult("28UL < ""12""", 28UL < "12") PrintResult("28UL < TypeCode.Double", 28UL < TypeCode.Double) PrintResult("-9D < False", -9D < False) PrintResult("-9D < True", -9D < True) PrintResult("-9D < System.SByte.MinValue", -9D < System.SByte.MinValue) PrintResult("-9D < System.Byte.MaxValue", -9D < System.Byte.MaxValue) PrintResult("-9D < -3S", -9D < -3S) PrintResult("-9D < 24US", -9D < 24US) PrintResult("-9D < -5I", -9D < -5I) PrintResult("-9D < 26UI", -9D < 26UI) PrintResult("-9D < -7L", -9D < -7L) PrintResult("-9D < 28UL", -9D < 28UL) PrintResult("-9D < -9D", -9D < -9D) PrintResult("-9D < 10.0F", -9D < 10.0F) PrintResult("-9D < -11.0R", -9D < -11.0R) PrintResult("-9D < ""12""", -9D < "12") PrintResult("-9D < TypeCode.Double", -9D < TypeCode.Double) PrintResult("10.0F < False", 10.0F < False) PrintResult("10.0F < True", 10.0F < True) PrintResult("10.0F < System.SByte.MinValue", 10.0F < System.SByte.MinValue) PrintResult("10.0F < System.Byte.MaxValue", 10.0F < System.Byte.MaxValue) PrintResult("10.0F < -3S", 10.0F < -3S) PrintResult("10.0F < 24US", 10.0F < 24US) PrintResult("10.0F < -5I", 10.0F < -5I) PrintResult("10.0F < 26UI", 10.0F < 26UI) PrintResult("10.0F < -7L", 10.0F < -7L) PrintResult("10.0F < 28UL", 10.0F < 28UL) PrintResult("10.0F < -9D", 10.0F < -9D) PrintResult("10.0F < 10.0F", 10.0F < 10.0F) PrintResult("10.0F < -11.0R", 10.0F < -11.0R) PrintResult("10.0F < ""12""", 10.0F < "12") PrintResult("10.0F < TypeCode.Double", 10.0F < TypeCode.Double) PrintResult("-11.0R < False", -11.0R < False) PrintResult("-11.0R < True", -11.0R < True) PrintResult("-11.0R < System.SByte.MinValue", -11.0R < System.SByte.MinValue) PrintResult("-11.0R < System.Byte.MaxValue", -11.0R < System.Byte.MaxValue) PrintResult("-11.0R < -3S", -11.0R < -3S) PrintResult("-11.0R < 24US", -11.0R < 24US) PrintResult("-11.0R < -5I", -11.0R < -5I) PrintResult("-11.0R < 26UI", -11.0R < 26UI) PrintResult("-11.0R < -7L", -11.0R < -7L) PrintResult("-11.0R < 28UL", -11.0R < 28UL) PrintResult("-11.0R < -9D", -11.0R < -9D) PrintResult("-11.0R < 10.0F", -11.0R < 10.0F) PrintResult("-11.0R < -11.0R", -11.0R < -11.0R) PrintResult("-11.0R < ""12""", -11.0R < "12") PrintResult("-11.0R < TypeCode.Double", -11.0R < TypeCode.Double) PrintResult("""12"" < False", "12" < False) PrintResult("""12"" < True", "12" < True) PrintResult("""12"" < System.SByte.MinValue", "12" < System.SByte.MinValue) PrintResult("""12"" < System.Byte.MaxValue", "12" < System.Byte.MaxValue) PrintResult("""12"" < -3S", "12" < -3S) PrintResult("""12"" < 24US", "12" < 24US) PrintResult("""12"" < -5I", "12" < -5I) PrintResult("""12"" < 26UI", "12" < 26UI) PrintResult("""12"" < -7L", "12" < -7L) PrintResult("""12"" < 28UL", "12" < 28UL) PrintResult("""12"" < -9D", "12" < -9D) PrintResult("""12"" < 10.0F", "12" < 10.0F) PrintResult("""12"" < -11.0R", "12" < -11.0R) PrintResult("""12"" < ""12""", "12" < "12") PrintResult("""12"" < TypeCode.Double", "12" < TypeCode.Double) PrintResult("TypeCode.Double < False", TypeCode.Double < False) PrintResult("TypeCode.Double < True", TypeCode.Double < True) PrintResult("TypeCode.Double < System.SByte.MinValue", TypeCode.Double < System.SByte.MinValue) PrintResult("TypeCode.Double < System.Byte.MaxValue", TypeCode.Double < System.Byte.MaxValue) PrintResult("TypeCode.Double < -3S", TypeCode.Double < -3S) PrintResult("TypeCode.Double < 24US", TypeCode.Double < 24US) PrintResult("TypeCode.Double < -5I", TypeCode.Double < -5I) PrintResult("TypeCode.Double < 26UI", TypeCode.Double < 26UI) PrintResult("TypeCode.Double < -7L", TypeCode.Double < -7L) PrintResult("TypeCode.Double < 28UL", TypeCode.Double < 28UL) PrintResult("TypeCode.Double < -9D", TypeCode.Double < -9D) PrintResult("TypeCode.Double < 10.0F", TypeCode.Double < 10.0F) PrintResult("TypeCode.Double < -11.0R", TypeCode.Double < -11.0R) PrintResult("TypeCode.Double < ""12""", TypeCode.Double < "12") PrintResult("TypeCode.Double < TypeCode.Double", TypeCode.Double < TypeCode.Double) PrintResult("False > False", False > False) PrintResult("False > True", False > True) PrintResult("False > System.SByte.MinValue", False > System.SByte.MinValue) PrintResult("False > System.Byte.MaxValue", False > System.Byte.MaxValue) PrintResult("False > -3S", False > -3S) PrintResult("False > 24US", False > 24US) PrintResult("False > -5I", False > -5I) PrintResult("False > 26UI", False > 26UI) PrintResult("False > -7L", False > -7L) PrintResult("False > 28UL", False > 28UL) PrintResult("False > -9D", False > -9D) PrintResult("False > 10.0F", False > 10.0F) PrintResult("False > -11.0R", False > -11.0R) PrintResult("False > ""12""", False > "12") PrintResult("False > TypeCode.Double", False > TypeCode.Double) PrintResult("True > False", True > False) PrintResult("True > True", True > True) PrintResult("True > System.SByte.MinValue", True > System.SByte.MinValue) PrintResult("True > System.Byte.MaxValue", True > System.Byte.MaxValue) PrintResult("True > -3S", True > -3S) PrintResult("True > 24US", True > 24US) PrintResult("True > -5I", True > -5I) PrintResult("True > 26UI", True > 26UI) PrintResult("True > -7L", True > -7L) PrintResult("True > 28UL", True > 28UL) PrintResult("True > -9D", True > -9D) PrintResult("True > 10.0F", True > 10.0F) PrintResult("True > -11.0R", True > -11.0R) PrintResult("True > ""12""", True > "12") PrintResult("True > TypeCode.Double", True > TypeCode.Double) PrintResult("System.SByte.MinValue > False", System.SByte.MinValue > False) PrintResult("System.SByte.MinValue > True", System.SByte.MinValue > True) PrintResult("System.SByte.MinValue > System.SByte.MinValue", System.SByte.MinValue > System.SByte.MinValue) PrintResult("System.SByte.MinValue > System.Byte.MaxValue", System.SByte.MinValue > System.Byte.MaxValue) PrintResult("System.SByte.MinValue > -3S", System.SByte.MinValue > -3S) PrintResult("System.SByte.MinValue > 24US", System.SByte.MinValue > 24US) PrintResult("System.SByte.MinValue > -5I", System.SByte.MinValue > -5I) PrintResult("System.SByte.MinValue > 26UI", System.SByte.MinValue > 26UI) PrintResult("System.SByte.MinValue > -7L", System.SByte.MinValue > -7L) PrintResult("System.SByte.MinValue > 28UL", System.SByte.MinValue > 28UL) PrintResult("System.SByte.MinValue > -9D", System.SByte.MinValue > -9D) PrintResult("System.SByte.MinValue > 10.0F", System.SByte.MinValue > 10.0F) PrintResult("System.SByte.MinValue > -11.0R", System.SByte.MinValue > -11.0R) PrintResult("System.SByte.MinValue > ""12""", System.SByte.MinValue > "12") PrintResult("System.SByte.MinValue > TypeCode.Double", System.SByte.MinValue > TypeCode.Double) PrintResult("System.Byte.MaxValue > False", System.Byte.MaxValue > False) PrintResult("System.Byte.MaxValue > True", System.Byte.MaxValue > True) PrintResult("System.Byte.MaxValue > System.SByte.MinValue", System.Byte.MaxValue > System.SByte.MinValue) PrintResult("System.Byte.MaxValue > System.Byte.MaxValue", System.Byte.MaxValue > System.Byte.MaxValue) PrintResult("System.Byte.MaxValue > -3S", System.Byte.MaxValue > -3S) PrintResult("System.Byte.MaxValue > 24US", System.Byte.MaxValue > 24US) PrintResult("System.Byte.MaxValue > -5I", System.Byte.MaxValue > -5I) PrintResult("System.Byte.MaxValue > 26UI", System.Byte.MaxValue > 26UI) PrintResult("System.Byte.MaxValue > -7L", System.Byte.MaxValue > -7L) PrintResult("System.Byte.MaxValue > 28UL", System.Byte.MaxValue > 28UL) PrintResult("System.Byte.MaxValue > -9D", System.Byte.MaxValue > -9D) PrintResult("System.Byte.MaxValue > 10.0F", System.Byte.MaxValue > 10.0F) PrintResult("System.Byte.MaxValue > -11.0R", System.Byte.MaxValue > -11.0R) PrintResult("System.Byte.MaxValue > ""12""", System.Byte.MaxValue > "12") PrintResult("System.Byte.MaxValue > TypeCode.Double", System.Byte.MaxValue > TypeCode.Double) PrintResult("-3S > False", -3S > False) PrintResult("-3S > True", -3S > True) PrintResult("-3S > System.SByte.MinValue", -3S > System.SByte.MinValue) PrintResult("-3S > System.Byte.MaxValue", -3S > System.Byte.MaxValue) PrintResult("-3S > -3S", -3S > -3S) PrintResult("-3S > 24US", -3S > 24US) PrintResult("-3S > -5I", -3S > -5I) PrintResult("-3S > 26UI", -3S > 26UI) PrintResult("-3S > -7L", -3S > -7L) PrintResult("-3S > 28UL", -3S > 28UL) PrintResult("-3S > -9D", -3S > -9D) PrintResult("-3S > 10.0F", -3S > 10.0F) PrintResult("-3S > -11.0R", -3S > -11.0R) PrintResult("-3S > ""12""", -3S > "12") PrintResult("-3S > TypeCode.Double", -3S > TypeCode.Double) PrintResult("24US > False", 24US > False) PrintResult("24US > True", 24US > True) PrintResult("24US > System.SByte.MinValue", 24US > System.SByte.MinValue) PrintResult("24US > System.Byte.MaxValue", 24US > System.Byte.MaxValue) PrintResult("24US > -3S", 24US > -3S) PrintResult("24US > 24US", 24US > 24US) PrintResult("24US > -5I", 24US > -5I) PrintResult("24US > 26UI", 24US > 26UI) PrintResult("24US > -7L", 24US > -7L) PrintResult("24US > 28UL", 24US > 28UL) PrintResult("24US > -9D", 24US > -9D) PrintResult("24US > 10.0F", 24US > 10.0F) PrintResult("24US > -11.0R", 24US > -11.0R) PrintResult("24US > ""12""", 24US > "12") PrintResult("24US > TypeCode.Double", 24US > TypeCode.Double) PrintResult("-5I > False", -5I > False) PrintResult("-5I > True", -5I > True) PrintResult("-5I > System.SByte.MinValue", -5I > System.SByte.MinValue) PrintResult("-5I > System.Byte.MaxValue", -5I > System.Byte.MaxValue) PrintResult("-5I > -3S", -5I > -3S) PrintResult("-5I > 24US", -5I > 24US) PrintResult("-5I > -5I", -5I > -5I) PrintResult("-5I > 26UI", -5I > 26UI) PrintResult("-5I > -7L", -5I > -7L) PrintResult("-5I > 28UL", -5I > 28UL) PrintResult("-5I > -9D", -5I > -9D) PrintResult("-5I > 10.0F", -5I > 10.0F) PrintResult("-5I > -11.0R", -5I > -11.0R) PrintResult("-5I > ""12""", -5I > "12") PrintResult("-5I > TypeCode.Double", -5I > TypeCode.Double) PrintResult("26UI > False", 26UI > False) PrintResult("26UI > True", 26UI > True) PrintResult("26UI > System.SByte.MinValue", 26UI > System.SByte.MinValue) PrintResult("26UI > System.Byte.MaxValue", 26UI > System.Byte.MaxValue) PrintResult("26UI > -3S", 26UI > -3S) PrintResult("26UI > 24US", 26UI > 24US) PrintResult("26UI > -5I", 26UI > -5I) PrintResult("26UI > 26UI", 26UI > 26UI) PrintResult("26UI > -7L", 26UI > -7L) PrintResult("26UI > 28UL", 26UI > 28UL) PrintResult("26UI > -9D", 26UI > -9D) PrintResult("26UI > 10.0F", 26UI > 10.0F) PrintResult("26UI > -11.0R", 26UI > -11.0R) PrintResult("26UI > ""12""", 26UI > "12") PrintResult("26UI > TypeCode.Double", 26UI > TypeCode.Double) PrintResult("-7L > False", -7L > False) PrintResult("-7L > True", -7L > True) PrintResult("-7L > System.SByte.MinValue", -7L > System.SByte.MinValue) PrintResult("-7L > System.Byte.MaxValue", -7L > System.Byte.MaxValue) PrintResult("-7L > -3S", -7L > -3S) PrintResult("-7L > 24US", -7L > 24US) PrintResult("-7L > -5I", -7L > -5I) PrintResult("-7L > 26UI", -7L > 26UI) PrintResult("-7L > -7L", -7L > -7L) PrintResult("-7L > 28UL", -7L > 28UL) PrintResult("-7L > -9D", -7L > -9D) PrintResult("-7L > 10.0F", -7L > 10.0F) PrintResult("-7L > -11.0R", -7L > -11.0R) PrintResult("-7L > ""12""", -7L > "12") PrintResult("-7L > TypeCode.Double", -7L > TypeCode.Double) PrintResult("28UL > False", 28UL > False) PrintResult("28UL > True", 28UL > True) PrintResult("28UL > System.SByte.MinValue", 28UL > System.SByte.MinValue) PrintResult("28UL > System.Byte.MaxValue", 28UL > System.Byte.MaxValue) PrintResult("28UL > -3S", 28UL > -3S) PrintResult("28UL > 24US", 28UL > 24US) PrintResult("28UL > -5I", 28UL > -5I) PrintResult("28UL > 26UI", 28UL > 26UI) PrintResult("28UL > -7L", 28UL > -7L) PrintResult("28UL > 28UL", 28UL > 28UL) PrintResult("28UL > -9D", 28UL > -9D) PrintResult("28UL > 10.0F", 28UL > 10.0F) PrintResult("28UL > -11.0R", 28UL > -11.0R) PrintResult("28UL > ""12""", 28UL > "12") PrintResult("28UL > TypeCode.Double", 28UL > TypeCode.Double) PrintResult("-9D > False", -9D > False) PrintResult("-9D > True", -9D > True) PrintResult("-9D > System.SByte.MinValue", -9D > System.SByte.MinValue) PrintResult("-9D > System.Byte.MaxValue", -9D > System.Byte.MaxValue) PrintResult("-9D > -3S", -9D > -3S) PrintResult("-9D > 24US", -9D > 24US) PrintResult("-9D > -5I", -9D > -5I) PrintResult("-9D > 26UI", -9D > 26UI) PrintResult("-9D > -7L", -9D > -7L) PrintResult("-9D > 28UL", -9D > 28UL) PrintResult("-9D > -9D", -9D > -9D) PrintResult("-9D > 10.0F", -9D > 10.0F) PrintResult("-9D > -11.0R", -9D > -11.0R) PrintResult("-9D > ""12""", -9D > "12") PrintResult("-9D > TypeCode.Double", -9D > TypeCode.Double) PrintResult("10.0F > False", 10.0F > False) PrintResult("10.0F > True", 10.0F > True) PrintResult("10.0F > System.SByte.MinValue", 10.0F > System.SByte.MinValue) PrintResult("10.0F > System.Byte.MaxValue", 10.0F > System.Byte.MaxValue) PrintResult("10.0F > -3S", 10.0F > -3S) PrintResult("10.0F > 24US", 10.0F > 24US) PrintResult("10.0F > -5I", 10.0F > -5I) PrintResult("10.0F > 26UI", 10.0F > 26UI) PrintResult("10.0F > -7L", 10.0F > -7L) PrintResult("10.0F > 28UL", 10.0F > 28UL) PrintResult("10.0F > -9D", 10.0F > -9D) PrintResult("10.0F > 10.0F", 10.0F > 10.0F) PrintResult("10.0F > -11.0R", 10.0F > -11.0R) PrintResult("10.0F > ""12""", 10.0F > "12") PrintResult("10.0F > TypeCode.Double", 10.0F > TypeCode.Double) PrintResult("-11.0R > False", -11.0R > False) PrintResult("-11.0R > True", -11.0R > True) PrintResult("-11.0R > System.SByte.MinValue", -11.0R > System.SByte.MinValue) PrintResult("-11.0R > System.Byte.MaxValue", -11.0R > System.Byte.MaxValue) PrintResult("-11.0R > -3S", -11.0R > -3S) PrintResult("-11.0R > 24US", -11.0R > 24US) PrintResult("-11.0R > -5I", -11.0R > -5I) PrintResult("-11.0R > 26UI", -11.0R > 26UI) PrintResult("-11.0R > -7L", -11.0R > -7L) PrintResult("-11.0R > 28UL", -11.0R > 28UL) PrintResult("-11.0R > -9D", -11.0R > -9D) PrintResult("-11.0R > 10.0F", -11.0R > 10.0F) PrintResult("-11.0R > -11.0R", -11.0R > -11.0R) PrintResult("-11.0R > ""12""", -11.0R > "12") PrintResult("-11.0R > TypeCode.Double", -11.0R > TypeCode.Double) PrintResult("""12"" > False", "12" > False) PrintResult("""12"" > True", "12" > True) PrintResult("""12"" > System.SByte.MinValue", "12" > System.SByte.MinValue) PrintResult("""12"" > System.Byte.MaxValue", "12" > System.Byte.MaxValue) PrintResult("""12"" > -3S", "12" > -3S) PrintResult("""12"" > 24US", "12" > 24US) PrintResult("""12"" > -5I", "12" > -5I) PrintResult("""12"" > 26UI", "12" > 26UI) PrintResult("""12"" > -7L", "12" > -7L) PrintResult("""12"" > 28UL", "12" > 28UL) PrintResult("""12"" > -9D", "12" > -9D) PrintResult("""12"" > 10.0F", "12" > 10.0F) PrintResult("""12"" > -11.0R", "12" > -11.0R) PrintResult("""12"" > ""12""", "12" > "12") PrintResult("""12"" > TypeCode.Double", "12" > TypeCode.Double) PrintResult("TypeCode.Double > False", TypeCode.Double > False) PrintResult("TypeCode.Double > True", TypeCode.Double > True) PrintResult("TypeCode.Double > System.SByte.MinValue", TypeCode.Double > System.SByte.MinValue) PrintResult("TypeCode.Double > System.Byte.MaxValue", TypeCode.Double > System.Byte.MaxValue) PrintResult("TypeCode.Double > -3S", TypeCode.Double > -3S) PrintResult("TypeCode.Double > 24US", TypeCode.Double > 24US) PrintResult("TypeCode.Double > -5I", TypeCode.Double > -5I) PrintResult("TypeCode.Double > 26UI", TypeCode.Double > 26UI) PrintResult("TypeCode.Double > -7L", TypeCode.Double > -7L) PrintResult("TypeCode.Double > 28UL", TypeCode.Double > 28UL) PrintResult("TypeCode.Double > -9D", TypeCode.Double > -9D) PrintResult("TypeCode.Double > 10.0F", TypeCode.Double > 10.0F) PrintResult("TypeCode.Double > -11.0R", TypeCode.Double > -11.0R) PrintResult("TypeCode.Double > ""12""", TypeCode.Double > "12") PrintResult("TypeCode.Double > TypeCode.Double", TypeCode.Double > TypeCode.Double) PrintResult("False Xor False", False Xor False) PrintResult("False Xor True", False Xor True) PrintResult("False Xor System.SByte.MinValue", False Xor System.SByte.MinValue) PrintResult("False Xor System.Byte.MaxValue", False Xor System.Byte.MaxValue) PrintResult("False Xor -3S", False Xor -3S) PrintResult("False Xor 24US", False Xor 24US) PrintResult("False Xor -5I", False Xor -5I) PrintResult("False Xor 26UI", False Xor 26UI) PrintResult("False Xor -7L", False Xor -7L) PrintResult("False Xor 28UL", False Xor 28UL) PrintResult("False Xor -9D", False Xor -9D) PrintResult("False Xor 10.0F", False Xor 10.0F) PrintResult("False Xor -11.0R", False Xor -11.0R) PrintResult("False Xor ""12""", False Xor "12") PrintResult("False Xor TypeCode.Double", False Xor TypeCode.Double) PrintResult("True Xor False", True Xor False) PrintResult("True Xor True", True Xor True) PrintResult("True Xor System.SByte.MinValue", True Xor System.SByte.MinValue) PrintResult("True Xor System.Byte.MaxValue", True Xor System.Byte.MaxValue) PrintResult("True Xor -3S", True Xor -3S) PrintResult("True Xor 24US", True Xor 24US) PrintResult("True Xor -5I", True Xor -5I) PrintResult("True Xor 26UI", True Xor 26UI) PrintResult("True Xor -7L", True Xor -7L) PrintResult("True Xor 28UL", True Xor 28UL) PrintResult("True Xor -9D", True Xor -9D) PrintResult("True Xor 10.0F", True Xor 10.0F) PrintResult("True Xor -11.0R", True Xor -11.0R) PrintResult("True Xor ""12""", True Xor "12") PrintResult("True Xor TypeCode.Double", True Xor TypeCode.Double) PrintResult("System.SByte.MinValue Xor False", System.SByte.MinValue Xor False) PrintResult("System.SByte.MinValue Xor True", System.SByte.MinValue Xor True) PrintResult("System.SByte.MinValue Xor System.SByte.MinValue", System.SByte.MinValue Xor System.SByte.MinValue) PrintResult("System.SByte.MinValue Xor System.Byte.MaxValue", System.SByte.MinValue Xor System.Byte.MaxValue) PrintResult("System.SByte.MinValue Xor -3S", System.SByte.MinValue Xor -3S) PrintResult("System.SByte.MinValue Xor 24US", System.SByte.MinValue Xor 24US) PrintResult("System.SByte.MinValue Xor -5I", System.SByte.MinValue Xor -5I) PrintResult("System.SByte.MinValue Xor 26UI", System.SByte.MinValue Xor 26UI) PrintResult("System.SByte.MinValue Xor -7L", System.SByte.MinValue Xor -7L) PrintResult("System.SByte.MinValue Xor 28UL", System.SByte.MinValue Xor 28UL) PrintResult("System.SByte.MinValue Xor -9D", System.SByte.MinValue Xor -9D) PrintResult("System.SByte.MinValue Xor 10.0F", System.SByte.MinValue Xor 10.0F) PrintResult("System.SByte.MinValue Xor -11.0R", System.SByte.MinValue Xor -11.0R) PrintResult("System.SByte.MinValue Xor ""12""", System.SByte.MinValue Xor "12") PrintResult("System.SByte.MinValue Xor TypeCode.Double", System.SByte.MinValue Xor TypeCode.Double) PrintResult("System.Byte.MaxValue Xor False", System.Byte.MaxValue Xor False) PrintResult("System.Byte.MaxValue Xor True", System.Byte.MaxValue Xor True) PrintResult("System.Byte.MaxValue Xor System.SByte.MinValue", System.Byte.MaxValue Xor System.SByte.MinValue) PrintResult("System.Byte.MaxValue Xor System.Byte.MaxValue", System.Byte.MaxValue Xor System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Xor -3S", System.Byte.MaxValue Xor -3S) PrintResult("System.Byte.MaxValue Xor 24US", System.Byte.MaxValue Xor 24US) PrintResult("System.Byte.MaxValue Xor -5I", System.Byte.MaxValue Xor -5I) PrintResult("System.Byte.MaxValue Xor 26UI", System.Byte.MaxValue Xor 26UI) PrintResult("System.Byte.MaxValue Xor -7L", System.Byte.MaxValue Xor -7L) PrintResult("System.Byte.MaxValue Xor 28UL", System.Byte.MaxValue Xor 28UL) PrintResult("System.Byte.MaxValue Xor -9D", System.Byte.MaxValue Xor -9D) PrintResult("System.Byte.MaxValue Xor 10.0F", System.Byte.MaxValue Xor 10.0F) PrintResult("System.Byte.MaxValue Xor -11.0R", System.Byte.MaxValue Xor -11.0R) PrintResult("System.Byte.MaxValue Xor ""12""", System.Byte.MaxValue Xor "12") PrintResult("System.Byte.MaxValue Xor TypeCode.Double", System.Byte.MaxValue Xor TypeCode.Double) PrintResult("-3S Xor False", -3S Xor False) PrintResult("-3S Xor True", -3S Xor True) PrintResult("-3S Xor System.SByte.MinValue", -3S Xor System.SByte.MinValue) PrintResult("-3S Xor System.Byte.MaxValue", -3S Xor System.Byte.MaxValue) PrintResult("-3S Xor -3S", -3S Xor -3S) PrintResult("-3S Xor 24US", -3S Xor 24US) PrintResult("-3S Xor -5I", -3S Xor -5I) PrintResult("-3S Xor 26UI", -3S Xor 26UI) PrintResult("-3S Xor -7L", -3S Xor -7L) PrintResult("-3S Xor 28UL", -3S Xor 28UL) PrintResult("-3S Xor -9D", -3S Xor -9D) PrintResult("-3S Xor 10.0F", -3S Xor 10.0F) PrintResult("-3S Xor -11.0R", -3S Xor -11.0R) PrintResult("-3S Xor ""12""", -3S Xor "12") PrintResult("-3S Xor TypeCode.Double", -3S Xor TypeCode.Double) PrintResult("24US Xor False", 24US Xor False) PrintResult("24US Xor True", 24US Xor True) PrintResult("24US Xor System.SByte.MinValue", 24US Xor System.SByte.MinValue) PrintResult("24US Xor System.Byte.MaxValue", 24US Xor System.Byte.MaxValue) PrintResult("24US Xor -3S", 24US Xor -3S) PrintResult("24US Xor 24US", 24US Xor 24US) PrintResult("24US Xor -5I", 24US Xor -5I) PrintResult("24US Xor 26UI", 24US Xor 26UI) PrintResult("24US Xor -7L", 24US Xor -7L) PrintResult("24US Xor 28UL", 24US Xor 28UL) PrintResult("24US Xor -9D", 24US Xor -9D) PrintResult("24US Xor 10.0F", 24US Xor 10.0F) PrintResult("24US Xor -11.0R", 24US Xor -11.0R) PrintResult("24US Xor ""12""", 24US Xor "12") PrintResult("24US Xor TypeCode.Double", 24US Xor TypeCode.Double) PrintResult("-5I Xor False", -5I Xor False) PrintResult("-5I Xor True", -5I Xor True) PrintResult("-5I Xor System.SByte.MinValue", -5I Xor System.SByte.MinValue) PrintResult("-5I Xor System.Byte.MaxValue", -5I Xor System.Byte.MaxValue) PrintResult("-5I Xor -3S", -5I Xor -3S) PrintResult("-5I Xor 24US", -5I Xor 24US) PrintResult("-5I Xor -5I", -5I Xor -5I) PrintResult("-5I Xor 26UI", -5I Xor 26UI) PrintResult("-5I Xor -7L", -5I Xor -7L) PrintResult("-5I Xor 28UL", -5I Xor 28UL) PrintResult("-5I Xor -9D", -5I Xor -9D) PrintResult("-5I Xor 10.0F", -5I Xor 10.0F) PrintResult("-5I Xor -11.0R", -5I Xor -11.0R) PrintResult("-5I Xor ""12""", -5I Xor "12") PrintResult("-5I Xor TypeCode.Double", -5I Xor TypeCode.Double) PrintResult("26UI Xor False", 26UI Xor False) PrintResult("26UI Xor True", 26UI Xor True) PrintResult("26UI Xor System.SByte.MinValue", 26UI Xor System.SByte.MinValue) PrintResult("26UI Xor System.Byte.MaxValue", 26UI Xor System.Byte.MaxValue) PrintResult("26UI Xor -3S", 26UI Xor -3S) PrintResult("26UI Xor 24US", 26UI Xor 24US) PrintResult("26UI Xor -5I", 26UI Xor -5I) PrintResult("26UI Xor 26UI", 26UI Xor 26UI) PrintResult("26UI Xor -7L", 26UI Xor -7L) PrintResult("26UI Xor 28UL", 26UI Xor 28UL) PrintResult("26UI Xor -9D", 26UI Xor -9D) PrintResult("26UI Xor 10.0F", 26UI Xor 10.0F) PrintResult("26UI Xor -11.0R", 26UI Xor -11.0R) PrintResult("26UI Xor ""12""", 26UI Xor "12") PrintResult("26UI Xor TypeCode.Double", 26UI Xor TypeCode.Double) PrintResult("-7L Xor False", -7L Xor False) PrintResult("-7L Xor True", -7L Xor True) PrintResult("-7L Xor System.SByte.MinValue", -7L Xor System.SByte.MinValue) PrintResult("-7L Xor System.Byte.MaxValue", -7L Xor System.Byte.MaxValue) PrintResult("-7L Xor -3S", -7L Xor -3S) PrintResult("-7L Xor 24US", -7L Xor 24US) PrintResult("-7L Xor -5I", -7L Xor -5I) PrintResult("-7L Xor 26UI", -7L Xor 26UI) PrintResult("-7L Xor -7L", -7L Xor -7L) PrintResult("-7L Xor 28UL", -7L Xor 28UL) PrintResult("-7L Xor -9D", -7L Xor -9D) PrintResult("-7L Xor 10.0F", -7L Xor 10.0F) PrintResult("-7L Xor -11.0R", -7L Xor -11.0R) PrintResult("-7L Xor ""12""", -7L Xor "12") PrintResult("-7L Xor TypeCode.Double", -7L Xor TypeCode.Double) PrintResult("28UL Xor False", 28UL Xor False) PrintResult("28UL Xor True", 28UL Xor True) PrintResult("28UL Xor System.SByte.MinValue", 28UL Xor System.SByte.MinValue) PrintResult("28UL Xor System.Byte.MaxValue", 28UL Xor System.Byte.MaxValue) PrintResult("28UL Xor -3S", 28UL Xor -3S) PrintResult("28UL Xor 24US", 28UL Xor 24US) PrintResult("28UL Xor -5I", 28UL Xor -5I) PrintResult("28UL Xor 26UI", 28UL Xor 26UI) PrintResult("28UL Xor -7L", 28UL Xor -7L) PrintResult("28UL Xor 28UL", 28UL Xor 28UL) PrintResult("28UL Xor -9D", 28UL Xor -9D) PrintResult("28UL Xor 10.0F", 28UL Xor 10.0F) PrintResult("28UL Xor -11.0R", 28UL Xor -11.0R) PrintResult("28UL Xor ""12""", 28UL Xor "12") PrintResult("28UL Xor TypeCode.Double", 28UL Xor TypeCode.Double) PrintResult("-9D Xor False", -9D Xor False) PrintResult("-9D Xor True", -9D Xor True) PrintResult("-9D Xor System.SByte.MinValue", -9D Xor System.SByte.MinValue) PrintResult("-9D Xor System.Byte.MaxValue", -9D Xor System.Byte.MaxValue) PrintResult("-9D Xor -3S", -9D Xor -3S) PrintResult("-9D Xor 24US", -9D Xor 24US) PrintResult("-9D Xor -5I", -9D Xor -5I) PrintResult("-9D Xor 26UI", -9D Xor 26UI) PrintResult("-9D Xor -7L", -9D Xor -7L) PrintResult("-9D Xor 28UL", -9D Xor 28UL) PrintResult("-9D Xor -9D", -9D Xor -9D) PrintResult("-9D Xor 10.0F", -9D Xor 10.0F) PrintResult("-9D Xor -11.0R", -9D Xor -11.0R) PrintResult("-9D Xor ""12""", -9D Xor "12") PrintResult("-9D Xor TypeCode.Double", -9D Xor TypeCode.Double) PrintResult("10.0F Xor False", 10.0F Xor False) PrintResult("10.0F Xor True", 10.0F Xor True) PrintResult("10.0F Xor System.SByte.MinValue", 10.0F Xor System.SByte.MinValue) PrintResult("10.0F Xor System.Byte.MaxValue", 10.0F Xor System.Byte.MaxValue) PrintResult("10.0F Xor -3S", 10.0F Xor -3S) PrintResult("10.0F Xor 24US", 10.0F Xor 24US) PrintResult("10.0F Xor -5I", 10.0F Xor -5I) PrintResult("10.0F Xor 26UI", 10.0F Xor 26UI) PrintResult("10.0F Xor -7L", 10.0F Xor -7L) PrintResult("10.0F Xor 28UL", 10.0F Xor 28UL) PrintResult("10.0F Xor -9D", 10.0F Xor -9D) PrintResult("10.0F Xor 10.0F", 10.0F Xor 10.0F) PrintResult("10.0F Xor -11.0R", 10.0F Xor -11.0R) PrintResult("10.0F Xor ""12""", 10.0F Xor "12") PrintResult("10.0F Xor TypeCode.Double", 10.0F Xor TypeCode.Double) PrintResult("-11.0R Xor False", -11.0R Xor False) PrintResult("-11.0R Xor True", -11.0R Xor True) PrintResult("-11.0R Xor System.SByte.MinValue", -11.0R Xor System.SByte.MinValue) PrintResult("-11.0R Xor System.Byte.MaxValue", -11.0R Xor System.Byte.MaxValue) PrintResult("-11.0R Xor -3S", -11.0R Xor -3S) PrintResult("-11.0R Xor 24US", -11.0R Xor 24US) PrintResult("-11.0R Xor -5I", -11.0R Xor -5I) PrintResult("-11.0R Xor 26UI", -11.0R Xor 26UI) PrintResult("-11.0R Xor -7L", -11.0R Xor -7L) PrintResult("-11.0R Xor 28UL", -11.0R Xor 28UL) PrintResult("-11.0R Xor -9D", -11.0R Xor -9D) PrintResult("-11.0R Xor 10.0F", -11.0R Xor 10.0F) PrintResult("-11.0R Xor -11.0R", -11.0R Xor -11.0R) PrintResult("-11.0R Xor ""12""", -11.0R Xor "12") PrintResult("-11.0R Xor TypeCode.Double", -11.0R Xor TypeCode.Double) PrintResult("""12"" Xor False", "12" Xor False) PrintResult("""12"" Xor True", "12" Xor True) PrintResult("""12"" Xor System.SByte.MinValue", "12" Xor System.SByte.MinValue) PrintResult("""12"" Xor System.Byte.MaxValue", "12" Xor System.Byte.MaxValue) PrintResult("""12"" Xor -3S", "12" Xor -3S) PrintResult("""12"" Xor 24US", "12" Xor 24US) PrintResult("""12"" Xor -5I", "12" Xor -5I) PrintResult("""12"" Xor 26UI", "12" Xor 26UI) PrintResult("""12"" Xor -7L", "12" Xor -7L) PrintResult("""12"" Xor 28UL", "12" Xor 28UL) PrintResult("""12"" Xor -9D", "12" Xor -9D) PrintResult("""12"" Xor 10.0F", "12" Xor 10.0F) PrintResult("""12"" Xor -11.0R", "12" Xor -11.0R) PrintResult("""12"" Xor ""12""", "12" Xor "12") PrintResult("""12"" Xor TypeCode.Double", "12" Xor TypeCode.Double) PrintResult("TypeCode.Double Xor False", TypeCode.Double Xor False) PrintResult("TypeCode.Double Xor True", TypeCode.Double Xor True) PrintResult("TypeCode.Double Xor System.SByte.MinValue", TypeCode.Double Xor System.SByte.MinValue) PrintResult("TypeCode.Double Xor System.Byte.MaxValue", TypeCode.Double Xor System.Byte.MaxValue) PrintResult("TypeCode.Double Xor -3S", TypeCode.Double Xor -3S) PrintResult("TypeCode.Double Xor 24US", TypeCode.Double Xor 24US) PrintResult("TypeCode.Double Xor -5I", TypeCode.Double Xor -5I) PrintResult("TypeCode.Double Xor 26UI", TypeCode.Double Xor 26UI) PrintResult("TypeCode.Double Xor -7L", TypeCode.Double Xor -7L) PrintResult("TypeCode.Double Xor 28UL", TypeCode.Double Xor 28UL) PrintResult("TypeCode.Double Xor -9D", TypeCode.Double Xor -9D) PrintResult("TypeCode.Double Xor 10.0F", TypeCode.Double Xor 10.0F) PrintResult("TypeCode.Double Xor -11.0R", TypeCode.Double Xor -11.0R) PrintResult("TypeCode.Double Xor ""12""", TypeCode.Double Xor "12") PrintResult("TypeCode.Double Xor TypeCode.Double", TypeCode.Double Xor TypeCode.Double) PrintResult("False Or False", False Or False) PrintResult("False Or True", False Or True) PrintResult("False Or System.SByte.MinValue", False Or System.SByte.MinValue) PrintResult("False Or System.Byte.MaxValue", False Or System.Byte.MaxValue) PrintResult("False Or -3S", False Or -3S) PrintResult("False Or 24US", False Or 24US) PrintResult("False Or -5I", False Or -5I) PrintResult("False Or 26UI", False Or 26UI) PrintResult("False Or -7L", False Or -7L) PrintResult("False Or 28UL", False Or 28UL) PrintResult("False Or -9D", False Or -9D) PrintResult("False Or 10.0F", False Or 10.0F) PrintResult("False Or -11.0R", False Or -11.0R) PrintResult("False Or ""12""", False Or "12") PrintResult("False Or TypeCode.Double", False Or TypeCode.Double) PrintResult("True Or False", True Or False) PrintResult("True Or True", True Or True) PrintResult("True Or System.SByte.MinValue", True Or System.SByte.MinValue) PrintResult("True Or System.Byte.MaxValue", True Or System.Byte.MaxValue) PrintResult("True Or -3S", True Or -3S) PrintResult("True Or 24US", True Or 24US) PrintResult("True Or -5I", True Or -5I) PrintResult("True Or 26UI", True Or 26UI) PrintResult("True Or -7L", True Or -7L) PrintResult("True Or 28UL", True Or 28UL) PrintResult("True Or -9D", True Or -9D) PrintResult("True Or 10.0F", True Or 10.0F) PrintResult("True Or -11.0R", True Or -11.0R) PrintResult("True Or ""12""", True Or "12") PrintResult("True Or TypeCode.Double", True Or TypeCode.Double) PrintResult("System.SByte.MinValue Or False", System.SByte.MinValue Or False) PrintResult("System.SByte.MinValue Or True", System.SByte.MinValue Or True) PrintResult("System.SByte.MinValue Or System.SByte.MinValue", System.SByte.MinValue Or System.SByte.MinValue) PrintResult("System.SByte.MinValue Or System.Byte.MaxValue", System.SByte.MinValue Or System.Byte.MaxValue) PrintResult("System.SByte.MinValue Or -3S", System.SByte.MinValue Or -3S) PrintResult("System.SByte.MinValue Or 24US", System.SByte.MinValue Or 24US) PrintResult("System.SByte.MinValue Or -5I", System.SByte.MinValue Or -5I) PrintResult("System.SByte.MinValue Or 26UI", System.SByte.MinValue Or 26UI) PrintResult("System.SByte.MinValue Or -7L", System.SByte.MinValue Or -7L) PrintResult("System.SByte.MinValue Or 28UL", System.SByte.MinValue Or 28UL) PrintResult("System.SByte.MinValue Or -9D", System.SByte.MinValue Or -9D) PrintResult("System.SByte.MinValue Or 10.0F", System.SByte.MinValue Or 10.0F) PrintResult("System.SByte.MinValue Or -11.0R", System.SByte.MinValue Or -11.0R) PrintResult("System.SByte.MinValue Or ""12""", System.SByte.MinValue Or "12") PrintResult("System.SByte.MinValue Or TypeCode.Double", System.SByte.MinValue Or TypeCode.Double) PrintResult("System.Byte.MaxValue Or False", System.Byte.MaxValue Or False) PrintResult("System.Byte.MaxValue Or True", System.Byte.MaxValue Or True) PrintResult("System.Byte.MaxValue Or System.SByte.MinValue", System.Byte.MaxValue Or System.SByte.MinValue) PrintResult("System.Byte.MaxValue Or System.Byte.MaxValue", System.Byte.MaxValue Or System.Byte.MaxValue) PrintResult("System.Byte.MaxValue Or -3S", System.Byte.MaxValue Or -3S) PrintResult("System.Byte.MaxValue Or 24US", System.Byte.MaxValue Or 24US) PrintResult("System.Byte.MaxValue Or -5I", System.Byte.MaxValue Or -5I) PrintResult("System.Byte.MaxValue Or 26UI", System.Byte.MaxValue Or 26UI) PrintResult("System.Byte.MaxValue Or -7L", System.Byte.MaxValue Or -7L) PrintResult("System.Byte.MaxValue Or 28UL", System.Byte.MaxValue Or 28UL) PrintResult("System.Byte.MaxValue Or -9D", System.Byte.MaxValue Or -9D) PrintResult("System.Byte.MaxValue Or 10.0F", System.Byte.MaxValue Or 10.0F) PrintResult("System.Byte.MaxValue Or -11.0R", System.Byte.MaxValue Or -11.0R) PrintResult("System.Byte.MaxValue Or ""12""", System.Byte.MaxValue Or "12") PrintResult("System.Byte.MaxValue Or TypeCode.Double", System.Byte.MaxValue Or TypeCode.Double) PrintResult("-3S Or False", -3S Or False) PrintResult("-3S Or True", -3S Or True) PrintResult("-3S Or System.SByte.MinValue", -3S Or System.SByte.MinValue) PrintResult("-3S Or System.Byte.MaxValue", -3S Or System.Byte.MaxValue) PrintResult("-3S Or -3S", -3S Or -3S) PrintResult("-3S Or 24US", -3S Or 24US) PrintResult("-3S Or -5I", -3S Or -5I) PrintResult("-3S Or 26UI", -3S Or 26UI) PrintResult("-3S Or -7L", -3S Or -7L) PrintResult("-3S Or 28UL", -3S Or 28UL) PrintResult("-3S Or -9D", -3S Or -9D) PrintResult("-3S Or 10.0F", -3S Or 10.0F) PrintResult("-3S Or -11.0R", -3S Or -11.0R) PrintResult("-3S Or ""12""", -3S Or "12") PrintResult("-3S Or TypeCode.Double", -3S Or TypeCode.Double) PrintResult("24US Or False", 24US Or False) PrintResult("24US Or True", 24US Or True) PrintResult("24US Or System.SByte.MinValue", 24US Or System.SByte.MinValue) PrintResult("24US Or System.Byte.MaxValue", 24US Or System.Byte.MaxValue) PrintResult("24US Or -3S", 24US Or -3S) PrintResult("24US Or 24US", 24US Or 24US) PrintResult("24US Or -5I", 24US Or -5I) PrintResult("24US Or 26UI", 24US Or 26UI) PrintResult("24US Or -7L", 24US Or -7L) PrintResult("24US Or 28UL", 24US Or 28UL) PrintResult("24US Or -9D", 24US Or -9D) PrintResult("24US Or 10.0F", 24US Or 10.0F) PrintResult("24US Or -11.0R", 24US Or -11.0R) PrintResult("24US Or ""12""", 24US Or "12") PrintResult("24US Or TypeCode.Double", 24US Or TypeCode.Double) PrintResult("-5I Or False", -5I Or False) PrintResult("-5I Or True", -5I Or True) PrintResult("-5I Or System.SByte.MinValue", -5I Or System.SByte.MinValue) PrintResult("-5I Or System.Byte.MaxValue", -5I Or System.Byte.MaxValue) PrintResult("-5I Or -3S", -5I Or -3S) PrintResult("-5I Or 24US", -5I Or 24US) PrintResult("-5I Or -5I", -5I Or -5I) PrintResult("-5I Or 26UI", -5I Or 26UI) PrintResult("-5I Or -7L", -5I Or -7L) PrintResult("-5I Or 28UL", -5I Or 28UL) PrintResult("-5I Or -9D", -5I Or -9D) PrintResult("-5I Or 10.0F", -5I Or 10.0F) PrintResult("-5I Or -11.0R", -5I Or -11.0R) PrintResult("-5I Or ""12""", -5I Or "12") PrintResult("-5I Or TypeCode.Double", -5I Or TypeCode.Double) PrintResult("26UI Or False", 26UI Or False) PrintResult("26UI Or True", 26UI Or True) PrintResult("26UI Or System.SByte.MinValue", 26UI Or System.SByte.MinValue) PrintResult("26UI Or System.Byte.MaxValue", 26UI Or System.Byte.MaxValue) PrintResult("26UI Or -3S", 26UI Or -3S) PrintResult("26UI Or 24US", 26UI Or 24US) PrintResult("26UI Or -5I", 26UI Or -5I) PrintResult("26UI Or 26UI", 26UI Or 26UI) PrintResult("26UI Or -7L", 26UI Or -7L) PrintResult("26UI Or 28UL", 26UI Or 28UL) PrintResult("26UI Or -9D", 26UI Or -9D) PrintResult("26UI Or 10.0F", 26UI Or 10.0F) PrintResult("26UI Or -11.0R", 26UI Or -11.0R) PrintResult("26UI Or ""12""", 26UI Or "12") PrintResult("26UI Or TypeCode.Double", 26UI Or TypeCode.Double) PrintResult("-7L Or False", -7L Or False) PrintResult("-7L Or True", -7L Or True) PrintResult("-7L Or System.SByte.MinValue", -7L Or System.SByte.MinValue) PrintResult("-7L Or System.Byte.MaxValue", -7L Or System.Byte.MaxValue) PrintResult("-7L Or -3S", -7L Or -3S) PrintResult("-7L Or 24US", -7L Or 24US) PrintResult("-7L Or -5I", -7L Or -5I) PrintResult("-7L Or 26UI", -7L Or 26UI) PrintResult("-7L Or -7L", -7L Or -7L) PrintResult("-7L Or 28UL", -7L Or 28UL) PrintResult("-7L Or -9D", -7L Or -9D) PrintResult("-7L Or 10.0F", -7L Or 10.0F) PrintResult("-7L Or -11.0R", -7L Or -11.0R) PrintResult("-7L Or ""12""", -7L Or "12") PrintResult("-7L Or TypeCode.Double", -7L Or TypeCode.Double) PrintResult("28UL Or False", 28UL Or False) PrintResult("28UL Or True", 28UL Or True) PrintResult("28UL Or System.SByte.MinValue", 28UL Or System.SByte.MinValue) PrintResult("28UL Or System.Byte.MaxValue", 28UL Or System.Byte.MaxValue) PrintResult("28UL Or -3S", 28UL Or -3S) PrintResult("28UL Or 24US", 28UL Or 24US) PrintResult("28UL Or -5I", 28UL Or -5I) PrintResult("28UL Or 26UI", 28UL Or 26UI) PrintResult("28UL Or -7L", 28UL Or -7L) PrintResult("28UL Or 28UL", 28UL Or 28UL) PrintResult("28UL Or -9D", 28UL Or -9D) PrintResult("28UL Or 10.0F", 28UL Or 10.0F) PrintResult("28UL Or -11.0R", 28UL Or -11.0R) PrintResult("28UL Or ""12""", 28UL Or "12") PrintResult("28UL Or TypeCode.Double", 28UL Or TypeCode.Double) PrintResult("-9D Or False", -9D Or False) PrintResult("-9D Or True", -9D Or True) PrintResult("-9D Or System.SByte.MinValue", -9D Or System.SByte.MinValue) PrintResult("-9D Or System.Byte.MaxValue", -9D Or System.Byte.MaxValue) PrintResult("-9D Or -3S", -9D Or -3S) PrintResult("-9D Or 24US", -9D Or 24US) PrintResult("-9D Or -5I", -9D Or -5I) PrintResult("-9D Or 26UI", -9D Or 26UI) PrintResult("-9D Or -7L", -9D Or -7L) PrintResult("-9D Or 28UL", -9D Or 28UL) PrintResult("-9D Or -9D", -9D Or -9D) PrintResult("-9D Or 10.0F", -9D Or 10.0F) PrintResult("-9D Or -11.0R", -9D Or -11.0R) PrintResult("-9D Or ""12""", -9D Or "12") PrintResult("-9D Or TypeCode.Double", -9D Or TypeCode.Double) PrintResult("10.0F Or False", 10.0F Or False) PrintResult("10.0F Or True", 10.0F Or True) PrintResult("10.0F Or System.SByte.MinValue", 10.0F Or System.SByte.MinValue) PrintResult("10.0F Or System.Byte.MaxValue", 10.0F Or System.Byte.MaxValue) PrintResult("10.0F Or -3S", 10.0F Or -3S) PrintResult("10.0F Or 24US", 10.0F Or 24US) PrintResult("10.0F Or -5I", 10.0F Or -5I) PrintResult("10.0F Or 26UI", 10.0F Or 26UI) PrintResult("10.0F Or -7L", 10.0F Or -7L) PrintResult("10.0F Or 28UL", 10.0F Or 28UL) PrintResult("10.0F Or -9D", 10.0F Or -9D) PrintResult("10.0F Or 10.0F", 10.0F Or 10.0F) PrintResult("10.0F Or -11.0R", 10.0F Or -11.0R) PrintResult("10.0F Or ""12""", 10.0F Or "12") PrintResult("10.0F Or TypeCode.Double", 10.0F Or TypeCode.Double) PrintResult("-11.0R Or False", -11.0R Or False) PrintResult("-11.0R Or True", -11.0R Or True) PrintResult("-11.0R Or System.SByte.MinValue", -11.0R Or System.SByte.MinValue) PrintResult("-11.0R Or System.Byte.MaxValue", -11.0R Or System.Byte.MaxValue) PrintResult("-11.0R Or -3S", -11.0R Or -3S) PrintResult("-11.0R Or 24US", -11.0R Or 24US) PrintResult("-11.0R Or -5I", -11.0R Or -5I) PrintResult("-11.0R Or 26UI", -11.0R Or 26UI) PrintResult("-11.0R Or -7L", -11.0R Or -7L) PrintResult("-11.0R Or 28UL", -11.0R Or 28UL) PrintResult("-11.0R Or -9D", -11.0R Or -9D) PrintResult("-11.0R Or 10.0F", -11.0R Or 10.0F) PrintResult("-11.0R Or -11.0R", -11.0R Or -11.0R) PrintResult("-11.0R Or ""12""", -11.0R Or "12") PrintResult("-11.0R Or TypeCode.Double", -11.0R Or TypeCode.Double) PrintResult("""12"" Or False", "12" Or False) PrintResult("""12"" Or True", "12" Or True) PrintResult("""12"" Or System.SByte.MinValue", "12" Or System.SByte.MinValue) PrintResult("""12"" Or System.Byte.MaxValue", "12" Or System.Byte.MaxValue) PrintResult("""12"" Or -3S", "12" Or -3S) PrintResult("""12"" Or 24US", "12" Or 24US) PrintResult("""12"" Or -5I", "12" Or -5I) PrintResult("""12"" Or 26UI", "12" Or 26UI) PrintResult("""12"" Or -7L", "12" Or -7L) PrintResult("""12"" Or 28UL", "12" Or 28UL) PrintResult("""12"" Or -9D", "12" Or -9D) PrintResult("""12"" Or 10.0F", "12" Or 10.0F) PrintResult("""12"" Or -11.0R", "12" Or -11.0R) PrintResult("""12"" Or ""12""", "12" Or "12") PrintResult("""12"" Or TypeCode.Double", "12" Or TypeCode.Double) PrintResult("TypeCode.Double Or False", TypeCode.Double Or False) PrintResult("TypeCode.Double Or True", TypeCode.Double Or True) PrintResult("TypeCode.Double Or System.SByte.MinValue", TypeCode.Double Or System.SByte.MinValue) PrintResult("TypeCode.Double Or System.Byte.MaxValue", TypeCode.Double Or System.Byte.MaxValue) PrintResult("TypeCode.Double Or -3S", TypeCode.Double Or -3S) PrintResult("TypeCode.Double Or 24US", TypeCode.Double Or 24US) PrintResult("TypeCode.Double Or -5I", TypeCode.Double Or -5I) PrintResult("TypeCode.Double Or 26UI", TypeCode.Double Or 26UI) PrintResult("TypeCode.Double Or -7L", TypeCode.Double Or -7L) PrintResult("TypeCode.Double Or 28UL", TypeCode.Double Or 28UL) PrintResult("TypeCode.Double Or -9D", TypeCode.Double Or -9D) PrintResult("TypeCode.Double Or 10.0F", TypeCode.Double Or 10.0F) PrintResult("TypeCode.Double Or -11.0R", TypeCode.Double Or -11.0R) PrintResult("TypeCode.Double Or ""12""", TypeCode.Double Or "12") PrintResult("TypeCode.Double Or TypeCode.Double", TypeCode.Double Or TypeCode.Double) PrintResult("False And False", False And False) PrintResult("False And True", False And True) PrintResult("False And System.SByte.MinValue", False And System.SByte.MinValue) PrintResult("False And System.Byte.MaxValue", False And System.Byte.MaxValue) PrintResult("False And -3S", False And -3S) PrintResult("False And 24US", False And 24US) PrintResult("False And -5I", False And -5I) PrintResult("False And 26UI", False And 26UI) PrintResult("False And -7L", False And -7L) PrintResult("False And 28UL", False And 28UL) PrintResult("False And -9D", False And -9D) PrintResult("False And 10.0F", False And 10.0F) PrintResult("False And -11.0R", False And -11.0R) PrintResult("False And ""12""", False And "12") PrintResult("False And TypeCode.Double", False And TypeCode.Double) PrintResult("True And False", True And False) PrintResult("True And True", True And True) PrintResult("True And System.SByte.MinValue", True And System.SByte.MinValue) PrintResult("True And System.Byte.MaxValue", True And System.Byte.MaxValue) PrintResult("True And -3S", True And -3S) PrintResult("True And 24US", True And 24US) PrintResult("True And -5I", True And -5I) PrintResult("True And 26UI", True And 26UI) PrintResult("True And -7L", True And -7L) PrintResult("True And 28UL", True And 28UL) PrintResult("True And -9D", True And -9D) PrintResult("True And 10.0F", True And 10.0F) PrintResult("True And -11.0R", True And -11.0R) PrintResult("True And ""12""", True And "12") PrintResult("True And TypeCode.Double", True And TypeCode.Double) PrintResult("System.SByte.MinValue And False", System.SByte.MinValue And False) PrintResult("System.SByte.MinValue And True", System.SByte.MinValue And True) PrintResult("System.SByte.MinValue And System.SByte.MinValue", System.SByte.MinValue And System.SByte.MinValue) PrintResult("System.SByte.MinValue And System.Byte.MaxValue", System.SByte.MinValue And System.Byte.MaxValue) PrintResult("System.SByte.MinValue And -3S", System.SByte.MinValue And -3S) PrintResult("System.SByte.MinValue And 24US", System.SByte.MinValue And 24US) PrintResult("System.SByte.MinValue And -5I", System.SByte.MinValue And -5I) PrintResult("System.SByte.MinValue And 26UI", System.SByte.MinValue And 26UI) PrintResult("System.SByte.MinValue And -7L", System.SByte.MinValue And -7L) PrintResult("System.SByte.MinValue And 28UL", System.SByte.MinValue And 28UL) PrintResult("System.SByte.MinValue And -9D", System.SByte.MinValue And -9D) PrintResult("System.SByte.MinValue And 10.0F", System.SByte.MinValue And 10.0F) PrintResult("System.SByte.MinValue And -11.0R", System.SByte.MinValue And -11.0R) PrintResult("System.SByte.MinValue And ""12""", System.SByte.MinValue And "12") PrintResult("System.SByte.MinValue And TypeCode.Double", System.SByte.MinValue And TypeCode.Double) PrintResult("System.Byte.MaxValue And False", System.Byte.MaxValue And False) PrintResult("System.Byte.MaxValue And True", System.Byte.MaxValue And True) PrintResult("System.Byte.MaxValue And System.SByte.MinValue", System.Byte.MaxValue And System.SByte.MinValue) PrintResult("System.Byte.MaxValue And System.Byte.MaxValue", System.Byte.MaxValue And System.Byte.MaxValue) PrintResult("System.Byte.MaxValue And -3S", System.Byte.MaxValue And -3S) PrintResult("System.Byte.MaxValue And 24US", System.Byte.MaxValue And 24US) PrintResult("System.Byte.MaxValue And -5I", System.Byte.MaxValue And -5I) PrintResult("System.Byte.MaxValue And 26UI", System.Byte.MaxValue And 26UI) PrintResult("System.Byte.MaxValue And -7L", System.Byte.MaxValue And -7L) PrintResult("System.Byte.MaxValue And 28UL", System.Byte.MaxValue And 28UL) PrintResult("System.Byte.MaxValue And -9D", System.Byte.MaxValue And -9D) PrintResult("System.Byte.MaxValue And 10.0F", System.Byte.MaxValue And 10.0F) PrintResult("System.Byte.MaxValue And -11.0R", System.Byte.MaxValue And -11.0R) PrintResult("System.Byte.MaxValue And ""12""", System.Byte.MaxValue And "12") PrintResult("System.Byte.MaxValue And TypeCode.Double", System.Byte.MaxValue And TypeCode.Double) PrintResult("-3S And False", -3S And False) PrintResult("-3S And True", -3S And True) PrintResult("-3S And System.SByte.MinValue", -3S And System.SByte.MinValue) PrintResult("-3S And System.Byte.MaxValue", -3S And System.Byte.MaxValue) PrintResult("-3S And -3S", -3S And -3S) PrintResult("-3S And 24US", -3S And 24US) PrintResult("-3S And -5I", -3S And -5I) PrintResult("-3S And 26UI", -3S And 26UI) PrintResult("-3S And -7L", -3S And -7L) PrintResult("-3S And 28UL", -3S And 28UL) PrintResult("-3S And -9D", -3S And -9D) PrintResult("-3S And 10.0F", -3S And 10.0F) PrintResult("-3S And -11.0R", -3S And -11.0R) PrintResult("-3S And ""12""", -3S And "12") PrintResult("-3S And TypeCode.Double", -3S And TypeCode.Double) PrintResult("24US And False", 24US And False) PrintResult("24US And True", 24US And True) PrintResult("24US And System.SByte.MinValue", 24US And System.SByte.MinValue) PrintResult("24US And System.Byte.MaxValue", 24US And System.Byte.MaxValue) PrintResult("24US And -3S", 24US And -3S) PrintResult("24US And 24US", 24US And 24US) PrintResult("24US And -5I", 24US And -5I) PrintResult("24US And 26UI", 24US And 26UI) PrintResult("24US And -7L", 24US And -7L) PrintResult("24US And 28UL", 24US And 28UL) PrintResult("24US And -9D", 24US And -9D) PrintResult("24US And 10.0F", 24US And 10.0F) PrintResult("24US And -11.0R", 24US And -11.0R) PrintResult("24US And ""12""", 24US And "12") PrintResult("24US And TypeCode.Double", 24US And TypeCode.Double) PrintResult("-5I And False", -5I And False) PrintResult("-5I And True", -5I And True) PrintResult("-5I And System.SByte.MinValue", -5I And System.SByte.MinValue) PrintResult("-5I And System.Byte.MaxValue", -5I And System.Byte.MaxValue) PrintResult("-5I And -3S", -5I And -3S) PrintResult("-5I And 24US", -5I And 24US) PrintResult("-5I And -5I", -5I And -5I) PrintResult("-5I And 26UI", -5I And 26UI) PrintResult("-5I And -7L", -5I And -7L) PrintResult("-5I And 28UL", -5I And 28UL) PrintResult("-5I And -9D", -5I And -9D) PrintResult("-5I And 10.0F", -5I And 10.0F) PrintResult("-5I And -11.0R", -5I And -11.0R) PrintResult("-5I And ""12""", -5I And "12") PrintResult("-5I And TypeCode.Double", -5I And TypeCode.Double) PrintResult("26UI And False", 26UI And False) PrintResult("26UI And True", 26UI And True) PrintResult("26UI And System.SByte.MinValue", 26UI And System.SByte.MinValue) PrintResult("26UI And System.Byte.MaxValue", 26UI And System.Byte.MaxValue) PrintResult("26UI And -3S", 26UI And -3S) PrintResult("26UI And 24US", 26UI And 24US) PrintResult("26UI And -5I", 26UI And -5I) PrintResult("26UI And 26UI", 26UI And 26UI) PrintResult("26UI And -7L", 26UI And -7L) PrintResult("26UI And 28UL", 26UI And 28UL) PrintResult("26UI And -9D", 26UI And -9D) PrintResult("26UI And 10.0F", 26UI And 10.0F) PrintResult("26UI And -11.0R", 26UI And -11.0R) PrintResult("26UI And ""12""", 26UI And "12") PrintResult("26UI And TypeCode.Double", 26UI And TypeCode.Double) PrintResult("-7L And False", -7L And False) PrintResult("-7L And True", -7L And True) PrintResult("-7L And System.SByte.MinValue", -7L And System.SByte.MinValue) PrintResult("-7L And System.Byte.MaxValue", -7L And System.Byte.MaxValue) PrintResult("-7L And -3S", -7L And -3S) PrintResult("-7L And 24US", -7L And 24US) PrintResult("-7L And -5I", -7L And -5I) PrintResult("-7L And 26UI", -7L And 26UI) PrintResult("-7L And -7L", -7L And -7L) PrintResult("-7L And 28UL", -7L And 28UL) PrintResult("-7L And -9D", -7L And -9D) PrintResult("-7L And 10.0F", -7L And 10.0F) PrintResult("-7L And -11.0R", -7L And -11.0R) PrintResult("-7L And ""12""", -7L And "12") PrintResult("-7L And TypeCode.Double", -7L And TypeCode.Double) PrintResult("28UL And False", 28UL And False) PrintResult("28UL And True", 28UL And True) PrintResult("28UL And System.SByte.MinValue", 28UL And System.SByte.MinValue) PrintResult("28UL And System.Byte.MaxValue", 28UL And System.Byte.MaxValue) PrintResult("28UL And -3S", 28UL And -3S) PrintResult("28UL And 24US", 28UL And 24US) PrintResult("28UL And -5I", 28UL And -5I) PrintResult("28UL And 26UI", 28UL And 26UI) PrintResult("28UL And -7L", 28UL And -7L) PrintResult("28UL And 28UL", 28UL And 28UL) PrintResult("28UL And -9D", 28UL And -9D) PrintResult("28UL And 10.0F", 28UL And 10.0F) PrintResult("28UL And -11.0R", 28UL And -11.0R) PrintResult("28UL And ""12""", 28UL And "12") PrintResult("28UL And TypeCode.Double", 28UL And TypeCode.Double) PrintResult("-9D And False", -9D And False) PrintResult("-9D And True", -9D And True) PrintResult("-9D And System.SByte.MinValue", -9D And System.SByte.MinValue) PrintResult("-9D And System.Byte.MaxValue", -9D And System.Byte.MaxValue) PrintResult("-9D And -3S", -9D And -3S) PrintResult("-9D And 24US", -9D And 24US) PrintResult("-9D And -5I", -9D And -5I) PrintResult("-9D And 26UI", -9D And 26UI) PrintResult("-9D And -7L", -9D And -7L) PrintResult("-9D And 28UL", -9D And 28UL) PrintResult("-9D And -9D", -9D And -9D) PrintResult("-9D And 10.0F", -9D And 10.0F) PrintResult("-9D And -11.0R", -9D And -11.0R) PrintResult("-9D And ""12""", -9D And "12") PrintResult("-9D And TypeCode.Double", -9D And TypeCode.Double) PrintResult("10.0F And False", 10.0F And False) PrintResult("10.0F And True", 10.0F And True) PrintResult("10.0F And System.SByte.MinValue", 10.0F And System.SByte.MinValue) PrintResult("10.0F And System.Byte.MaxValue", 10.0F And System.Byte.MaxValue) PrintResult("10.0F And -3S", 10.0F And -3S) PrintResult("10.0F And 24US", 10.0F And 24US) PrintResult("10.0F And -5I", 10.0F And -5I) PrintResult("10.0F And 26UI", 10.0F And 26UI) PrintResult("10.0F And -7L", 10.0F And -7L) PrintResult("10.0F And 28UL", 10.0F And 28UL) PrintResult("10.0F And -9D", 10.0F And -9D) PrintResult("10.0F And 10.0F", 10.0F And 10.0F) PrintResult("10.0F And -11.0R", 10.0F And -11.0R) PrintResult("10.0F And ""12""", 10.0F And "12") PrintResult("10.0F And TypeCode.Double", 10.0F And TypeCode.Double) PrintResult("-11.0R And False", -11.0R And False) PrintResult("-11.0R And True", -11.0R And True) PrintResult("-11.0R And System.SByte.MinValue", -11.0R And System.SByte.MinValue) PrintResult("-11.0R And System.Byte.MaxValue", -11.0R And System.Byte.MaxValue) PrintResult("-11.0R And -3S", -11.0R And -3S) PrintResult("-11.0R And 24US", -11.0R And 24US) PrintResult("-11.0R And -5I", -11.0R And -5I) PrintResult("-11.0R And 26UI", -11.0R And 26UI) PrintResult("-11.0R And -7L", -11.0R And -7L) PrintResult("-11.0R And 28UL", -11.0R And 28UL) PrintResult("-11.0R And -9D", -11.0R And -9D) PrintResult("-11.0R And 10.0F", -11.0R And 10.0F) PrintResult("-11.0R And -11.0R", -11.0R And -11.0R) PrintResult("-11.0R And ""12""", -11.0R And "12") PrintResult("-11.0R And TypeCode.Double", -11.0R And TypeCode.Double) PrintResult("""12"" And False", "12" And False) PrintResult("""12"" And True", "12" And True) PrintResult("""12"" And System.SByte.MinValue", "12" And System.SByte.MinValue) PrintResult("""12"" And System.Byte.MaxValue", "12" And System.Byte.MaxValue) PrintResult("""12"" And -3S", "12" And -3S) PrintResult("""12"" And 24US", "12" And 24US) PrintResult("""12"" And -5I", "12" And -5I) PrintResult("""12"" And 26UI", "12" And 26UI) PrintResult("""12"" And -7L", "12" And -7L) PrintResult("""12"" And 28UL", "12" And 28UL) PrintResult("""12"" And -9D", "12" And -9D) PrintResult("""12"" And 10.0F", "12" And 10.0F) PrintResult("""12"" And -11.0R", "12" And -11.0R) PrintResult("""12"" And ""12""", "12" And "12") PrintResult("""12"" And TypeCode.Double", "12" And TypeCode.Double) PrintResult("TypeCode.Double And False", TypeCode.Double And False) PrintResult("TypeCode.Double And True", TypeCode.Double And True) PrintResult("TypeCode.Double And System.SByte.MinValue", TypeCode.Double And System.SByte.MinValue) PrintResult("TypeCode.Double And System.Byte.MaxValue", TypeCode.Double And System.Byte.MaxValue) PrintResult("TypeCode.Double And -3S", TypeCode.Double And -3S) PrintResult("TypeCode.Double And 24US", TypeCode.Double And 24US) PrintResult("TypeCode.Double And -5I", TypeCode.Double And -5I) PrintResult("TypeCode.Double And 26UI", TypeCode.Double And 26UI) PrintResult("TypeCode.Double And -7L", TypeCode.Double And -7L) PrintResult("TypeCode.Double And 28UL", TypeCode.Double And 28UL) PrintResult("TypeCode.Double And -9D", TypeCode.Double And -9D) PrintResult("TypeCode.Double And 10.0F", TypeCode.Double And 10.0F) PrintResult("TypeCode.Double And -11.0R", TypeCode.Double And -11.0R) PrintResult("TypeCode.Double And ""12""", TypeCode.Double And "12") PrintResult("TypeCode.Double And TypeCode.Double", TypeCode.Double And TypeCode.Double) 'PrintResult("#8:30:00 AM# + ""12""", #8:30:00 AM# + "12") 'PrintResult("#8:30:00 AM# + #8:30:00 AM#", #8:30:00 AM# + #8:30:00 AM#) PrintResult("""c""c + ""12""", "c"c + "12") PrintResult("""c""c + ""c""c", "c"c + "c"c) 'PrintResult("""12"" + #8:30:00 AM#", "12" + #8:30:00 AM#) PrintResult("""12"" + ""c""c", "12" + "c"c) 'PrintResult("#8:30:00 AM# & False", #8:30:00 AM# & False) 'PrintResult("#8:30:00 AM# & True", #8:30:00 AM# & True) 'PrintResult("#8:30:00 AM# & System.SByte.MinValue", #8:30:00 AM# & System.SByte.MinValue) 'PrintResult("#8:30:00 AM# & System.Byte.MaxValue", #8:30:00 AM# & System.Byte.MaxValue) 'PrintResult("#8:30:00 AM# & -3S", #8:30:00 AM# & -3S) 'PrintResult("#8:30:00 AM# & 24US", #8:30:00 AM# & 24US) 'PrintResult("#8:30:00 AM# & -5I", #8:30:00 AM# & -5I) 'PrintResult("#8:30:00 AM# & 26UI", #8:30:00 AM# & 26UI) 'PrintResult("#8:30:00 AM# & -7L", #8:30:00 AM# & -7L) 'PrintResult("#8:30:00 AM# & 28UL", #8:30:00 AM# & 28UL) 'PrintResult("#8:30:00 AM# & -9D", #8:30:00 AM# & -9D) 'PrintResult("#8:30:00 AM# & 10.0F", #8:30:00 AM# & 10.0F) 'PrintResult("#8:30:00 AM# & -11.0R", #8:30:00 AM# & -11.0R) 'PrintResult("#8:30:00 AM# & ""12""", #8:30:00 AM# & "12") 'PrintResult("#8:30:00 AM# & TypeCode.Double", #8:30:00 AM# & TypeCode.Double) 'PrintResult("#8:30:00 AM# & #8:30:00 AM#", #8:30:00 AM# & #8:30:00 AM#) 'PrintResult("#8:30:00 AM# & ""c""c", #8:30:00 AM# & "c"c) PrintResult("""c""c & False", "c"c & False) PrintResult("""c""c & True", "c"c & True) PrintResult("""c""c & System.SByte.MinValue", "c"c & System.SByte.MinValue) PrintResult("""c""c & System.Byte.MaxValue", "c"c & System.Byte.MaxValue) PrintResult("""c""c & -3S", "c"c & -3S) PrintResult("""c""c & 24US", "c"c & 24US) PrintResult("""c""c & -5I", "c"c & -5I) PrintResult("""c""c & 26UI", "c"c & 26UI) PrintResult("""c""c & -7L", "c"c & -7L) PrintResult("""c""c & 28UL", "c"c & 28UL) PrintResult("""c""c & -9D", "c"c & -9D) PrintResult("""c""c & 10.0F", "c"c & 10.0F) PrintResult("""c""c & -11.0R", "c"c & -11.0R) PrintResult("""c""c & ""12""", "c"c & "12") PrintResult("""c""c & TypeCode.Double", "c"c & TypeCode.Double) 'PrintResult("""c""c & #8:30:00 AM#", "c"c & #8:30:00 AM#) PrintResult("""c""c & ""c""c", "c"c & "c"c) 'PrintResult("False & #8:30:00 AM#", False & #8:30:00 AM#) PrintResult("False & ""c""c", False & "c"c) 'PrintResult("True & #8:30:00 AM#", True & #8:30:00 AM#) PrintResult("True & ""c""c", True & "c"c) 'PrintResult("System.SByte.MinValue & #8:30:00 AM#", System.SByte.MinValue & #8:30:00 AM#) PrintResult("System.SByte.MinValue & ""c""c", System.SByte.MinValue & "c"c) 'PrintResult("System.Byte.MaxValue & #8:30:00 AM#", System.Byte.MaxValue & #8:30:00 AM#) PrintResult("System.Byte.MaxValue & ""c""c", System.Byte.MaxValue & "c"c) 'PrintResult("-3S & #8:30:00 AM#", -3S & #8:30:00 AM#) PrintResult("-3S & ""c""c", -3S & "c"c) 'PrintResult("24US & #8:30:00 AM#", 24US & #8:30:00 AM#) PrintResult("24US & ""c""c", 24US & "c"c) 'PrintResult("-5I & #8:30:00 AM#", -5I & #8:30:00 AM#) PrintResult("-5I & ""c""c", -5I & "c"c) 'PrintResult("26UI & #8:30:00 AM#", 26UI & #8:30:00 AM#) PrintResult("26UI & ""c""c", 26UI & "c"c) 'PrintResult("-7L & #8:30:00 AM#", -7L & #8:30:00 AM#) PrintResult("-7L & ""c""c", -7L & "c"c) 'PrintResult("28UL & #8:30:00 AM#", 28UL & #8:30:00 AM#) PrintResult("28UL & ""c""c", 28UL & "c"c) 'PrintResult("-9D & #8:30:00 AM#", -9D & #8:30:00 AM#) PrintResult("-9D & ""c""c", -9D & "c"c) 'PrintResult("10.0F & #8:30:00 AM#", 10.0F & #8:30:00 AM#) PrintResult("10.0F & ""c""c", 10.0F & "c"c) 'PrintResult("-11.0R & #8:30:00 AM#", -11.0R & #8:30:00 AM#) PrintResult("-11.0R & ""c""c", -11.0R & "c"c) 'PrintResult("""12"" & #8:30:00 AM#", "12" & #8:30:00 AM#) PrintResult("""12"" & ""c""c", "12" & "c"c) 'PrintResult("TypeCode.Double & #8:30:00 AM#", TypeCode.Double & #8:30:00 AM#) PrintResult("TypeCode.Double & ""c""c", TypeCode.Double & "c"c) PrintResult("#8:30:00 AM# Like False", #8:30:00 AM# Like False) PrintResult("#8:30:00 AM# Like True", #8:30:00 AM# Like True) PrintResult("#8:30:00 AM# Like System.SByte.MinValue", #8:30:00 AM# Like System.SByte.MinValue) PrintResult("#8:30:00 AM# Like System.Byte.MaxValue", #8:30:00 AM# Like System.Byte.MaxValue) PrintResult("#8:30:00 AM# Like -3S", #8:30:00 AM# Like -3S) PrintResult("#8:30:00 AM# Like 24US", #8:30:00 AM# Like 24US) PrintResult("#8:30:00 AM# Like -5I", #8:30:00 AM# Like -5I) PrintResult("#8:30:00 AM# Like 26UI", #8:30:00 AM# Like 26UI) PrintResult("#8:30:00 AM# Like -7L", #8:30:00 AM# Like -7L) PrintResult("#8:30:00 AM# Like 28UL", #8:30:00 AM# Like 28UL) PrintResult("#8:30:00 AM# Like -9D", #8:30:00 AM# Like -9D) PrintResult("#8:30:00 AM# Like 10.0F", #8:30:00 AM# Like 10.0F) PrintResult("#8:30:00 AM# Like -11.0R", #8:30:00 AM# Like -11.0R) PrintResult("#8:30:00 AM# Like ""12""", #8:30:00 AM# Like "12") PrintResult("#8:30:00 AM# Like TypeCode.Double", #8:30:00 AM# Like TypeCode.Double) PrintResult("#8:30:00 AM# Like #8:30:00 AM#", #8:30:00 AM# Like #8:30:00 AM#) PrintResult("#8:30:00 AM# Like ""c""c", #8:30:00 AM# Like "c"c) PrintResult("""c""c Like False", "c"c Like False) PrintResult("""c""c Like True", "c"c Like True) PrintResult("""c""c Like System.SByte.MinValue", "c"c Like System.SByte.MinValue) PrintResult("""c""c Like System.Byte.MaxValue", "c"c Like System.Byte.MaxValue) PrintResult("""c""c Like -3S", "c"c Like -3S) PrintResult("""c""c Like 24US", "c"c Like 24US) PrintResult("""c""c Like -5I", "c"c Like -5I) PrintResult("""c""c Like 26UI", "c"c Like 26UI) PrintResult("""c""c Like -7L", "c"c Like -7L) PrintResult("""c""c Like 28UL", "c"c Like 28UL) PrintResult("""c""c Like -9D", "c"c Like -9D) PrintResult("""c""c Like 10.0F", "c"c Like 10.0F) PrintResult("""c""c Like -11.0R", "c"c Like -11.0R) PrintResult("""c""c Like ""12""", "c"c Like "12") PrintResult("""c""c Like TypeCode.Double", "c"c Like TypeCode.Double) PrintResult("""c""c Like #8:30:00 AM#", "c"c Like #8:30:00 AM#) PrintResult("""c""c Like ""c""c", "c"c Like "c"c) PrintResult("False Like #8:30:00 AM#", False Like #8:30:00 AM#) PrintResult("False Like ""c""c", False Like "c"c) PrintResult("True Like #8:30:00 AM#", True Like #8:30:00 AM#) PrintResult("True Like ""c""c", True Like "c"c) PrintResult("System.SByte.MinValue Like #8:30:00 AM#", System.SByte.MinValue Like #8:30:00 AM#) PrintResult("System.SByte.MinValue Like ""c""c", System.SByte.MinValue Like "c"c) PrintResult("System.Byte.MaxValue Like #8:30:00 AM#", System.Byte.MaxValue Like #8:30:00 AM#) PrintResult("System.Byte.MaxValue Like ""c""c", System.Byte.MaxValue Like "c"c) PrintResult("-3S Like #8:30:00 AM#", -3S Like #8:30:00 AM#) PrintResult("-3S Like ""c""c", -3S Like "c"c) PrintResult("24US Like #8:30:00 AM#", 24US Like #8:30:00 AM#) PrintResult("24US Like ""c""c", 24US Like "c"c) PrintResult("-5I Like #8:30:00 AM#", -5I Like #8:30:00 AM#) PrintResult("-5I Like ""c""c", -5I Like "c"c) PrintResult("26UI Like #8:30:00 AM#", 26UI Like #8:30:00 AM#) PrintResult("26UI Like ""c""c", 26UI Like "c"c) PrintResult("-7L Like #8:30:00 AM#", -7L Like #8:30:00 AM#) PrintResult("-7L Like ""c""c", -7L Like "c"c) PrintResult("28UL Like #8:30:00 AM#", 28UL Like #8:30:00 AM#) PrintResult("28UL Like ""c""c", 28UL Like "c"c) PrintResult("-9D Like #8:30:00 AM#", -9D Like #8:30:00 AM#) PrintResult("-9D Like ""c""c", -9D Like "c"c) PrintResult("10.0F Like #8:30:00 AM#", 10.0F Like #8:30:00 AM#) PrintResult("10.0F Like ""c""c", 10.0F Like "c"c) PrintResult("-11.0R Like #8:30:00 AM#", -11.0R Like #8:30:00 AM#) PrintResult("-11.0R Like ""c""c", -11.0R Like "c"c) PrintResult("""12"" Like #8:30:00 AM#", "12" Like #8:30:00 AM#) PrintResult("""12"" Like ""c""c", "12" Like "c"c) PrintResult("TypeCode.Double Like #8:30:00 AM#", TypeCode.Double Like #8:30:00 AM#) PrintResult("TypeCode.Double Like ""c""c", TypeCode.Double Like "c"c) PrintResult("#8:30:00 AM# = #8:30:00 AM#", #8:30:00 AM# = #8:30:00 AM#) PrintResult("""c""c = ""12""", "c"c = "12") PrintResult("""c""c = ""c""c", "c"c = "c"c) PrintResult("""12"" = ""c""c", "12" = "c"c) PrintResult("#8:30:00 AM# <> #8:30:00 AM#", #8:30:00 AM# <> #8:30:00 AM#) PrintResult("""c""c <> ""12""", "c"c <> "12") PrintResult("""c""c <> ""c""c", "c"c <> "c"c) PrintResult("""12"" <> ""c""c", "12" <> "c"c) PrintResult("#8:30:00 AM# <= #8:30:00 AM#", #8:30:00 AM# <= #8:30:00 AM#) PrintResult("""c""c <= ""12""", "c"c <= "12") PrintResult("""c""c <= ""c""c", "c"c <= "c"c) PrintResult("""12"" <= ""c""c", "12" <= "c"c) PrintResult("#8:30:00 AM# >= #8:30:00 AM#", #8:30:00 AM# >= #8:30:00 AM#) PrintResult("""c""c >= ""12""", "c"c >= "12") PrintResult("""c""c >= ""c""c", "c"c >= "c"c) PrintResult("""12"" >= ""c""c", "12" >= "c"c) PrintResult("#8:30:00 AM# < #8:30:00 AM#", #8:30:00 AM# < #8:30:00 AM#) PrintResult("""c""c < ""12""", "c"c < "12") PrintResult("""c""c < ""c""c", "c"c < "c"c) PrintResult("""12"" < ""c""c", "12" < "c"c) PrintResult("#8:30:00 AM# > #8:30:00 AM#", #8:30:00 AM# > #8:30:00 AM#) PrintResult("""c""c > ""12""", "c"c > "12") PrintResult("""c""c > ""c""c", "c"c > "c"c) PrintResult("""12"" > ""c""c", "12" > "c"c) PrintResult("System.Byte.MaxValue - 24US", System.Byte.MaxValue - 24US) PrintResult("System.Byte.MaxValue - 26UI", System.Byte.MaxValue - 26UI) PrintResult("System.Byte.MaxValue - 28UL", System.Byte.MaxValue - 28UL) PrintResult("44US - 26UI", 44US - 26UI) PrintResult("44US - 28UL", 44US - 28UL) PrintResult("46UI - 28UL", 46UI - 28UL) PrintResult("System.Byte.MaxValue * (System.Byte.MaxValue \ System.Byte.MaxValue)", System.Byte.MaxValue * (System.Byte.MaxValue \ System.Byte.MaxValue)) PrintResult("#8:31:00 AM# = ""8:30:00 AM""", #8:31:00 AM# = "8:30:00 AM") PrintResult("""8:30:00 AM"" = #8:31:00 AM#", "8:30:00 AM" = #8:31:00 AM#) PrintResult("#8:31:00 AM# <> ""8:30:00 AM""", #8:31:00 AM# <> "8:30:00 AM") PrintResult("""8:30:00 AM"" <> #8:31:00 AM#", "8:30:00 AM" <> #8:31:00 AM#) PrintResult("#8:31:00 AM# <= ""8:30:00 AM""", #8:31:00 AM# <= "8:30:00 AM") PrintResult("""8:30:00 AM"" <= #8:31:00 AM#", "8:30:00 AM" <= #8:31:00 AM#) PrintResult("#8:31:00 AM# >= ""8:30:00 AM""", #8:31:00 AM# >= "8:30:00 AM") PrintResult("""8:30:00 AM"" >= #8:31:00 AM#", "8:30:00 AM" >= #8:31:00 AM#) PrintResult("#8:31:00 AM# < ""8:30:00 AM""", #8:31:00 AM# < "8:30:00 AM") PrintResult("""8:30:00 AM"" < #8:31:00 AM#", "8:30:00 AM" < #8:31:00 AM#) PrintResult("#8:31:00 AM# > ""8:30:00 AM""", #8:31:00 AM# > "8:30:00 AM") PrintResult("""8:30:00 AM"" > #8:31:00 AM#", "8:30:00 AM" > #8:31:00 AM#) PrintResult("-5I + Nothing", -5I + Nothing) PrintResult("""12"" + Nothing", "12" + Nothing) PrintResult("""12"" + DBNull.Value", "12" + DBNull.Value) PrintResult("Nothing + Nothing", Nothing + Nothing) PrintResult("Nothing + -5I", Nothing + -5I) PrintResult("Nothing + ""12""", Nothing + "12") PrintResult("DBNull.Value + ""12""", DBNull.Value + "12") PrintResult("-5I - Nothing", -5I - Nothing) PrintResult("""12"" - Nothing", "12" - Nothing) PrintResult("Nothing - Nothing", Nothing - Nothing) PrintResult("Nothing - -5I", Nothing - -5I) PrintResult("Nothing - ""12""", Nothing - "12") PrintResult("-5I * Nothing", -5I * Nothing) PrintResult("""12"" * Nothing", "12" * Nothing) PrintResult("Nothing * Nothing", Nothing * Nothing) PrintResult("Nothing * -5I", Nothing * -5I) PrintResult("Nothing * ""12""", Nothing * "12") PrintResult("-5I / Nothing", -5I / Nothing) PrintResult("""12"" / Nothing", "12" / Nothing) PrintResult("Nothing / Nothing", Nothing / Nothing) PrintResult("Nothing / -5I", Nothing / -5I) PrintResult("Nothing / ""12""", Nothing / "12") PrintResult("Nothing \ -5I", Nothing \ -5I) PrintResult("Nothing \ ""12""", Nothing \ "12") PrintResult("""12"" Mod Nothing", "12" Mod Nothing) PrintResult("Nothing Mod -5I", Nothing Mod -5I) PrintResult("Nothing Mod ""12""", Nothing Mod "12") PrintResult("-5I ^ Nothing", -5I ^ Nothing) PrintResult("""12"" ^ Nothing", "12" ^ Nothing) PrintResult("Nothing ^ Nothing", Nothing ^ Nothing) PrintResult("Nothing ^ -5I", Nothing ^ -5I) PrintResult("Nothing ^ ""12""", Nothing ^ "12") PrintResult("-5I << Nothing", -5I << Nothing) PrintResult("""12"" << Nothing", "12" << Nothing) PrintResult("Nothing << Nothing", Nothing << Nothing) PrintResult("Nothing << -5I", Nothing << -5I) PrintResult("Nothing << ""12""", Nothing << "12") PrintResult("-5I >> Nothing", -5I >> Nothing) PrintResult("""12"" >> Nothing", "12" >> Nothing) PrintResult("Nothing >> Nothing", Nothing >> Nothing) PrintResult("Nothing >> -5I", Nothing >> -5I) PrintResult("Nothing >> ""12""", Nothing >> "12") PrintResult("-5I OrElse Nothing", -5I OrElse Nothing) PrintResult("""12"" OrElse Nothing", "12" OrElse Nothing) PrintResult("Nothing OrElse Nothing", Nothing OrElse Nothing) PrintResult("Nothing OrElse -5I", Nothing OrElse -5I) PrintResult("-5I AndAlso Nothing", -5I AndAlso Nothing) PrintResult("Nothing AndAlso Nothing", Nothing AndAlso Nothing) PrintResult("Nothing AndAlso -5I", Nothing AndAlso -5I) PrintResult("-5I & Nothing", -5I & Nothing) PrintResult("-5I & DBNull.Value", -5I & DBNull.Value) PrintResult("""12"" & Nothing", "12" & Nothing) PrintResult("""12"" & DBNull.Value", "12" & DBNull.Value) PrintResult("Nothing & Nothing", Nothing & Nothing) PrintResult("Nothing & DBNull.Value", Nothing & DBNull.Value) PrintResult("DBNull.Value & Nothing", DBNull.Value & Nothing) PrintResult("Nothing & -5I", Nothing & -5I) PrintResult("Nothing & ""12""", Nothing & "12") PrintResult("DBNull.Value & -5I", DBNull.Value & -5I) PrintResult("DBNull.Value & ""12""", DBNull.Value & "12") PrintResult("-5I Like Nothing", -5I Like Nothing) PrintResult("""12"" Like Nothing", "12" Like Nothing) PrintResult("Nothing Like Nothing", Nothing Like Nothing) PrintResult("Nothing Like -5I", Nothing Like -5I) PrintResult("Nothing Like ""12""", Nothing Like "12") PrintResult("-5I = Nothing", -5I = Nothing) PrintResult("""12"" = Nothing", "12" = Nothing) PrintResult("Nothing = Nothing", Nothing = Nothing) PrintResult("Nothing = -5I", Nothing = -5I) PrintResult("Nothing = ""12""", Nothing = "12") PrintResult("-5I <> Nothing", -5I <> Nothing) PrintResult("""12"" <> Nothing", "12" <> Nothing) PrintResult("Nothing <> Nothing", Nothing <> Nothing) PrintResult("Nothing <> -5I", Nothing <> -5I) PrintResult("Nothing <> ""12""", Nothing <> "12") PrintResult("-5I <= Nothing", -5I <= Nothing) PrintResult("""12"" <= Nothing", "12" <= Nothing) PrintResult("Nothing <= Nothing", Nothing <= Nothing) PrintResult("Nothing <= -5I", Nothing <= -5I) PrintResult("Nothing <= ""12""", Nothing <= "12") PrintResult("-5I >= Nothing", -5I >= Nothing) PrintResult("""12"" >= Nothing", "12" >= Nothing) PrintResult("Nothing >= Nothing", Nothing >= Nothing) PrintResult("Nothing >= -5I", Nothing >= -5I) PrintResult("Nothing >= ""12""", Nothing >= "12") PrintResult("-5I < Nothing", -5I < Nothing) PrintResult("""12"" < Nothing", "12" < Nothing) PrintResult("Nothing < Nothing", Nothing < Nothing) PrintResult("Nothing < -5I", Nothing < -5I) PrintResult("Nothing < ""12""", Nothing < "12") PrintResult("-5I > Nothing", -5I > Nothing) PrintResult("""12"" > Nothing", "12" > Nothing) PrintResult("Nothing > Nothing", Nothing > Nothing) PrintResult("Nothing > -5I", Nothing > -5I) PrintResult("Nothing > ""12""", Nothing > "12") PrintResult("-5I Xor Nothing", -5I Xor Nothing) PrintResult("""12"" Xor Nothing", "12" Xor Nothing) PrintResult("Nothing Xor Nothing", Nothing Xor Nothing) PrintResult("Nothing Xor -5I", Nothing Xor -5I) PrintResult("Nothing Xor ""12""", Nothing Xor "12") PrintResult("-5I Or Nothing", -5I Or Nothing) PrintResult("""12"" Or Nothing", "12" Or Nothing) PrintResult("Nothing Or Nothing", Nothing Or Nothing) PrintResult("Nothing Or -5I", Nothing Or -5I) PrintResult("Nothing Or ""12""", Nothing Or "12") PrintResult("-5I And Nothing", -5I And Nothing) PrintResult("""12"" And Nothing", "12" And Nothing) PrintResult("Nothing And Nothing", Nothing And Nothing) PrintResult("Nothing And -5I", Nothing And -5I) PrintResult("Nothing And ""12""", Nothing And "12") PrintResult("2I / 0", 2I / 0) PrintResult("1.5F / 0", 1.5F / 0) PrintResult("2.5R / 0", 2.5R / 0) PrintResult("1.5F Mod 0", 1.5F Mod 0) PrintResult("2.5R Mod 0", 2.5R Mod 0) PrintResult("2I / 0", 2I / Nothing) PrintResult("1.5F / 0", 1.5F / Nothing) PrintResult("2.5R / 0", 2.5R / Nothing) PrintResult("1.5F Mod 0", 1.5F Mod Nothing) PrintResult("2.5R Mod 0", 2.5R Mod Nothing) PrintResult("System.Single.MinValue - 1.0F", System.Single.MinValue - 1.0F) PrintResult("System.Double.MinValue - 1.0R", System.Double.MinValue - 1.0R) PrintResult("System.Single.MaxValue + 1.0F", System.Single.MaxValue + 1.0F) PrintResult("System.Double.MaxValue + 1.0R", System.Double.MaxValue + 1.0R) PrintResult("1.0F ^ System.Single.NegativeInfinity", 1.0F ^ System.Single.NegativeInfinity) PrintResult("1.0F ^ System.Single.PositiveInfinity", 1.0F ^ System.Single.PositiveInfinity) PrintResult("1.0R ^ System.Double.NegativeInfinity", 1.0R ^ System.Double.NegativeInfinity) PrintResult("1.0R ^ System.Double.PositiveInfinity", 1.0R ^ System.Double.PositiveInfinity) PrintResult("-1.0F ^ System.Single.NegativeInfinity", -1.0F ^ System.Single.NegativeInfinity) PrintResult("-1.0F ^ System.Single.PositiveInfinity", -1.0F ^ System.Single.PositiveInfinity) PrintResult("-1.0R ^ System.Double.NegativeInfinity", -1.0R ^ System.Double.NegativeInfinity) PrintResult("-1.0R ^ System.Double.PositiveInfinity", -1.0R ^ System.Double.PositiveInfinity) PrintResult("2.0F ^ System.Single.NaN", 2.0F ^ System.Single.NaN) PrintResult("2.0R ^ System.Double.NaN", 2.0R ^ System.Double.NaN) PrintResult("(-1.0F) ^ System.Single.NegativeInfinity", (-1.0F) ^ System.Single.NegativeInfinity) PrintResult("(-1.0F) ^ System.Single.PositiveInfinity", (-1.0F) ^ System.Single.PositiveInfinity) PrintResult("(-1.0F) ^ System.Double.NegativeInfinity", (-1.0F) ^ System.Double.NegativeInfinity) PrintResult("(-1.0F) ^ System.Double.PositiveInfinity", (-1.0F) ^ System.Double.PositiveInfinity) End Sub End Module
-1
dotnet/roslyn
56,278
Add documents to PDB for types that have no methods with IL
Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
davidwengier
"2021-09-09T01:55:39Z"
"2021-09-27T10:25:49Z"
09c9db28fc79823152a73b654f6521dc4b6dfa16
40cfa4b8ff85eb0c37622fca8bdafb97521168f8
Add documents to PDB for types that have no methods with IL. Part of https://github.com/dotnet/roslyn/issues/55834 First two commits are from Samuel, subsequent is my cleanup/changes, but easiest to just look at the entire changeset as one.
./src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicPackage.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options.Formatting Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.Interop Imports Task = System.Threading.Tasks.Task Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic ' The option page configuration is duplicated in PackageRegistration.pkgdef. ' ' VB option pages tree ' Basic ' General (from editor) ' Scroll Bars (from editor) ' Tabs (from editor) ' Advanced ' Code Style (category) ' General <ProvideLanguageEditorOptionPage(GetType(AdvancedOptionPage), "Basic", Nothing, "Advanced", "#102", 10160)> <ProvideLanguageEditorToolsOptionCategory("Basic", "Code Style", "#109")> <ProvideLanguageEditorOptionPage(GetType(CodeStylePage), "Basic", "Code Style", "General", "#111", 10161)> <ProvideLanguageEditorOptionPage(GetType(NamingStylesOptionPage), "Basic", "Code Style", "Naming", "#110", 10162)> <ProvideLanguageEditorOptionPage(GetType(IntelliSenseOptionPage), "Basic", Nothing, "IntelliSense", "#112", 312)> <Guid(Guids.VisualBasicPackageIdString)> Friend NotInheritable Class VisualBasicPackage Inherits AbstractPackage(Of VisualBasicPackage, VisualBasicLanguageService) Implements IVbCompilerService Implements IVsUserSettingsQuery ' The property page for WinForms project has a special interface that it uses to get ' entry points that are Forms: IVbEntryPointProvider. The semantics for this ' interface are the same as VisualBasicProject::GetFormEntryPoints, but callers get ' the VB Package and cast it to IVbEntryPointProvider. The property page is managed ' and we've redefined the interface, so we have to register a COM aggregate of the ' VB package. This is the same pattern we use for the LanguageService and Razor. Private ReadOnly _comAggregate As Object Private _libraryManager As ObjectBrowserLibraryManager Private _libraryManagerCookie As UInteger Public Sub New() MyBase.New() _comAggregate = Interop.ComAggregate.CreateAggregatedObject(Me) End Sub Protected Overrides Async Function InitializeAsync(cancellationToken As CancellationToken, progress As IProgress(Of ServiceProgressData)) As Task Try Await MyBase.InitializeAsync(cancellationToken, progress).ConfigureAwait(True) Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) RegisterLanguageService(GetType(IVbCompilerService), Function() Task.FromResult(_comAggregate)) RegisterService(Of IVbTempPECompilerFactory)( Async Function(ct) Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(ct) Return New TempPECompilerFactory(workspace) End Function) Catch ex As Exception When FatalError.ReportAndPropagateUnlessCanceled(ex) Throw ExceptionUtilities.Unreachable End Try End Function Protected Overrides Async Function RegisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Dim workspace As VisualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then Me._libraryManager = New ObjectBrowserLibraryManager(Me, ComponentModel, workspace) If ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(Me._libraryManager, Me._libraryManagerCookie)) Then Me._libraryManagerCookie = 0 End If End If End Function Protected Overrides Async Function UnregisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) If _libraryManagerCookie <> 0 Then Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then objectManager.UnregisterLibrary(Me._libraryManagerCookie) Me._libraryManagerCookie = 0 End If Me._libraryManager.Dispose() Me._libraryManager = Nothing End If End Function Public Function NeedExport(pageID As String, <Out> ByRef needExportParam As Integer) As Integer Implements IVsUserSettingsQuery.NeedExport ' We need to override MPF's definition of NeedExport since it doesn't know about our automation object needExportParam = If(pageID = "TextEditor.Basic-Specific", 1, 0) Return VSConstants.S_OK End Function Protected Overrides Function GetAutomationObject(name As String) As Object If name = "Basic-Specific" Then Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Return New AutomationObject(workspace) End If Return MyBase.GetAutomationObject(name) End Function Protected Overrides Function CreateEditorFactories() As IEnumerable(Of IVsEditorFactory) Dim editorFactory = New VisualBasicEditorFactory(Me.ComponentModel) Dim codePageEditorFactory = New VisualBasicCodePageEditorFactory(editorFactory) Return {editorFactory, codePageEditorFactory} End Function Protected Overrides Function CreateLanguageService() As VisualBasicLanguageService Return New VisualBasicLanguageService(Me) End Function Protected Overrides Sub RegisterMiscellaneousFilesWorkspaceInformation(miscellaneousFilesWorkspace As MiscellaneousFilesWorkspace) miscellaneousFilesWorkspace.RegisterLanguage( Guids.VisualBasicLanguageServiceId, LanguageNames.VisualBasic, ".vbx") End Sub Protected Overrides ReadOnly Property RoslynLanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.ErrorReporting Imports Microsoft.VisualStudio.LanguageServices.Implementation Imports Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ObjectBrowser Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Options.Formatting Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.Interop Imports Task = System.Threading.Tasks.Task Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic ' The option page configuration is duplicated in PackageRegistration.pkgdef. ' ' VB option pages tree ' Basic ' General (from editor) ' Scroll Bars (from editor) ' Tabs (from editor) ' Advanced ' Code Style (category) ' General <ProvideLanguageEditorOptionPage(GetType(AdvancedOptionPage), "Basic", Nothing, "Advanced", "#102", 10160)> <ProvideLanguageEditorToolsOptionCategory("Basic", "Code Style", "#109")> <ProvideLanguageEditorOptionPage(GetType(CodeStylePage), "Basic", "Code Style", "General", "#111", 10161)> <ProvideLanguageEditorOptionPage(GetType(NamingStylesOptionPage), "Basic", "Code Style", "Naming", "#110", 10162)> <ProvideLanguageEditorOptionPage(GetType(IntelliSenseOptionPage), "Basic", Nothing, "IntelliSense", "#112", 312)> <Guid(Guids.VisualBasicPackageIdString)> Friend NotInheritable Class VisualBasicPackage Inherits AbstractPackage(Of VisualBasicPackage, VisualBasicLanguageService) Implements IVbCompilerService Implements IVsUserSettingsQuery ' The property page for WinForms project has a special interface that it uses to get ' entry points that are Forms: IVbEntryPointProvider. The semantics for this ' interface are the same as VisualBasicProject::GetFormEntryPoints, but callers get ' the VB Package and cast it to IVbEntryPointProvider. The property page is managed ' and we've redefined the interface, so we have to register a COM aggregate of the ' VB package. This is the same pattern we use for the LanguageService and Razor. Private ReadOnly _comAggregate As Object Private _libraryManager As ObjectBrowserLibraryManager Private _libraryManagerCookie As UInteger Public Sub New() MyBase.New() _comAggregate = Interop.ComAggregate.CreateAggregatedObject(Me) End Sub Protected Overrides Async Function InitializeAsync(cancellationToken As CancellationToken, progress As IProgress(Of ServiceProgressData)) As Task Try Await MyBase.InitializeAsync(cancellationToken, progress).ConfigureAwait(True) Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) RegisterLanguageService(GetType(IVbCompilerService), Function() Task.FromResult(_comAggregate)) RegisterService(Of IVbTempPECompilerFactory)( Async Function(ct) Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(ct) Return New TempPECompilerFactory(workspace) End Function) Catch ex As Exception When FatalError.ReportAndPropagateUnlessCanceled(ex) Throw ExceptionUtilities.Unreachable End Try End Function Protected Overrides Async Function RegisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Dim workspace As VisualStudioWorkspace = ComponentModel.GetService(Of VisualStudioWorkspace)() Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then Me._libraryManager = New ObjectBrowserLibraryManager(Me, ComponentModel, workspace) If ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(Me._libraryManager, Me._libraryManagerCookie)) Then Me._libraryManagerCookie = 0 End If End If End Function Protected Overrides Async Function UnregisterObjectBrowserLibraryManagerAsync(cancellationToken As CancellationToken) As Task Await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken) If _libraryManagerCookie <> 0 Then Dim objectManager = TryCast(Await GetServiceAsync(GetType(SVsObjectManager)).ConfigureAwait(True), IVsObjectManager2) If objectManager IsNot Nothing Then objectManager.UnregisterLibrary(Me._libraryManagerCookie) Me._libraryManagerCookie = 0 End If Me._libraryManager.Dispose() Me._libraryManager = Nothing End If End Function Public Function NeedExport(pageID As String, <Out> ByRef needExportParam As Integer) As Integer Implements IVsUserSettingsQuery.NeedExport ' We need to override MPF's definition of NeedExport since it doesn't know about our automation object needExportParam = If(pageID = "TextEditor.Basic-Specific", 1, 0) Return VSConstants.S_OK End Function Protected Overrides Function GetAutomationObject(name As String) As Object If name = "Basic-Specific" Then Dim workspace = Me.ComponentModel.GetService(Of VisualStudioWorkspace)() Return New AutomationObject(workspace) End If Return MyBase.GetAutomationObject(name) End Function Protected Overrides Function CreateEditorFactories() As IEnumerable(Of IVsEditorFactory) Dim editorFactory = New VisualBasicEditorFactory(Me.ComponentModel) Dim codePageEditorFactory = New VisualBasicCodePageEditorFactory(editorFactory) Return {editorFactory, codePageEditorFactory} End Function Protected Overrides Function CreateLanguageService() As VisualBasicLanguageService Return New VisualBasicLanguageService(Me) End Function Protected Overrides Sub RegisterMiscellaneousFilesWorkspaceInformation(miscellaneousFilesWorkspace As MiscellaneousFilesWorkspace) miscellaneousFilesWorkspace.RegisterLanguage( Guids.VisualBasicLanguageServiceId, LanguageNames.VisualBasic, ".vbx") End Sub Protected Overrides ReadOnly Property RoslynLanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1